1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1148 2011/12/14 16:16:50 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
85: %courseownerbuf, %coursetypebuf,$locknum);
86:
87: use IO::Socket;
88: use GDBM_File;
89: use HTML::LCParser;
90: use Fcntl qw(:flock);
91: use Storable qw(thaw nfreeze);
92: use Time::HiRes qw( gettimeofday tv_interval );
93: use Cache::Memcached;
94: use Digest::MD5;
95: use Math::Random;
96: use File::MMagic;
97: use LONCAPA qw(:DEFAULT :match);
98: use LONCAPA::Configuration;
99:
100: use File::Copy;
101:
102: my $readit;
103: my $max_connection_retries = 10; # Or some such value.
104:
105: require Exporter;
106:
107: our @ISA = qw (Exporter);
108: our @EXPORT = qw(%env);
109:
110:
111: # --------------------------------------------------------------------- Logging
112: {
113: my $logid;
114: sub instructor_log {
115: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
116: if (($cnum eq '') || ($cdom eq '')) {
117: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
119: }
120: $logid++;
121: my $now = time();
122: my $id=$now.'00000'.$$.'00000'.$logid;
123: return &Apache::lonnet::put('nohist_'.$hash_name,
124: { $id => {
125: 'exe_uname' => $env{'user.name'},
126: 'exe_udom' => $env{'user.domain'},
127: 'exe_time' => $now,
128: 'exe_ip' => $ENV{'REMOTE_ADDR'},
129: 'delflag' => $delflag,
130: 'logentry' => $storehash,
131: 'uname' => $uname,
132: 'udom' => $udom,
133: }
134: },$cdom,$cnum);
135: }
136: }
137:
138: sub logtouch {
139: my $execdir=$perlvar{'lonDaemons'};
140: unless (-e "$execdir/logs/lonnet.log") {
141: open(my $fh,">>$execdir/logs/lonnet.log");
142: close $fh;
143: }
144: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
145: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
146: }
147:
148: sub logthis {
149: my $message=shift;
150: my $execdir=$perlvar{'lonDaemons'};
151: my $now=time;
152: my $local=localtime($now);
153: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
154: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
155: print $fh $logstring;
156: close($fh);
157: }
158: return 1;
159: }
160:
161: sub logperm {
162: my $message=shift;
163: my $execdir=$perlvar{'lonDaemons'};
164: my $now=time;
165: my $local=localtime($now);
166: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
167: print $fh "$now:$message:$local\n";
168: close($fh);
169: }
170: return 1;
171: }
172:
173: sub create_connection {
174: my ($hostname,$lonid) = @_;
175: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
176: Type => SOCK_STREAM,
177: Timeout => 10);
178: return 0 if (!$client);
179: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
180: my $result = <$client>;
181: chomp($result);
182: return 1 if ($result eq 'done');
183: return 0;
184: }
185:
186: sub get_server_timezone {
187: my ($cnum,$cdom) = @_;
188: my $home=&homeserver($cnum,$cdom);
189: if ($home ne 'no_host') {
190: my $cachetime = 24*3600;
191: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
192: if (defined($cached)) {
193: return $timezone;
194: } else {
195: my $timezone = &reply('servertimezone',$home);
196: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
197: }
198: }
199: }
200:
201: sub get_server_distarch {
202: my ($lonhost,$ignore_cache) = @_;
203: if (defined($lonhost)) {
204: if (!defined(&hostname($lonhost))) {
205: return;
206: }
207: my $cachetime = 12*3600;
208: if (!$ignore_cache) {
209: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
210: if (defined($cached)) {
211: return $distarch;
212: }
213: }
214: my $rep = &reply('serverdistarch',$lonhost);
215: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
216: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
217: $rep eq '') {
218: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
219: }
220: }
221: return;
222: }
223:
224: sub get_server_loncaparev {
225: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
226: if (defined($lonhost)) {
227: if (!defined(&hostname($lonhost))) {
228: undef($lonhost);
229: }
230: }
231: if (!defined($lonhost)) {
232: if (defined(&domain($dom,'primary'))) {
233: $lonhost=&domain($dom,'primary');
234: if ($lonhost eq 'no_host') {
235: undef($lonhost);
236: }
237: }
238: }
239: if (defined($lonhost)) {
240: my $cachetime = 12*3600;
241: if (!$ignore_cache) {
242: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
243: if (defined($cached)) {
244: return $loncaparev;
245: }
246: }
247: my ($answer,$loncaparev);
248: my @ids=¤t_machine_ids();
249: if (grep(/^\Q$lonhost\E$/,@ids)) {
250: $answer = $perlvar{'lonVersion'};
251: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
252: $loncaparev = $1;
253: }
254: } else {
255: $answer = &reply('serverloncaparev',$lonhost);
256: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
257: if ($caller eq 'loncron') {
258: my $ua=new LWP::UserAgent;
259: $ua->timeout(4);
260: my $protocol = $protocol{$lonhost};
261: $protocol = 'http' if ($protocol ne 'https');
262: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
263: my $request=new HTTP::Request('GET',$url);
264: my $response=$ua->request($request);
265: unless ($response->is_error()) {
266: my $content = $response->content;
267: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
268: $loncaparev = $1;
269: }
270: }
271: } else {
272: $loncaparev = $loncaparevs{$lonhost};
273: }
274: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
275: $loncaparev = $1;
276: }
277: }
278: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
279: }
280: }
281:
282: sub get_server_homeID {
283: my ($hostname,$ignore_cache,$caller) = @_;
284: unless ($ignore_cache) {
285: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
286: if (defined($cached)) {
287: return $serverhomeID;
288: }
289: }
290: my $cachetime = 12*3600;
291: my $serverhomeID;
292: if ($caller eq 'loncron') {
293: my @machine_ids = &machine_ids($hostname);
294: foreach my $id (@machine_ids) {
295: my $response = &reply('serverhomeID',$id);
296: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
297: $serverhomeID = $response;
298: last;
299: }
300: }
301: if ($serverhomeID eq '') {
302: $serverhomeID = $machine_ids[-1];
303: }
304: } else {
305: $serverhomeID = $serverhomeIDs{$hostname};
306: }
307: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
308: }
309:
310: sub get_remote_globals {
311: my ($lonhost,$whathash,$ignore_cache) = @_;
312: my ($result,%returnhash,%whatneeded);
313: if (ref($whathash) eq 'HASH') {
314: foreach my $what (sort(keys(%{$whathash}))) {
315: my $hashid = $lonhost.'-'.$what;
316: my ($response,$cached);
317: unless ($ignore_cache) {
318: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
319: }
320: if (defined($cached)) {
321: $returnhash{$what} = $response;
322: } else {
323: $whatneeded{$what} = 1;
324: }
325: }
326: if (keys(%whatneeded) == 0) {
327: $result = 'ok';
328: } else {
329: my $requested = &freeze_escape(\%whatneeded);
330: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
331: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
332: ($rep eq 'unknown_cmd')) {
333: $result = $rep;
334: } else {
335: $result = 'ok';
336: my @pairs=split(/\&/,$rep);
337: foreach my $item (@pairs) {
338: my ($key,$value)=split(/=/,$item,2);
339: my $what = &unescape($key);
340: my $hashid = $lonhost.'-'.$what;
341: $returnhash{$what}=&thaw_unescape($value);
342: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
343: }
344: }
345: }
346: }
347: return ($result,\%returnhash);
348: }
349:
350: sub remote_devalidate_cache {
351: my ($lonhost,$name,$id) = @_;
352: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
353: return $response;
354: }
355:
356: # -------------------------------------------------- Non-critical communication
357: sub subreply {
358: my ($cmd,$server)=@_;
359: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
360: #
361: # With loncnew process trimming, there's a timing hole between lonc server
362: # process exit and the master server picking up the listen on the AF_UNIX
363: # socket. In that time interval, a lock file will exist:
364:
365: my $lockfile=$peerfile.".lock";
366: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
367: sleep(1);
368: }
369: # At this point, either a loncnew parent is listening or an old lonc
370: # or loncnew child is listening so we can connect or everything's dead.
371: #
372: # We'll give the connection a few tries before abandoning it. If
373: # connection is not possible, we'll con_lost back to the client.
374: #
375: my $client;
376: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
377: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
378: Type => SOCK_STREAM,
379: Timeout => 10);
380: if ($client) {
381: last; # Connected!
382: } else {
383: &create_connection(&hostname($server),$server);
384: }
385: sleep(1); # Try again later if failed connection.
386: }
387: my $answer;
388: if ($client) {
389: print $client "sethost:$server:$cmd\n";
390: $answer=<$client>;
391: if (!$answer) { $answer="con_lost"; }
392: chomp($answer);
393: } else {
394: $answer = 'con_lost'; # Failed connection.
395: }
396: return $answer;
397: }
398:
399: sub reply {
400: my ($cmd,$server)=@_;
401: unless (defined(&hostname($server))) { return 'no_such_host'; }
402: my $answer=subreply($cmd,$server);
403: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
404: &logthis("<font color=\"blue\">WARNING:".
405: " $cmd to $server returned $answer</font>");
406: }
407: return $answer;
408: }
409:
410: # ----------------------------------------------------------- Send USR1 to lonc
411:
412: sub reconlonc {
413: my ($lonid) = @_;
414: my $hostname = &hostname($lonid);
415: if ($lonid) {
416: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
417: if ($hostname && -e $peerfile) {
418: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
419: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
420: Type => SOCK_STREAM,
421: Timeout => 10);
422: if ($client) {
423: print $client ("reset_retries\n");
424: my $answer=<$client>;
425: #reset just this one.
426: }
427: }
428: return;
429: }
430:
431: &logthis("Trying to reconnect lonc");
432: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
433: if (open(my $fh,"<$loncfile")) {
434: my $loncpid=<$fh>;
435: chomp($loncpid);
436: if (kill 0 => $loncpid) {
437: &logthis("lonc at pid $loncpid responding, sending USR1");
438: kill USR1 => $loncpid;
439: sleep 1;
440: } else {
441: &logthis(
442: "<font color=\"blue\">WARNING:".
443: " lonc at pid $loncpid not responding, giving up</font>");
444: }
445: } else {
446: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
447: }
448: }
449:
450: # ------------------------------------------------------ Critical communication
451:
452: sub critical {
453: my ($cmd,$server)=@_;
454: unless (&hostname($server)) {
455: &logthis("<font color=\"blue\">WARNING:".
456: " Critical message to unknown server ($server)</font>");
457: return 'no_such_host';
458: }
459: my $answer=reply($cmd,$server);
460: if ($answer eq 'con_lost') {
461: &reconlonc("$perlvar{'lonSockDir'}/$server");
462: my $answer=reply($cmd,$server);
463: if ($answer eq 'con_lost') {
464: my $now=time;
465: my $middlename=$cmd;
466: $middlename=substr($middlename,0,16);
467: $middlename=~s/\W//g;
468: my $dfilename=
469: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
470: $dumpcount++;
471: {
472: my $dfh;
473: if (open($dfh,">$dfilename")) {
474: print $dfh "$cmd\n";
475: close($dfh);
476: }
477: }
478: sleep 2;
479: my $wcmd='';
480: {
481: my $dfh;
482: if (open($dfh,"<$dfilename")) {
483: $wcmd=<$dfh>;
484: close($dfh);
485: }
486: }
487: chomp($wcmd);
488: if ($wcmd eq $cmd) {
489: &logthis("<font color=\"blue\">WARNING: ".
490: "Connection buffer $dfilename: $cmd</font>");
491: &logperm("D:$server:$cmd");
492: return 'con_delayed';
493: } else {
494: &logthis("<font color=\"red\">CRITICAL:"
495: ." Critical connection failed: $server $cmd</font>");
496: &logperm("F:$server:$cmd");
497: return 'con_failed';
498: }
499: }
500: }
501: return $answer;
502: }
503:
504: # ------------------------------------------- check if return value is an error
505:
506: sub error {
507: my ($result) = @_;
508: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
509: if ($2 == 2) { return undef; }
510: return $1;
511: }
512: return undef;
513: }
514:
515: sub convert_and_load_session_env {
516: my ($lonidsdir,$handle)=@_;
517: my @profile;
518: {
519: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
520: if (!$opened) {
521: return 0;
522: }
523: flock($idf,LOCK_SH);
524: @profile=<$idf>;
525: close($idf);
526: }
527: my %temp_env;
528: foreach my $line (@profile) {
529: if ($line !~ m/=/) {
530: return 0;
531: }
532: chomp($line);
533: my ($envname,$envvalue)=split(/=/,$line,2);
534: $temp_env{&unescape($envname)} = &unescape($envvalue);
535: }
536: unlink("$lonidsdir/$handle.id");
537: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
538: 0640)) {
539: %disk_env = %temp_env;
540: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
541: untie(%disk_env);
542: }
543: return 1;
544: }
545:
546: # ------------------------------------------- Transfer profile into environment
547: my $env_loaded;
548: sub transfer_profile_to_env {
549: my ($lonidsdir,$handle,$force_transfer) = @_;
550: if (!$force_transfer && $env_loaded) { return; }
551:
552: if (!defined($lonidsdir)) {
553: $lonidsdir = $perlvar{'lonIDsDir'};
554: }
555: if (!defined($handle)) {
556: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
557: }
558:
559: my $convert;
560: {
561: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
562: if (!$opened) {
563: return;
564: }
565: flock($idf,LOCK_SH);
566: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
567: &GDBM_READER(),0640)) {
568: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
569: untie(%disk_env);
570: } else {
571: $convert = 1;
572: }
573: }
574: if ($convert) {
575: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
576: &logthis("Failed to load session, or convert session.");
577: }
578: }
579:
580: my %remove;
581: while ( my $envname = each(%env) ) {
582: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
583: if ($time < time-300) {
584: $remove{$key}++;
585: }
586: }
587: }
588:
589: $env{'user.environment'} = "$lonidsdir/$handle.id";
590: $env_loaded=1;
591: foreach my $expired_key (keys(%remove)) {
592: &delenv($expired_key);
593: }
594: }
595:
596: # ---------------------------------------------------- Check for valid session
597: sub check_for_valid_session {
598: my ($r) = @_;
599: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
600: my $lonid=$cookies{'lonID'};
601: return undef if (!$lonid);
602:
603: my $handle=&LONCAPA::clean_handle($lonid->value);
604: my $lonidsdir=$r->dir_config('lonIDsDir');
605: return undef if (!-e "$lonidsdir/$handle.id");
606:
607: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
608: return undef if (!$opened);
609:
610: flock($idf,LOCK_SH);
611: my %disk_env;
612: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
613: &GDBM_READER(),0640)) {
614: return undef;
615: }
616:
617: if (!defined($disk_env{'user.name'})
618: || !defined($disk_env{'user.domain'})) {
619: return undef;
620: }
621: return $handle;
622: }
623:
624: sub timed_flock {
625: my ($file,$lock_type) = @_;
626: my $failed=0;
627: eval {
628: local $SIG{__DIE__}='DEFAULT';
629: local $SIG{ALRM}=sub {
630: $failed=1;
631: die("failed lock");
632: };
633: alarm(13);
634: flock($file,$lock_type);
635: alarm(0);
636: };
637: if ($failed) {
638: return undef;
639: } else {
640: return 1;
641: }
642: }
643:
644: # ---------------------------------------------------------- Append Environment
645:
646: sub appenv {
647: my ($newenv,$roles) = @_;
648: if (ref($newenv) eq 'HASH') {
649: foreach my $key (keys(%{$newenv})) {
650: my $refused = 0;
651: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
652: $refused = 1;
653: if (ref($roles) eq 'ARRAY') {
654: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
655: if (grep(/^\Q$role\E$/,@{$roles})) {
656: $refused = 0;
657: }
658: }
659: }
660: if ($refused) {
661: &logthis("<font color=\"blue\">WARNING: ".
662: "Attempt to modify environment ".$key." to ".$newenv->{$key}
663: .'</font>');
664: delete($newenv->{$key});
665: } else {
666: $env{$key}=$newenv->{$key};
667: }
668: }
669: my $opened = open(my $env_file,'+<',$env{'user.environment'});
670: if ($opened
671: && &timed_flock($env_file,LOCK_EX)
672: &&
673: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
674: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
675: while (my ($key,$value) = each(%{$newenv})) {
676: $disk_env{$key} = $value;
677: }
678: untie(%disk_env);
679: }
680: }
681: return 'ok';
682: }
683: # ----------------------------------------------------- Delete from Environment
684:
685: sub delenv {
686: my ($delthis,$regexp,$roles) = @_;
687: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
688: my $refused = 1;
689: if (ref($roles) eq 'ARRAY') {
690: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
691: if (grep(/^\Q$role\E$/,@{$roles})) {
692: $refused = 0;
693: }
694: }
695: if ($refused) {
696: &logthis("<font color=\"blue\">WARNING: ".
697: "Attempt to delete from environment ".$delthis);
698: return 'error';
699: }
700: }
701: my $opened = open(my $env_file,'+<',$env{'user.environment'});
702: if ($opened
703: && &timed_flock($env_file,LOCK_EX)
704: &&
705: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
706: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
707: foreach my $key (keys(%disk_env)) {
708: if ($regexp) {
709: if ($key=~/^$delthis/) {
710: delete($env{$key});
711: delete($disk_env{$key});
712: }
713: } else {
714: if ($key=~/^\Q$delthis\E/) {
715: delete($env{$key});
716: delete($disk_env{$key});
717: }
718: }
719: }
720: untie(%disk_env);
721: }
722: return 'ok';
723: }
724:
725: sub get_env_multiple {
726: my ($name) = @_;
727: my @values;
728: if (defined($env{$name})) {
729: # exists is it an array
730: if (ref($env{$name})) {
731: @values=@{ $env{$name} };
732: } else {
733: $values[0]=$env{$name};
734: }
735: }
736: return(@values);
737: }
738:
739: # ------------------------------------------------------------------- Locking
740:
741: sub set_lock {
742: my ($text)=@_;
743: $locknum++;
744: my $id=$$.'-'.$locknum;
745: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
746: 'session.lock.'.$id => $text});
747: return $id;
748: }
749:
750: sub get_locks {
751: my $num=0;
752: my %texts=();
753: foreach my $lock (split(/\,/,$env{'session.locks'})) {
754: if ($lock=~/\w/) {
755: $num++;
756: $texts{$lock}=$env{'session.lock.'.$lock};
757: }
758: }
759: return ($num,%texts);
760: }
761:
762: sub remove_lock {
763: my ($id)=@_;
764: my $newlocks='';
765: foreach my $lock (split(/\,/,$env{'session.locks'})) {
766: if (($lock=~/\w/) && ($lock ne $id)) {
767: $newlocks.=','.$lock;
768: }
769: }
770: &appenv({'session.locks' => $newlocks});
771: &delenv('session.lock.'.$id);
772: }
773:
774: sub remove_all_locks {
775: my $activelocks=$env{'session.locks'};
776: foreach my $lock (split(/\,/,$env{'session.locks'})) {
777: if ($lock=~/\w/) {
778: &remove_lock($lock);
779: }
780: }
781: }
782:
783:
784: # ------------------------------------------ Find out current server userload
785: sub userload {
786: my $numusers=0;
787: {
788: opendir(LONIDS,$perlvar{'lonIDsDir'});
789: my $filename;
790: my $curtime=time;
791: while ($filename=readdir(LONIDS)) {
792: next if ($filename eq '.' || $filename eq '..');
793: next if ($filename =~ /publicuser_\d+\.id/);
794: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
795: if ($curtime-$mtime < 1800) { $numusers++; }
796: }
797: closedir(LONIDS);
798: }
799: my $userloadpercent=0;
800: my $maxuserload=$perlvar{'lonUserLoadLim'};
801: if ($maxuserload) {
802: $userloadpercent=100*$numusers/$maxuserload;
803: }
804: $userloadpercent=sprintf("%.2f",$userloadpercent);
805: return $userloadpercent;
806: }
807:
808: # ------------------------------ Find server with least workload from spare.tab
809:
810: sub spareserver {
811: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
812: my $spare_server;
813: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
814: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
815: : $userloadpercent;
816: my ($uint_dom,$remotesessions);
817: if (($udom ne '') && (&domain($udom) ne '')) {
818: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
819: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
820: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
821: $remotesessions = $udomdefaults{'remotesessions'};
822: }
823: my $spareshash = &this_host_spares($udom);
824: if (ref($spareshash) eq 'HASH') {
825: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
826: foreach my $try_server (@{ $spareshash->{'primary'} }) {
827: if ($uint_dom) {
828: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
829: $try_server));
830: }
831: ($spare_server, $lowest_load) =
832: &compare_server_load($try_server, $spare_server, $lowest_load);
833: }
834: }
835:
836: my $found_server = ($spare_server ne '' && $lowest_load < 100);
837:
838: if (!$found_server) {
839: if (ref($spareshash->{'default'}) eq 'ARRAY') {
840: foreach my $try_server (@{ $spareshash->{'default'} }) {
841: if ($uint_dom) {
842: next unless (&spare_can_host($udom,$uint_dom,
843: $remotesessions,$try_server));
844: }
845: ($spare_server, $lowest_load) =
846: &compare_server_load($try_server, $spare_server, $lowest_load);
847: }
848: }
849: }
850: }
851:
852: if (!$want_server_name) {
853: my $protocol = 'http';
854: if ($protocol{$spare_server} eq 'https') {
855: $protocol = $protocol{$spare_server};
856: }
857: if (defined($spare_server)) {
858: my $hostname = &hostname($spare_server);
859: if (defined($hostname)) {
860: $spare_server = $protocol.'://'.$hostname;
861: }
862: }
863: }
864: return $spare_server;
865: }
866:
867: sub compare_server_load {
868: my ($try_server, $spare_server, $lowest_load) = @_;
869:
870: my $loadans = &reply('load', $try_server);
871: my $userloadans = &reply('userload',$try_server);
872:
873: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
874: return ($spare_server, $lowest_load); #didn't get a number from the server
875: }
876:
877: my $load;
878: if ($loadans =~ /\d/) {
879: if ($userloadans =~ /\d/) {
880: #both are numbers, pick the bigger one
881: $load = ($loadans > $userloadans) ? $loadans
882: : $userloadans;
883: } else {
884: $load = $loadans;
885: }
886: } else {
887: $load = $userloadans;
888: }
889:
890: if (($load =~ /\d/) && ($load < $lowest_load)) {
891: $spare_server = $try_server;
892: $lowest_load = $load;
893: }
894: return ($spare_server,$lowest_load);
895: }
896:
897: # --------------------------- ask offload servers if user already has a session
898: sub find_existing_session {
899: my ($udom,$uname) = @_;
900: my $spareshash = &this_host_spares($udom);
901: if (ref($spareshash) eq 'HASH') {
902: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
903: foreach my $try_server (@{ $spareshash->{'primary'} }) {
904: return $try_server if (&has_user_session($try_server, $udom, $uname));
905: }
906: }
907: if (ref($spareshash->{'default'}) eq 'ARRAY') {
908: foreach my $try_server (@{ $spareshash->{'default'} }) {
909: return $try_server if (&has_user_session($try_server, $udom, $uname));
910: }
911: }
912: }
913: return;
914: }
915:
916: # -------------------------------- ask if server already has a session for user
917: sub has_user_session {
918: my ($lonid,$udom,$uname) = @_;
919: my $result = &reply(join(':','userhassession',
920: map {&escape($_)} ($udom,$uname)),$lonid);
921: return 1 if ($result eq 'ok');
922:
923: return 0;
924: }
925:
926: # --------- determine least loaded server in a user's domain which allows login
927:
928: sub choose_server {
929: my ($udom,$checkloginvia) = @_;
930: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
931: my %servers = &get_servers($udom);
932: my $lowest_load = 30000;
933: my ($login_host,$hostname,$portal_path);
934: foreach my $lonhost (keys(%servers)) {
935: my $loginvia;
936: if ($checkloginvia) {
937: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
938: if ($loginvia) {
939: my ($server,$path) = split(/:/,$loginvia);
940: ($login_host, $lowest_load) =
941: &compare_server_load($server, $login_host, $lowest_load);
942: if ($login_host eq $server) {
943: $portal_path = $path;
944: }
945: } else {
946: ($login_host, $lowest_load) =
947: &compare_server_load($lonhost, $login_host, $lowest_load);
948: if ($login_host eq $lonhost) {
949: $portal_path = '';
950: }
951: }
952: } else {
953: ($login_host, $lowest_load) =
954: &compare_server_load($lonhost, $login_host, $lowest_load);
955: }
956: }
957: if ($login_host ne '') {
958: $hostname = &hostname($login_host);
959: }
960: return ($login_host,$hostname,$portal_path);
961: }
962:
963: # --------------------------------------------- Try to change a user's password
964:
965: sub changepass {
966: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
967: $currentpass = &escape($currentpass);
968: $newpass = &escape($newpass);
969: my $lonhost = $perlvar{'lonHostID'};
970: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
971: $server);
972: if (! $answer) {
973: &logthis("No reply on password change request to $server ".
974: "by $uname in domain $udom.");
975: } elsif ($answer =~ "^ok") {
976: &logthis("$uname in $udom successfully changed their password ".
977: "on $server.");
978: } elsif ($answer =~ "^pwchange_failure") {
979: &logthis("$uname in $udom was unable to change their password ".
980: "on $server. The action was blocked by either lcpasswd ".
981: "or pwchange");
982: } elsif ($answer =~ "^non_authorized") {
983: &logthis("$uname in $udom did not get their password correct when ".
984: "attempting to change it on $server.");
985: } elsif ($answer =~ "^auth_mode_error") {
986: &logthis("$uname in $udom attempted to change their password despite ".
987: "not being locally or internally authenticated on $server.");
988: } elsif ($answer =~ "^unknown_user") {
989: &logthis("$uname in $udom attempted to change their password ".
990: "on $server but were unable to because $server is not ".
991: "their home server.");
992: } elsif ($answer =~ "^refused") {
993: &logthis("$server refused to change $uname in $udom password because ".
994: "it was sent an unencrypted request to change the password.");
995: } elsif ($answer =~ "invalid_client") {
996: &logthis("$server refused to change $uname in $udom password because ".
997: "it was a reset by e-mail originating from an invalid server.");
998: }
999: return $answer;
1000: }
1001:
1002: # ----------------------- Try to determine user's current authentication scheme
1003:
1004: sub queryauthenticate {
1005: my ($uname,$udom)=@_;
1006: my $uhome=&homeserver($uname,$udom);
1007: if (!$uhome) {
1008: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1009: return 'no_host';
1010: }
1011: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1012: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1013: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1014: }
1015: return $answer;
1016: }
1017:
1018: # --------- Try to authenticate user from domain's lib servers (first this one)
1019:
1020: sub authenticate {
1021: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1022: $upass=&escape($upass);
1023: $uname= &LONCAPA::clean_username($uname);
1024: my $uhome=&homeserver($uname,$udom,1);
1025: my $newhome;
1026: if ((!$uhome) || ($uhome eq 'no_host')) {
1027: # Maybe the machine was offline and only re-appeared again recently?
1028: &reconlonc();
1029: # One more
1030: $uhome=&homeserver($uname,$udom,1);
1031: if (($uhome eq 'no_host') && $checkdefauth) {
1032: if (defined(&domain($udom,'primary'))) {
1033: $newhome=&domain($udom,'primary');
1034: }
1035: if ($newhome ne '') {
1036: $uhome = $newhome;
1037: }
1038: }
1039: if ((!$uhome) || ($uhome eq 'no_host')) {
1040: &logthis("User $uname at $udom is unknown in authenticate");
1041: return 'no_host';
1042: }
1043: }
1044: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1045: if ($answer eq 'authorized') {
1046: if ($newhome) {
1047: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1048: return 'no_account_on_host';
1049: } else {
1050: &logthis("User $uname at $udom authorized by $uhome");
1051: return $uhome;
1052: }
1053: }
1054: if ($answer eq 'non_authorized') {
1055: &logthis("User $uname at $udom rejected by $uhome");
1056: return 'no_host';
1057: }
1058: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1059: return 'no_host';
1060: }
1061:
1062: sub can_host_session {
1063: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1064: my $canhost = 1;
1065: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1066: if (ref($remotesessions) eq 'HASH') {
1067: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1068: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1069: $canhost = 0;
1070: } else {
1071: $canhost = 1;
1072: }
1073: }
1074: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1075: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1076: $canhost = 1;
1077: } else {
1078: $canhost = 0;
1079: }
1080: }
1081: if ($canhost) {
1082: if ($remotesessions->{'version'} ne '') {
1083: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1084: if ($reqmajor ne '' && $reqminor ne '') {
1085: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1086: my $major = $1;
1087: my $minor = $2;
1088: if (($major < $reqmajor ) ||
1089: (($major == $reqmajor) && ($minor < $reqminor))) {
1090: $canhost = 0;
1091: }
1092: } else {
1093: $canhost = 0;
1094: }
1095: }
1096: }
1097: }
1098: }
1099: if ($canhost) {
1100: if (ref($hostedsessions) eq 'HASH') {
1101: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1102: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1103: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1104: if (($uint_dom ne '') &&
1105: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1106: $canhost = 0;
1107: } else {
1108: $canhost = 1;
1109: }
1110: }
1111: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1112: if (($uint_dom ne '') &&
1113: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1114: $canhost = 1;
1115: } else {
1116: $canhost = 0;
1117: }
1118: }
1119: }
1120: }
1121: return $canhost;
1122: }
1123:
1124: sub spare_can_host {
1125: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1126: my $canhost=1;
1127: my @intdoms;
1128: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1129: if (ref($internet_names) eq 'ARRAY') {
1130: @intdoms = @{$internet_names};
1131: }
1132: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1133: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1134: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1135: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1136: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1137: $canhost = &can_host_session($udom,$try_server,$remoterev,
1138: $remotesessions,
1139: $defdomdefaults{'hostedsessions'});
1140: }
1141: return $canhost;
1142: }
1143:
1144: sub this_host_spares {
1145: my ($dom) = @_;
1146: my ($dom_in_use,$lonhost_in_use,$result);
1147: my @hosts = ¤t_machine_ids();
1148: foreach my $lonhost (@hosts) {
1149: if (&host_domain($lonhost) eq $dom) {
1150: $dom_in_use = $dom;
1151: $lonhost_in_use = $lonhost;
1152: last;
1153: }
1154: }
1155: if ($dom_in_use ne '') {
1156: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1157: }
1158: if (ref($result) ne 'HASH') {
1159: $lonhost_in_use = $perlvar{'lonHostID'};
1160: $dom_in_use = &host_domain($lonhost_in_use);
1161: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1162: if (ref($result) ne 'HASH') {
1163: $result = \%spareid;
1164: }
1165: }
1166: return $result;
1167: }
1168:
1169: sub spares_for_offload {
1170: my ($dom_in_use,$lonhost_in_use) = @_;
1171: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1172: if (defined($cached)) {
1173: return $result;
1174: } else {
1175: my $cachetime = 60*60*24;
1176: my %domconfig =
1177: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1178: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1179: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1180: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1181: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1182: }
1183: }
1184: }
1185: }
1186: return;
1187: }
1188:
1189: sub get_lonbalancer_config {
1190: my ($servers) = @_;
1191: my ($currbalancer,$currtargets);
1192: if (ref($servers) eq 'HASH') {
1193: foreach my $server (keys(%{$servers})) {
1194: my %what = (
1195: spareid => 1,
1196: perlvar => 1,
1197: );
1198: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1199: if ($result eq 'ok') {
1200: if (ref($returnhash) eq 'HASH') {
1201: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1202: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1203: $currbalancer = $server;
1204: $currtargets = {};
1205: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1206: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1207: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1208: }
1209: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1210: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1211: }
1212: }
1213: last;
1214: }
1215: }
1216: }
1217: }
1218: }
1219: }
1220: return ($currbalancer,$currtargets);
1221: }
1222:
1223: sub check_loadbalancing {
1224: my ($uname,$udom) = @_;
1225: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1226: $offloadto,$otherserver);
1227: my $lonhost = $perlvar{'lonHostID'};
1228: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1229: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1230: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1231: my $serverhomedom = &host_domain($lonhost);
1232:
1233: my $cachetime = 60*60*24;
1234:
1235: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1236: $dom_in_use = $udom;
1237: $homeintdom = 1;
1238: } else {
1239: $dom_in_use = $serverhomedom;
1240: }
1241: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1242: unless (defined($cached)) {
1243: my %domconfig =
1244: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1245: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1246: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1247: }
1248: }
1249: if (ref($result) eq 'HASH') {
1250: my $currbalancer = $result->{'lonhost'};
1251: my $currtargets = $result->{'targets'};
1252: my $currrules = $result->{'rules'};
1253: if ($currbalancer ne '') {
1254: my @hosts = ¤t_machine_ids();
1255: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1256: $is_balancer = 1;
1257: }
1258: }
1259: if ($is_balancer) {
1260: if (ref($currrules) eq 'HASH') {
1261: if ($homeintdom) {
1262: if ($uname ne '') {
1263: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1264: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1265: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1266: $rule_in_effect = $currrules->{'_LC_author'};
1267: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1268: $rule_in_effect = $currrules->{'_LC_adv'}
1269: }
1270: }
1271: if ($rule_in_effect eq '') {
1272: my %userenv = &userenvironment($udom,$uname,'inststatus');
1273: if ($userenv{'inststatus'} ne '') {
1274: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1275: my ($othertitle,$usertypes,$types) =
1276: &Apache::loncommon::sorted_inst_types($udom);
1277: if (ref($types) eq 'ARRAY') {
1278: foreach my $type (@{$types}) {
1279: if (grep(/^\Q$type\E$/,@statuses)) {
1280: if (exists($currrules->{$type})) {
1281: $rule_in_effect = $currrules->{$type};
1282: }
1283: }
1284: }
1285: }
1286: } else {
1287: if (exists($currrules->{'default'})) {
1288: $rule_in_effect = $currrules->{'default'};
1289: }
1290: }
1291: }
1292: } else {
1293: if (exists($currrules->{'default'})) {
1294: $rule_in_effect = $currrules->{'default'};
1295: }
1296: }
1297: } else {
1298: if ($currrules->{'_LC_external'} ne '') {
1299: $rule_in_effect = $currrules->{'_LC_external'};
1300: }
1301: }
1302: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1303: $uname,$udom);
1304: }
1305: }
1306: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1307: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1308: unless (defined($cached)) {
1309: my %domconfig =
1310: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1311: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1312: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1313: }
1314: }
1315: if (ref($result) eq 'HASH') {
1316: my $currbalancer = $result->{'lonhost'};
1317: my $currtargets = $result->{'targets'};
1318: my $currrules = $result->{'rules'};
1319:
1320: if ($currbalancer eq $lonhost) {
1321: $is_balancer = 1;
1322: if (ref($currrules) eq 'HASH') {
1323: if ($currrules->{'_LC_internetdom'} ne '') {
1324: $rule_in_effect = $currrules->{'_LC_internetdom'};
1325: }
1326: }
1327: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1328: $uname,$udom);
1329: }
1330: } else {
1331: if ($perlvar{'lonBalancer'} eq 'yes') {
1332: $is_balancer = 1;
1333: $offloadto = &this_host_spares($dom_in_use);
1334: }
1335: }
1336: } else {
1337: if ($perlvar{'lonBalancer'} eq 'yes') {
1338: $is_balancer = 1;
1339: $offloadto = &this_host_spares($dom_in_use);
1340: }
1341: }
1342: my $lowest_load = 30000;
1343: if (ref($offloadto) eq 'HASH') {
1344: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1345: foreach my $try_server (@{$offloadto->{'primary'}}) {
1346: ($otherserver,$lowest_load) =
1347: &compare_server_load($try_server,$otherserver,$lowest_load);
1348: }
1349: }
1350: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1351:
1352: if (!$found_server) {
1353: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1354: foreach my $try_server (@{$offloadto->{'default'}}) {
1355: ($otherserver,$lowest_load) =
1356: &compare_server_load($try_server,$otherserver,$lowest_load);
1357: }
1358: }
1359: }
1360: } elsif (ref($offloadto) eq 'ARRAY') {
1361: if (@{$offloadto} == 1) {
1362: $otherserver = $offloadto->[0];
1363: } elsif (@{$offloadto} > 1) {
1364: foreach my $try_server (@{$offloadto}) {
1365: ($otherserver,$lowest_load) =
1366: &compare_server_load($try_server,$otherserver,$lowest_load);
1367: }
1368: }
1369: }
1370: return ($is_balancer,$otherserver);
1371: }
1372:
1373: sub get_loadbalancer_targets {
1374: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1375: my $offloadto;
1376: if ($rule_in_effect eq '') {
1377: $offloadto = $currtargets;
1378: } else {
1379: if ($rule_in_effect eq 'homeserver') {
1380: my $homeserver = &homeserver($uname,$udom);
1381: if ($homeserver ne 'no_host') {
1382: $offloadto = [$homeserver];
1383: }
1384: } elsif ($rule_in_effect eq 'externalbalancer') {
1385: my %domconfig =
1386: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1387: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1388: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1389: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1390: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1391: }
1392: }
1393: } else {
1394: my %servers = &dom_servers($udom);
1395: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1396: if (&hostname($remotebalancer) ne '') {
1397: $offloadto = [$remotebalancer];
1398: }
1399: }
1400: } elsif (&hostname($rule_in_effect) ne '') {
1401: $offloadto = [$rule_in_effect];
1402: }
1403: }
1404: return $offloadto;
1405: }
1406:
1407: sub internet_dom_servers {
1408: my ($dom) = @_;
1409: my (%uniqservers,%servers);
1410: my $primaryserver = &hostname(&domain($dom,'primary'));
1411: my @machinedoms = &machine_domains($primaryserver);
1412: foreach my $mdom (@machinedoms) {
1413: my %currservers = %servers;
1414: my %server = &get_servers($mdom);
1415: %servers = (%currservers,%server);
1416: }
1417: my %by_hostname;
1418: foreach my $id (keys(%servers)) {
1419: push(@{$by_hostname{$servers{$id}}},$id);
1420: }
1421: foreach my $hostname (sort(keys(%by_hostname))) {
1422: if (@{$by_hostname{$hostname}} > 1) {
1423: my $match = 0;
1424: foreach my $id (@{$by_hostname{$hostname}}) {
1425: if (&host_domain($id) eq $dom) {
1426: $uniqservers{$id} = $hostname;
1427: $match = 1;
1428: }
1429: }
1430: unless ($match) {
1431: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1432: }
1433: } else {
1434: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1435: }
1436: }
1437: return %uniqservers;
1438: }
1439:
1440: # ---------------------- Find the homebase for a user from domain's lib servers
1441:
1442: my %homecache;
1443: sub homeserver {
1444: my ($uname,$udom,$ignoreBadCache)=@_;
1445: my $index="$uname:$udom";
1446:
1447: if (exists($homecache{$index})) { return $homecache{$index}; }
1448:
1449: my %servers = &get_servers($udom,'library');
1450: foreach my $tryserver (keys(%servers)) {
1451: next if ($ignoreBadCache ne 'true' &&
1452: exists($badServerCache{$tryserver}));
1453:
1454: my $answer=reply("home:$udom:$uname",$tryserver);
1455: if ($answer eq 'found') {
1456: delete($badServerCache{$tryserver});
1457: return $homecache{$index}=$tryserver;
1458: } elsif ($answer eq 'no_host') {
1459: $badServerCache{$tryserver}=1;
1460: }
1461: }
1462: return 'no_host';
1463: }
1464:
1465: # ------------------------------------- Find the usernames behind a list of IDs
1466:
1467: sub idget {
1468: my ($udom,@ids)=@_;
1469: my %returnhash=();
1470:
1471: my %servers = &get_servers($udom,'library');
1472: foreach my $tryserver (keys(%servers)) {
1473: my $idlist=join('&',@ids);
1474: $idlist=~tr/A-Z/a-z/;
1475: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1476: my @answer=();
1477: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1478: @answer=split(/\&/,$reply);
1479: } ;
1480: my $i;
1481: for ($i=0;$i<=$#ids;$i++) {
1482: if ($answer[$i]) {
1483: $returnhash{$ids[$i]}=$answer[$i];
1484: }
1485: }
1486: }
1487: return %returnhash;
1488: }
1489:
1490: # ------------------------------------- Find the IDs behind a list of usernames
1491:
1492: sub idrget {
1493: my ($udom,@unames)=@_;
1494: my %returnhash=();
1495: foreach my $uname (@unames) {
1496: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1497: }
1498: return %returnhash;
1499: }
1500:
1501: # ------------------------------- Store away a list of names and associated IDs
1502:
1503: sub idput {
1504: my ($udom,%ids)=@_;
1505: my %servers=();
1506: foreach my $uname (keys(%ids)) {
1507: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1508: my $uhom=&homeserver($uname,$udom);
1509: if ($uhom ne 'no_host') {
1510: my $id=&escape($ids{$uname});
1511: $id=~tr/A-Z/a-z/;
1512: my $esc_unam=&escape($uname);
1513: if ($servers{$uhom}) {
1514: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1515: } else {
1516: $servers{$uhom}=$id.'='.$esc_unam;
1517: }
1518: }
1519: }
1520: foreach my $server (keys(%servers)) {
1521: &critical('idput:'.$udom.':'.$servers{$server},$server);
1522: }
1523: }
1524:
1525: # ------------------------------dump from db file owned by domainconfig user
1526: sub dump_dom {
1527: my ($namespace,$udom,$regexp,$range)=@_;
1528: if (!$udom) {
1529: $udom=$env{'user.domain'};
1530: }
1531: my %returnhash;
1532: if ($udom) {
1533: my $uname = &get_domainconfiguser($udom);
1534: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1535: }
1536: return %returnhash;
1537: }
1538:
1539: # ------------------------------------------ get items from domain db files
1540:
1541: sub get_dom {
1542: my ($namespace,$storearr,$udom,$uhome)=@_;
1543: my $items='';
1544: foreach my $item (@$storearr) {
1545: $items.=&escape($item).'&';
1546: }
1547: $items=~s/\&$//;
1548: if (!$udom) {
1549: $udom=$env{'user.domain'};
1550: if (defined(&domain($udom,'primary'))) {
1551: $uhome=&domain($udom,'primary');
1552: } else {
1553: undef($uhome);
1554: }
1555: } else {
1556: if (!$uhome) {
1557: if (defined(&domain($udom,'primary'))) {
1558: $uhome=&domain($udom,'primary');
1559: }
1560: }
1561: }
1562: if ($udom && $uhome && ($uhome ne 'no_host')) {
1563: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1564: my %returnhash;
1565: if ($rep eq '' || $rep =~ /^error: 2 /) {
1566: return %returnhash;
1567: }
1568: my @pairs=split(/\&/,$rep);
1569: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1570: return @pairs;
1571: }
1572: my $i=0;
1573: foreach my $item (@$storearr) {
1574: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1575: $i++;
1576: }
1577: return %returnhash;
1578: } else {
1579: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1580: }
1581: }
1582:
1583: # -------------------------------------------- put items in domain db files
1584:
1585: sub put_dom {
1586: my ($namespace,$storehash,$udom,$uhome)=@_;
1587: if (!$udom) {
1588: $udom=$env{'user.domain'};
1589: if (defined(&domain($udom,'primary'))) {
1590: $uhome=&domain($udom,'primary');
1591: } else {
1592: undef($uhome);
1593: }
1594: } else {
1595: if (!$uhome) {
1596: if (defined(&domain($udom,'primary'))) {
1597: $uhome=&domain($udom,'primary');
1598: }
1599: }
1600: }
1601: if ($udom && $uhome && ($uhome ne 'no_host')) {
1602: my $items='';
1603: foreach my $item (keys(%$storehash)) {
1604: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1605: }
1606: $items=~s/\&$//;
1607: return &reply("putdom:$udom:$namespace:$items",$uhome);
1608: } else {
1609: &logthis("put_dom failed - no homeserver and/or domain");
1610: }
1611: }
1612:
1613: # --------------------- newput for items in db file owned by domainconfig user
1614: sub newput_dom {
1615: my ($namespace,$storehash,$udom) = @_;
1616: my $result;
1617: if (!$udom) {
1618: $udom=$env{'user.domain'};
1619: }
1620: if ($udom) {
1621: my $uname = &get_domainconfiguser($udom);
1622: $result = &newput($namespace,$storehash,$udom,$uname);
1623: }
1624: return $result;
1625: }
1626:
1627: # --------------------- delete for items in db file owned by domainconfig user
1628: sub del_dom {
1629: my ($namespace,$storearr,$udom)=@_;
1630: if (ref($storearr) eq 'ARRAY') {
1631: if (!$udom) {
1632: $udom=$env{'user.domain'};
1633: }
1634: if ($udom) {
1635: my $uname = &get_domainconfiguser($udom);
1636: return &del($namespace,$storearr,$udom,$uname);
1637: }
1638: }
1639: }
1640:
1641: # ----------------------------------construct domainconfig user for a domain
1642: sub get_domainconfiguser {
1643: my ($udom) = @_;
1644: return $udom.'-domainconfig';
1645: }
1646:
1647: sub retrieve_inst_usertypes {
1648: my ($udom) = @_;
1649: my (%returnhash,@order);
1650: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1651: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1652: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1653: %returnhash = %{$domdefs{'inststatustypes'}};
1654: @order = @{$domdefs{'inststatusorder'}};
1655: } else {
1656: if (defined(&domain($udom,'primary'))) {
1657: my $uhome=&domain($udom,'primary');
1658: my $rep=&reply("inst_usertypes:$udom",$uhome);
1659: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1660: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1661: return (\%returnhash,\@order);
1662: }
1663: my ($hashitems,$orderitems) = split(/:/,$rep);
1664: my @pairs=split(/\&/,$hashitems);
1665: foreach my $item (@pairs) {
1666: my ($key,$value)=split(/=/,$item,2);
1667: $key = &unescape($key);
1668: next if ($key =~ /^error: 2 /);
1669: $returnhash{$key}=&thaw_unescape($value);
1670: }
1671: my @esc_order = split(/\&/,$orderitems);
1672: foreach my $item (@esc_order) {
1673: push(@order,&unescape($item));
1674: }
1675: } else {
1676: &logthis("get_dom failed - no primary domain server for $udom");
1677: }
1678: }
1679: return (\%returnhash,\@order);
1680: }
1681:
1682: sub is_domainimage {
1683: my ($url) = @_;
1684: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1685: if (&domain($1) ne '') {
1686: return '1';
1687: }
1688: }
1689: return;
1690: }
1691:
1692: sub inst_directory_query {
1693: my ($srch) = @_;
1694: my $udom = $srch->{'srchdomain'};
1695: my %results;
1696: my $homeserver = &domain($udom,'primary');
1697: my $outcome;
1698: if ($homeserver ne '') {
1699: my $queryid=&reply("querysend:instdirsearch:".
1700: &escape($srch->{'srchby'}).':'.
1701: &escape($srch->{'srchterm'}).':'.
1702: &escape($srch->{'srchtype'}),$homeserver);
1703: my $host=&hostname($homeserver);
1704: if ($queryid !~/^\Q$host\E\_/) {
1705: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1706: return;
1707: }
1708: my $response = &get_query_reply($queryid);
1709: my $maxtries = 5;
1710: my $tries = 1;
1711: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1712: $response = &get_query_reply($queryid);
1713: $tries ++;
1714: }
1715:
1716: if (!&error($response) && $response ne 'refused') {
1717: if ($response eq 'unavailable') {
1718: $outcome = $response;
1719: } else {
1720: $outcome = 'ok';
1721: my @matches = split(/\n/,$response);
1722: foreach my $match (@matches) {
1723: my ($key,$value) = split(/=/,$match);
1724: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1725: }
1726: }
1727: }
1728: }
1729: return ($outcome,%results);
1730: }
1731:
1732: sub usersearch {
1733: my ($srch) = @_;
1734: my $dom = $srch->{'srchdomain'};
1735: my %results;
1736: my %libserv = &all_library();
1737: my $query = 'usersearch';
1738: foreach my $tryserver (keys(%libserv)) {
1739: if (&host_domain($tryserver) eq $dom) {
1740: my $host=&hostname($tryserver);
1741: my $queryid=
1742: &reply("querysend:".&escape($query).':'.
1743: &escape($srch->{'srchby'}).':'.
1744: &escape($srch->{'srchtype'}).':'.
1745: &escape($srch->{'srchterm'}),$tryserver);
1746: if ($queryid !~/^\Q$host\E\_/) {
1747: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1748: next;
1749: }
1750: my $reply = &get_query_reply($queryid);
1751: my $maxtries = 1;
1752: my $tries = 1;
1753: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1754: $reply = &get_query_reply($queryid);
1755: $tries ++;
1756: }
1757: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1758: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1759: } else {
1760: my @matches;
1761: if ($reply =~ /\n/) {
1762: @matches = split(/\n/,$reply);
1763: } else {
1764: @matches = split(/\&/,$reply);
1765: }
1766: foreach my $match (@matches) {
1767: my ($uname,$udom,%userhash);
1768: foreach my $entry (split(/:/,$match)) {
1769: my ($key,$value) =
1770: map {&unescape($_);} split(/=/,$entry);
1771: $userhash{$key} = $value;
1772: if ($key eq 'username') {
1773: $uname = $value;
1774: } elsif ($key eq 'domain') {
1775: $udom = $value;
1776: }
1777: }
1778: $results{$uname.':'.$udom} = \%userhash;
1779: }
1780: }
1781: }
1782: }
1783: return %results;
1784: }
1785:
1786: sub get_instuser {
1787: my ($udom,$uname,$id) = @_;
1788: my $homeserver = &domain($udom,'primary');
1789: my ($outcome,%results);
1790: if ($homeserver ne '') {
1791: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1792: &escape($id).':'.&escape($udom),$homeserver);
1793: my $host=&hostname($homeserver);
1794: if ($queryid !~/^\Q$host\E\_/) {
1795: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1796: return;
1797: }
1798: my $response = &get_query_reply($queryid);
1799: my $maxtries = 5;
1800: my $tries = 1;
1801: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1802: $response = &get_query_reply($queryid);
1803: $tries ++;
1804: }
1805: if (!&error($response) && $response ne 'refused') {
1806: if ($response eq 'unavailable') {
1807: $outcome = $response;
1808: } else {
1809: $outcome = 'ok';
1810: my @matches = split(/\n/,$response);
1811: foreach my $match (@matches) {
1812: my ($key,$value) = split(/=/,$match);
1813: $results{&unescape($key)} = &thaw_unescape($value);
1814: }
1815: }
1816: }
1817: }
1818: my %userinfo;
1819: if (ref($results{$uname}) eq 'HASH') {
1820: %userinfo = %{$results{$uname}};
1821: }
1822: return ($outcome,%userinfo);
1823: }
1824:
1825: sub inst_rulecheck {
1826: my ($udom,$uname,$id,$item,$rules) = @_;
1827: my %returnhash;
1828: if ($udom ne '') {
1829: if (ref($rules) eq 'ARRAY') {
1830: @{$rules} = map {&escape($_);} (@{$rules});
1831: my $rulestr = join(':',@{$rules});
1832: my $homeserver=&domain($udom,'primary');
1833: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1834: my $response;
1835: if ($item eq 'username') {
1836: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1837: ':'.&escape($uname).':'.$rulestr,
1838: $homeserver));
1839: } elsif ($item eq 'id') {
1840: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1841: ':'.&escape($id).':'.$rulestr,
1842: $homeserver));
1843: } elsif ($item eq 'selfcreate') {
1844: $response=&unescape(&reply('instselfcreatecheck:'.
1845: &escape($udom).':'.&escape($uname).
1846: ':'.$rulestr,$homeserver));
1847: }
1848: if ($response ne 'refused') {
1849: my @pairs=split(/\&/,$response);
1850: foreach my $item (@pairs) {
1851: my ($key,$value)=split(/=/,$item,2);
1852: $key = &unescape($key);
1853: next if ($key =~ /^error: 2 /);
1854: $returnhash{$key}=&thaw_unescape($value);
1855: }
1856: }
1857: }
1858: }
1859: }
1860: return %returnhash;
1861: }
1862:
1863: sub inst_userrules {
1864: my ($udom,$check) = @_;
1865: my (%ruleshash,@ruleorder);
1866: if ($udom ne '') {
1867: my $homeserver=&domain($udom,'primary');
1868: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1869: my $response;
1870: if ($check eq 'id') {
1871: $response=&reply('instidrules:'.&escape($udom),
1872: $homeserver);
1873: } elsif ($check eq 'email') {
1874: $response=&reply('instemailrules:'.&escape($udom),
1875: $homeserver);
1876: } else {
1877: $response=&reply('instuserrules:'.&escape($udom),
1878: $homeserver);
1879: }
1880: if (($response ne 'refused') && ($response ne 'error') &&
1881: ($response ne 'unknown_cmd') &&
1882: ($response ne 'no_such_host')) {
1883: my ($hashitems,$orderitems) = split(/:/,$response);
1884: my @pairs=split(/\&/,$hashitems);
1885: foreach my $item (@pairs) {
1886: my ($key,$value)=split(/=/,$item,2);
1887: $key = &unescape($key);
1888: next if ($key =~ /^error: 2 /);
1889: $ruleshash{$key}=&thaw_unescape($value);
1890: }
1891: my @esc_order = split(/\&/,$orderitems);
1892: foreach my $item (@esc_order) {
1893: push(@ruleorder,&unescape($item));
1894: }
1895: }
1896: }
1897: }
1898: return (\%ruleshash,\@ruleorder);
1899: }
1900:
1901: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1902:
1903: sub get_domain_defaults {
1904: my ($domain) = @_;
1905: my $cachetime = 60*60*24;
1906: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1907: if (defined($cached)) {
1908: if (ref($result) eq 'HASH') {
1909: return %{$result};
1910: }
1911: }
1912: my %domdefaults;
1913: my %domconfig =
1914: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1915: 'requestcourses','inststatus',
1916: 'coursedefaults','usersessions'],$domain);
1917: if (ref($domconfig{'defaults'}) eq 'HASH') {
1918: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1919: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1920: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1921: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1922: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1923: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1924: } else {
1925: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1926: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1927: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1928: }
1929: if (ref($domconfig{'quotas'}) eq 'HASH') {
1930: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1931: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1932: } else {
1933: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1934: }
1935: my @usertools = ('aboutme','blog','portfolio');
1936: foreach my $item (@usertools) {
1937: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1938: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1939: }
1940: }
1941: }
1942: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1943: foreach my $item ('official','unofficial','community') {
1944: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1945: }
1946: }
1947: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1948: foreach my $item ('inststatustypes','inststatusorder') {
1949: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1950: }
1951: }
1952: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1953: foreach my $item ('canuse_pdfforms') {
1954: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1955: }
1956: }
1957: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1958: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1959: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1960: }
1961: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1962: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1963: }
1964: }
1965: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1966: $cachetime);
1967: return %domdefaults;
1968: }
1969:
1970: # --------------------------------------------------- Assign a key to a student
1971:
1972: sub assign_access_key {
1973: #
1974: # a valid key looks like uname:udom#comments
1975: # comments are being appended
1976: #
1977: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1978: $kdom=
1979: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1980: $knum=
1981: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1982: $cdom=
1983: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1984: $cnum=
1985: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1986: $udom=$env{'user.name'} unless (defined($udom));
1987: $uname=$env{'user.domain'} unless (defined($uname));
1988: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1989: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1990: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1991: # assigned to this person
1992: # - this should not happen,
1993: # unless something went wrong
1994: # the first time around
1995: # ready to assign
1996: $logentry=$1.'; '.$logentry;
1997: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1998: $kdom,$knum) eq 'ok') {
1999: # key now belongs to user
2000: my $envkey='key.'.$cdom.'_'.$cnum;
2001: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2002: &appenv({'environment.'.$envkey => $ckey});
2003: return 'ok';
2004: } else {
2005: return
2006: 'error: Count not permanently assign key, will need to be re-entered later.';
2007: }
2008: } else {
2009: return 'error: Could not assign key, try again later.';
2010: }
2011: } elsif (!$existing{$ckey}) {
2012: # the key does not exist
2013: return 'error: The key does not exist';
2014: } else {
2015: # the key is somebody else's
2016: return 'error: The key is already in use';
2017: }
2018: }
2019:
2020: # ------------------------------------------ put an additional comment on a key
2021:
2022: sub comment_access_key {
2023: #
2024: # a valid key looks like uname:udom#comments
2025: # comments are being appended
2026: #
2027: my ($ckey,$cdom,$cnum,$logentry)=@_;
2028: $cdom=
2029: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2030: $cnum=
2031: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2032: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2033: if ($existing{$ckey}) {
2034: $existing{$ckey}.='; '.$logentry;
2035: # ready to assign
2036: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2037: $cdom,$cnum) eq 'ok') {
2038: return 'ok';
2039: } else {
2040: return 'error: Count not store comment.';
2041: }
2042: } else {
2043: # the key does not exist
2044: return 'error: The key does not exist';
2045: }
2046: }
2047:
2048: # ------------------------------------------------------ Generate a set of keys
2049:
2050: sub generate_access_keys {
2051: my ($number,$cdom,$cnum,$logentry)=@_;
2052: $cdom=
2053: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2054: $cnum=
2055: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2056: unless (&allowed('mky',$cdom)) { return 0; }
2057: unless (($cdom) && ($cnum)) { return 0; }
2058: if ($number>10000) { return 0; }
2059: sleep(2); # make sure don't get same seed twice
2060: srand(time()^($$+($$<<15))); # from "Programming Perl"
2061: my $total=0;
2062: for (my $i=1;$i<=$number;$i++) {
2063: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2064: sprintf("%lx",int(100000*rand)).'-'.
2065: sprintf("%lx",int(100000*rand));
2066: $newkey=~s/1/g/g; # folks mix up 1 and l
2067: $newkey=~s/0/h/g; # and also 0 and O
2068: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2069: if ($existing{$newkey}) {
2070: $i--;
2071: } else {
2072: if (&put('accesskeys',
2073: { $newkey => '# generated '.localtime().
2074: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2075: '; '.$logentry },
2076: $cdom,$cnum) eq 'ok') {
2077: $total++;
2078: }
2079: }
2080: }
2081: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2082: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2083: return $total;
2084: }
2085:
2086: # ------------------------------------------------------- Validate an accesskey
2087:
2088: sub validate_access_key {
2089: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2090: $cdom=
2091: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2092: $cnum=
2093: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2094: $udom=$env{'user.domain'} unless (defined($udom));
2095: $uname=$env{'user.name'} unless (defined($uname));
2096: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2097: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2098: }
2099:
2100: # ------------------------------------- Find the section of student in a course
2101: sub devalidate_getsection_cache {
2102: my ($udom,$unam,$courseid)=@_;
2103: my $hashid="$udom:$unam:$courseid";
2104: &devalidate_cache_new('getsection',$hashid);
2105: }
2106:
2107: sub courseid_to_courseurl {
2108: my ($courseid) = @_;
2109: #already url style courseid
2110: return $courseid if ($courseid =~ m{^/});
2111:
2112: if (exists($env{'course.'.$courseid.'.num'})) {
2113: my $cnum = $env{'course.'.$courseid.'.num'};
2114: my $cdom = $env{'course.'.$courseid.'.domain'};
2115: return "/$cdom/$cnum";
2116: }
2117:
2118: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2119: if (exists($courseinfo{'num'})) {
2120: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2121: }
2122:
2123: return undef;
2124: }
2125:
2126: sub getsection {
2127: my ($udom,$unam,$courseid)=@_;
2128: my $cachetime=1800;
2129:
2130: my $hashid="$udom:$unam:$courseid";
2131: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2132: if (defined($cached)) { return $result; }
2133:
2134: my %Pending;
2135: my %Expired;
2136: #
2137: # Each role can either have not started yet (pending), be active,
2138: # or have expired.
2139: #
2140: # If there is an active role, we are done.
2141: #
2142: # If there is more than one role which has not started yet,
2143: # choose the one which will start sooner
2144: # If there is one role which has not started yet, return it.
2145: #
2146: # If there is more than one expired role, choose the one which ended last.
2147: # If there is a role which has expired, return it.
2148: #
2149: $courseid = &courseid_to_courseurl($courseid);
2150: my $extra = &freeze_escape({'skipcheck' => 1});
2151: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
2152: foreach my $key (keys(%roleshash)) {
2153: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2154: my $section=$1;
2155: if ($key eq $courseid.'_st') { $section=''; }
2156: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2157: my $now=time;
2158: if (defined($end) && $end && ($now > $end)) {
2159: $Expired{$end}=$section;
2160: next;
2161: }
2162: if (defined($start) && $start && ($now < $start)) {
2163: $Pending{$start}=$section;
2164: next;
2165: }
2166: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2167: }
2168: #
2169: # Presumedly there will be few matching roles from the above
2170: # loop and the sorting time will be negligible.
2171: if (scalar(keys(%Pending))) {
2172: my ($time) = sort {$a <=> $b} keys(%Pending);
2173: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2174: }
2175: if (scalar(keys(%Expired))) {
2176: my @sorted = sort {$a <=> $b} keys(%Expired);
2177: my $time = pop(@sorted);
2178: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2179: }
2180: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2181: }
2182:
2183: sub save_cache {
2184: &purge_remembered();
2185: #&Apache::loncommon::validate_page();
2186: undef(%env);
2187: undef($env_loaded);
2188: }
2189:
2190: my $to_remember=-1;
2191: my %remembered;
2192: my %accessed;
2193: my $kicks=0;
2194: my $hits=0;
2195: sub make_key {
2196: my ($name,$id) = @_;
2197: if (length($id) > 65
2198: && length(&escape($id)) > 200) {
2199: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2200: }
2201: return &escape($name.':'.$id);
2202: }
2203:
2204: sub devalidate_cache_new {
2205: my ($name,$id,$debug) = @_;
2206: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2207: $id=&make_key($name,$id);
2208: $memcache->delete($id);
2209: delete($remembered{$id});
2210: delete($accessed{$id});
2211: }
2212:
2213: sub is_cached_new {
2214: my ($name,$id,$debug) = @_;
2215: $id=&make_key($name,$id);
2216: if (exists($remembered{$id})) {
2217: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2218: $accessed{$id}=[&gettimeofday()];
2219: $hits++;
2220: return ($remembered{$id},1);
2221: }
2222: my $value = $memcache->get($id);
2223: if (!(defined($value))) {
2224: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2225: return (undef,undef);
2226: }
2227: if ($value eq '__undef__') {
2228: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2229: $value=undef;
2230: }
2231: &make_room($id,$value,$debug);
2232: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2233: return ($value,1);
2234: }
2235:
2236: sub do_cache_new {
2237: my ($name,$id,$value,$time,$debug) = @_;
2238: $id=&make_key($name,$id);
2239: my $setvalue=$value;
2240: if (!defined($setvalue)) {
2241: $setvalue='__undef__';
2242: }
2243: if (!defined($time) ) {
2244: $time=600;
2245: }
2246: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2247: my $result = $memcache->set($id,$setvalue,$time);
2248: if (! $result) {
2249: &logthis("caching of id -> $id failed");
2250: $memcache->disconnect_all();
2251: }
2252: # need to make a copy of $value
2253: &make_room($id,$value,$debug);
2254: return $value;
2255: }
2256:
2257: sub make_room {
2258: my ($id,$value,$debug)=@_;
2259:
2260: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2261: : $value;
2262: if ($to_remember<0) { return; }
2263: $accessed{$id}=[&gettimeofday()];
2264: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2265: my $to_kick;
2266: my $max_time=0;
2267: foreach my $other (keys(%accessed)) {
2268: if (&tv_interval($accessed{$other}) > $max_time) {
2269: $to_kick=$other;
2270: $max_time=&tv_interval($accessed{$other});
2271: }
2272: }
2273: delete($remembered{$to_kick});
2274: delete($accessed{$to_kick});
2275: $kicks++;
2276: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2277: return;
2278: }
2279:
2280: sub purge_remembered {
2281: #&logthis("Tossing ".scalar(keys(%remembered)));
2282: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2283: undef(%remembered);
2284: undef(%accessed);
2285: }
2286: # ------------------------------------- Read an entry from a user's environment
2287:
2288: sub userenvironment {
2289: my ($udom,$unam,@what)=@_;
2290: my $items;
2291: foreach my $item (@what) {
2292: $items.=&escape($item).'&';
2293: }
2294: $items=~s/\&$//;
2295: my %returnhash=();
2296: my $uhome = &homeserver($unam,$udom);
2297: unless ($uhome eq 'no_host') {
2298: my @answer=split(/\&/,
2299: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2300: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2301: return %returnhash;
2302: }
2303: my $i;
2304: for ($i=0;$i<=$#what;$i++) {
2305: $returnhash{$what[$i]}=&unescape($answer[$i]);
2306: }
2307: }
2308: return %returnhash;
2309: }
2310:
2311: # ---------------------------------------------------------- Get a studentphoto
2312: sub studentphoto {
2313: my ($udom,$unam,$ext) = @_;
2314: my $home=&Apache::lonnet::homeserver($unam,$udom);
2315: if (defined($env{'request.course.id'})) {
2316: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2317: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2318: return(&retrievestudentphoto($udom,$unam,$ext));
2319: } else {
2320: my ($result,$perm_reqd)=
2321: &Apache::lonnet::auto_photo_permission($unam,$udom);
2322: if ($result eq 'ok') {
2323: if (!($perm_reqd eq 'yes')) {
2324: return(&retrievestudentphoto($udom,$unam,$ext));
2325: }
2326: }
2327: }
2328: }
2329: } else {
2330: my ($result,$perm_reqd) =
2331: &Apache::lonnet::auto_photo_permission($unam,$udom);
2332: if ($result eq 'ok') {
2333: if (!($perm_reqd eq 'yes')) {
2334: return(&retrievestudentphoto($udom,$unam,$ext));
2335: }
2336: }
2337: }
2338: return '/adm/lonKaputt/lonlogo_broken.gif';
2339: }
2340:
2341: sub retrievestudentphoto {
2342: my ($udom,$unam,$ext,$type) = @_;
2343: my $home=&Apache::lonnet::homeserver($unam,$udom);
2344: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2345: if ($ret eq 'ok') {
2346: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2347: if ($type eq 'thumbnail') {
2348: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2349: }
2350: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2351: return $tokenurl;
2352: } else {
2353: if ($type eq 'thumbnail') {
2354: return '/adm/lonKaputt/genericstudent_tn.gif';
2355: } else {
2356: return '/adm/lonKaputt/lonlogo_broken.gif';
2357: }
2358: }
2359: }
2360:
2361: # -------------------------------------------------------------------- New chat
2362:
2363: sub chatsend {
2364: my ($newentry,$anon,$group)=@_;
2365: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2366: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2367: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2368: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2369: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2370: &escape($newentry)).':'.$group,$chome);
2371: }
2372:
2373: # ------------------------------------------ Find current version of a resource
2374:
2375: sub getversion {
2376: my $fname=&clutter(shift);
2377: unless ($fname=~/^\/res\//) { return -1; }
2378: return ¤tversion(&filelocation('',$fname));
2379: }
2380:
2381: sub currentversion {
2382: my $fname=shift;
2383: my $author=$fname;
2384: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2385: my ($udom,$uname)=split(/\//,$author);
2386: my $home=&homeserver($uname,$udom);
2387: if ($home eq 'no_host') {
2388: return -1;
2389: }
2390: my $answer=&reply("currentversion:$fname",$home);
2391: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2392: return -1;
2393: }
2394: return $answer;
2395: }
2396:
2397: #
2398: # Return special version number of resource if set by override, empty otherwise
2399: #
2400: sub usedversion {
2401: my $fname=shift;
2402: unless ($fname) { $fname=$env{'request.uri'}; }
2403: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2404: if ($urlversion) { return $urlversion; }
2405: return '';
2406: }
2407:
2408: # ----------------------------- Subscribe to a resource, return URL if possible
2409:
2410: sub subscribe {
2411: my $fname=shift;
2412: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2413: $fname=~s/[\n\r]//g;
2414: my $author=$fname;
2415: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2416: my ($udom,$uname)=split(/\//,$author);
2417: my $home=homeserver($uname,$udom);
2418: if ($home eq 'no_host') {
2419: return 'not_found';
2420: }
2421: my $answer=reply("sub:$fname",$home);
2422: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2423: $answer.=' by '.$home;
2424: }
2425: return $answer;
2426: }
2427:
2428: # -------------------------------------------------------------- Replicate file
2429:
2430: sub repcopy {
2431: my $filename=shift;
2432: $filename=~s/\/+/\//g;
2433: my $londocroot = $perlvar{'lonDocRoot'};
2434: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2435: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2436: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2437: $filename=~m{^/*(uploaded|editupload)/}) {
2438: return &repcopy_userfile($filename);
2439: }
2440: $filename=~s/[\n\r]//g;
2441: my $transname="$filename.in.transfer";
2442: # FIXME: this should flock
2443: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2444: my $remoteurl=subscribe($filename);
2445: if ($remoteurl =~ /^con_lost by/) {
2446: &logthis("Subscribe returned $remoteurl: $filename");
2447: return 'unavailable';
2448: } elsif ($remoteurl eq 'not_found') {
2449: #&logthis("Subscribe returned not_found: $filename");
2450: return 'not_found';
2451: } elsif ($remoteurl =~ /^rejected by/) {
2452: &logthis("Subscribe returned $remoteurl: $filename");
2453: return 'forbidden';
2454: } elsif ($remoteurl eq 'directory') {
2455: return 'ok';
2456: } else {
2457: my $author=$filename;
2458: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2459: my ($udom,$uname)=split(/\//,$author);
2460: my $home=homeserver($uname,$udom);
2461: unless ($home eq $perlvar{'lonHostID'}) {
2462: my @parts=split(/\//,$filename);
2463: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2464: if ($path ne "$londocroot/res") {
2465: &logthis("Malconfiguration for replication: $filename");
2466: return 'bad_request';
2467: }
2468: my $count;
2469: for ($count=5;$count<$#parts;$count++) {
2470: $path.="/$parts[$count]";
2471: if ((-e $path)!=1) {
2472: mkdir($path,0777);
2473: }
2474: }
2475: my $ua=new LWP::UserAgent;
2476: my $request=new HTTP::Request('GET',"$remoteurl");
2477: my $response=$ua->request($request,$transname);
2478: if ($response->is_error()) {
2479: unlink($transname);
2480: my $message=$response->status_line;
2481: &logthis("<font color=\"blue\">WARNING:"
2482: ." LWP get: $message: $filename</font>");
2483: return 'unavailable';
2484: } else {
2485: if ($remoteurl!~/\.meta$/) {
2486: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2487: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2488: if ($mresponse->is_error()) {
2489: unlink($filename.'.meta');
2490: &logthis(
2491: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2492: }
2493: }
2494: rename($transname,$filename);
2495: return 'ok';
2496: }
2497: }
2498: }
2499: }
2500:
2501: # ------------------------------------------------ Get server side include body
2502: sub ssi_body {
2503: my ($filelink,%form)=@_;
2504: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2505: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2506: }
2507: my $output='';
2508: my $response;
2509: if ($filelink=~/^https?\:/) {
2510: ($output,$response)=&externalssi($filelink);
2511: } else {
2512: $filelink .= $filelink=~/\?/ ? '&' : '?';
2513: $filelink .= 'inhibitmenu=yes';
2514: ($output,$response)=&ssi($filelink,%form);
2515: }
2516: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2517: $output=~s/^.*?\<body[^\>]*\>//si;
2518: $output=~s/\<\/body\s*\>.*?$//si;
2519: if (wantarray) {
2520: return ($output, $response);
2521: } else {
2522: return $output;
2523: }
2524: }
2525:
2526: # --------------------------------------------------------- Server Side Include
2527:
2528: sub absolute_url {
2529: my ($host_name) = @_;
2530: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2531: if ($host_name eq '') {
2532: $host_name = $ENV{'SERVER_NAME'};
2533: }
2534: return $protocol.$host_name;
2535: }
2536:
2537: #
2538: # Server side include.
2539: # Parameters:
2540: # fn Possibly encrypted resource name/id.
2541: # form Hash that describes how the rendering should be done
2542: # and other things.
2543: # Returns:
2544: # Scalar context: The content of the response.
2545: # Array context: 2 element list of the content and the full response object.
2546: #
2547: sub ssi {
2548:
2549: my ($fn,%form)=@_;
2550: my $ua=new LWP::UserAgent;
2551: my $request;
2552:
2553: $form{'no_update_last_known'}=1;
2554: &Apache::lonenc::check_encrypt(\$fn);
2555: if (%form) {
2556: $request=new HTTP::Request('POST',&absolute_url().$fn);
2557: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2558: } else {
2559: $request=new HTTP::Request('GET',&absolute_url().$fn);
2560: }
2561:
2562: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2563: my $response=$ua->request($request);
2564:
2565: if (wantarray) {
2566: return ($response->content, $response);
2567: } else {
2568: return $response->content;
2569: }
2570: }
2571:
2572: sub externalssi {
2573: my ($url)=@_;
2574: my $ua=new LWP::UserAgent;
2575: my $request=new HTTP::Request('GET',$url);
2576: my $response=$ua->request($request);
2577: if (wantarray) {
2578: return ($response->content, $response);
2579: } else {
2580: return $response->content;
2581: }
2582: }
2583:
2584: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2585:
2586: sub allowuploaded {
2587: my ($srcurl,$url)=@_;
2588: $url=&clutter(&declutter($url));
2589: my $dir=$url;
2590: $dir=~s/\/[^\/]+$//;
2591: my %httpref=();
2592: my $httpurl=&hreflocation('',$url);
2593: $httpref{'httpref.'.$httpurl}=$srcurl;
2594: &Apache::lonnet::appenv(\%httpref);
2595: }
2596:
2597: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2598: # input: action, courseID, current domain, intended
2599: # path to file, source of file, instruction to parse file for objects,
2600: # ref to hash for embedded objects,
2601: # ref to hash for codebase of java objects.
2602: # reference to scalar to accommodate mime type determined
2603: # from File::MMagic if $parser = parse.
2604: #
2605: # output: url to file (if action was uploaddoc),
2606: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2607: #
2608: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2609: # course.
2610: #
2611: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2612: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2613: # course's home server.
2614: #
2615: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2616: # be copied from $source (current location) to
2617: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2618: # and will then be copied to
2619: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2620: # course's home server.
2621: #
2622: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2623: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2624: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2625: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2626: # in course's home server.
2627: #
2628:
2629: sub process_coursefile {
2630: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2631: $mimetype)=@_;
2632: my $fetchresult;
2633: my $home=&homeserver($docuname,$docudom);
2634: if ($action eq 'propagate') {
2635: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2636: $home);
2637: } else {
2638: my $fpath = '';
2639: my $fname = $file;
2640: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2641: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2642: my $filepath = &build_filepath($fpath);
2643: if ($action eq 'copy') {
2644: if ($source eq '') {
2645: $fetchresult = 'no source file';
2646: return $fetchresult;
2647: } else {
2648: my $destination = $filepath.'/'.$fname;
2649: rename($source,$destination);
2650: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2651: $home);
2652: }
2653: } elsif ($action eq 'uploaddoc') {
2654: open(my $fh,'>'.$filepath.'/'.$fname);
2655: print $fh $env{'form.'.$source};
2656: close($fh);
2657: if ($parser eq 'parse') {
2658: my $mm = new File::MMagic;
2659: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2660: if ($type eq 'text/html') {
2661: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2662: unless ($parse_result eq 'ok') {
2663: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2664: }
2665: }
2666: if (ref($mimetype)) {
2667: $$mimetype = $type;
2668: }
2669: }
2670: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2671: $home);
2672: if ($fetchresult eq 'ok') {
2673: return '/uploaded/'.$fpath.'/'.$fname;
2674: } else {
2675: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2676: ' to host '.$home.': '.$fetchresult);
2677: return '/adm/notfound.html';
2678: }
2679: }
2680: }
2681: unless ( $fetchresult eq 'ok') {
2682: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2683: ' to host '.$home.': '.$fetchresult);
2684: }
2685: return $fetchresult;
2686: }
2687:
2688: sub build_filepath {
2689: my ($fpath) = @_;
2690: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2691: unless ($fpath eq '') {
2692: my @parts=split('/',$fpath);
2693: foreach my $part (@parts) {
2694: $filepath.= '/'.$part;
2695: if ((-e $filepath)!=1) {
2696: mkdir($filepath,0777);
2697: }
2698: }
2699: }
2700: return $filepath;
2701: }
2702:
2703: sub store_edited_file {
2704: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2705: my $file = $primary_url;
2706: $file =~ s#^/uploaded/$docudom/$docuname/##;
2707: my $fpath = '';
2708: my $fname = $file;
2709: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2710: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2711: my $filepath = &build_filepath($fpath);
2712: open(my $fh,'>'.$filepath.'/'.$fname);
2713: print $fh $content;
2714: close($fh);
2715: my $home=&homeserver($docuname,$docudom);
2716: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2717: $home);
2718: if ($$fetchresult eq 'ok') {
2719: return '/uploaded/'.$fpath.'/'.$fname;
2720: } else {
2721: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2722: ' to host '.$home.': '.$$fetchresult);
2723: return '/adm/notfound.html';
2724: }
2725: }
2726:
2727: sub clean_filename {
2728: my ($fname,$args)=@_;
2729: # Replace Windows backslashes by forward slashes
2730: $fname=~s/\\/\//g;
2731: if (!$args->{'keep_path'}) {
2732: # Get rid of everything but the actual filename
2733: $fname=~s/^.*\/([^\/]+)$/$1/;
2734: }
2735: # Replace spaces by underscores
2736: $fname=~s/\s+/\_/g;
2737: # Replace all other weird characters by nothing
2738: $fname=~s{[^/\w\.\-]}{}g;
2739: # Replace all .\d. sequences with _\d. so they no longer look like version
2740: # numbers
2741: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2742: return $fname;
2743: }
2744: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2745: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2746: # image with the same aspect ratio as the original, but with dimensions which do
2747: # not exceed $resizewidth and $resizeheight.
2748:
2749: sub resizeImage {
2750: my ($img_path,$resizewidth,$resizeheight) = @_;
2751: my $ima = Image::Magick->new;
2752: my $resized;
2753: if (-e $img_path) {
2754: $ima->Read($img_path);
2755: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2756: my $width = $ima->Get('width');
2757: my $height = $ima->Get('height');
2758: if ($width > $resizewidth) {
2759: my $factor = $width/$resizewidth;
2760: my $newheight = $height/$factor;
2761: $ima->Scale(width=>$resizewidth,height=>$newheight);
2762: $resized = 1;
2763: }
2764: }
2765: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2766: my $width = $ima->Get('width');
2767: my $height = $ima->Get('height');
2768: if ($height > $resizeheight) {
2769: my $factor = $height/$resizeheight;
2770: my $newwidth = $width/$factor;
2771: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2772: $resized = 1;
2773: }
2774: }
2775: if ($resized) {
2776: $ima->Write($img_path);
2777: }
2778: }
2779: return;
2780: }
2781:
2782: # --------------- Take an uploaded file and put it into the userfiles directory
2783: # input: $formname - the contents of the file are in $env{"form.$formname"}
2784: # the desired filename is in $env{"form.$formname.filename"}
2785: # $context - possible values: coursedoc, existingfile, overwrite,
2786: # canceloverwrite, or ''.
2787: # if 'coursedoc': upload to the current course
2788: # if 'existingfile': write file to tmp/overwrites directory
2789: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2790: # $context is passed as argument to &finishuserfileupload
2791: # $subdir - directory in userfile to store the file into
2792: # $parser - instruction to parse file for objects ($parser = parse)
2793: # $allfiles - reference to hash for embedded objects
2794: # $codebase - reference to hash for codebase of java objects
2795: # $desuname - username for permanent storage of uploaded file
2796: # $dsetudom - domain for permanaent storage of uploaded file
2797: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2798: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2799: # $resizewidth - width (pixels) to which to resize uploaded image
2800: # $resizeheight - height (pixels) to which to resize uploaded image
2801: # $mimetype - reference to scalar to accommodate mime type determined
2802: # from File::MMagic if $parser = parse.
2803: #
2804: # output: url of file in userspace, or error: <message>
2805: # or /adm/notfound.html if failure to upload occurse
2806:
2807: sub userfileupload {
2808: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2809: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2810: if (!defined($subdir)) { $subdir='unknown'; }
2811: my $fname=$env{'form.'.$formname.'.filename'};
2812: $fname=&clean_filename($fname);
2813: # See if there is anything left
2814: unless ($fname) { return 'error: no uploaded file'; }
2815: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2816: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2817: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2818: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2819: my $now = time;
2820: my $filepath;
2821: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2822: $filepath = 'tmp/helprequests/'.$now;
2823: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2824: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2825: '_'.$env{'user.domain'}.'/pending';
2826: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2827: my ($docuname,$docudom);
2828: if ($destudom) {
2829: $docudom = $destudom;
2830: } else {
2831: $docudom = $env{'user.domain'};
2832: }
2833: if ($destuname) {
2834: $docuname = $destuname;
2835: } else {
2836: $docuname = $env{'user.name'};
2837: }
2838: if (exists($env{'form.group'})) {
2839: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2840: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2841: }
2842: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2843: if ($context eq 'canceloverwrite') {
2844: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2845: if (-e $tempfile) {
2846: my @info = stat($tempfile);
2847: if ($info[9] eq $env{'form.timestamp'}) {
2848: unlink($tempfile);
2849: }
2850: }
2851: return;
2852: }
2853: }
2854: # Create the directory if not present
2855: my @parts=split(/\//,$filepath);
2856: my $fullpath = $perlvar{'lonDaemons'};
2857: for (my $i=0;$i<@parts;$i++) {
2858: $fullpath .= '/'.$parts[$i];
2859: if ((-e $fullpath)!=1) {
2860: mkdir($fullpath,0777);
2861: }
2862: }
2863: open(my $fh,'>'.$fullpath.'/'.$fname);
2864: print $fh $env{'form.'.$formname};
2865: close($fh);
2866: if ($context eq 'existingfile') {
2867: my @info = stat($fullpath.'/'.$fname);
2868: return ($fullpath.'/'.$fname,$info[9]);
2869: } else {
2870: return $fullpath.'/'.$fname;
2871: }
2872: }
2873: if ($subdir eq 'scantron') {
2874: $fname = 'scantron_orig_'.$fname;
2875: } else {
2876: $fname="$subdir/$fname";
2877: }
2878: if ($context eq 'coursedoc') {
2879: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2880: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2881: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2882: return &finishuserfileupload($docuname,$docudom,
2883: $formname,$fname,$parser,$allfiles,
2884: $codebase,$thumbwidth,$thumbheight,
2885: $resizewidth,$resizeheight,$context,$mimetype);
2886: } else {
2887: $fname=$env{'form.folder'}.'/'.$fname;
2888: return &process_coursefile('uploaddoc',$docuname,$docudom,
2889: $fname,$formname,$parser,
2890: $allfiles,$codebase,$mimetype);
2891: }
2892: } elsif (defined($destuname)) {
2893: my $docuname=$destuname;
2894: my $docudom=$destudom;
2895: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2896: $parser,$allfiles,$codebase,
2897: $thumbwidth,$thumbheight,
2898: $resizewidth,$resizeheight,$context,$mimetype);
2899: } else {
2900: my $docuname=$env{'user.name'};
2901: my $docudom=$env{'user.domain'};
2902: if (exists($env{'form.group'})) {
2903: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2904: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2905: }
2906: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2907: $parser,$allfiles,$codebase,
2908: $thumbwidth,$thumbheight,
2909: $resizewidth,$resizeheight,$context,$mimetype);
2910: }
2911: }
2912:
2913: sub finishuserfileupload {
2914: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2915: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2916: my $path=$docudom.'/'.$docuname.'/';
2917: my $filepath=$perlvar{'lonDocRoot'};
2918:
2919: my ($fnamepath,$file,$fetchthumb);
2920: $file=$fname;
2921: if ($fname=~m|/|) {
2922: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2923: $path.=$fnamepath.'/';
2924: }
2925: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2926: my $count;
2927: for ($count=4;$count<=$#parts;$count++) {
2928: $filepath.="/$parts[$count]";
2929: if ((-e $filepath)!=1) {
2930: mkdir($filepath,0777);
2931: }
2932: }
2933:
2934: # Save the file
2935: {
2936: if (!open(FH,'>'.$filepath.'/'.$file)) {
2937: &logthis('Failed to create '.$filepath.'/'.$file);
2938: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2939: return '/adm/notfound.html';
2940: }
2941: if ($context eq 'overwrite') {
2942: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2943: my $target = $filepath.'/'.$file;
2944: if (-e $source) {
2945: my @info = stat($source);
2946: if ($info[9] eq $env{'form.timestamp'}) {
2947: unless (&File::Copy::move($source,$target)) {
2948: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2949: return "Moving from $source failed";
2950: }
2951: } else {
2952: return "Temporary file: $source had unexpected date/time for last modification";
2953: }
2954: } else {
2955: return "Temporary file: $source missing";
2956: }
2957: } elsif (!print FH ($env{'form.'.$formname})) {
2958: &logthis('Failed to write to '.$filepath.'/'.$file);
2959: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2960: return '/adm/notfound.html';
2961: }
2962: close(FH);
2963: if ($resizewidth && $resizeheight) {
2964: my $mm = new File::MMagic;
2965: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2966: if ($mime_type =~ m{^image/}) {
2967: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2968: }
2969: }
2970: }
2971: if ($parser eq 'parse') {
2972: my $mm = new File::MMagic;
2973: my $type = $mm->checktype_filename($filepath.'/'.$file);
2974: if ($type eq 'text/html') {
2975: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2976: $allfiles,$codebase);
2977: unless ($parse_result eq 'ok') {
2978: &logthis('Failed to parse '.$filepath.$file.
2979: ' for embedded media: '.$parse_result);
2980: }
2981: }
2982: if (ref($mimetype)) {
2983: $$mimetype = $type;
2984: }
2985: }
2986: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2987: my $input = $filepath.'/'.$file;
2988: my $output = $filepath.'/'.'tn-'.$file;
2989: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2990: system("convert -sample $thumbsize $input $output");
2991: if (-e $filepath.'/'.'tn-'.$file) {
2992: $fetchthumb = 1;
2993: }
2994: }
2995:
2996: # Notify homeserver to grep it
2997: #
2998: my $docuhome=&homeserver($docuname,$docudom);
2999: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3000: if ($fetchresult eq 'ok') {
3001: if ($fetchthumb) {
3002: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3003: if ($thumbresult ne 'ok') {
3004: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3005: $docuhome.': '.$thumbresult);
3006: }
3007: }
3008: #
3009: # Return the URL to it
3010: return '/uploaded/'.$path.$file;
3011: } else {
3012: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3013: ': '.$fetchresult);
3014: return '/adm/notfound.html';
3015: }
3016: }
3017:
3018: sub extract_embedded_items {
3019: my ($fullpath,$allfiles,$codebase,$content) = @_;
3020: my @state = ();
3021: my %javafiles = (
3022: codebase => '',
3023: code => '',
3024: archive => ''
3025: );
3026: my %mediafiles = (
3027: src => '',
3028: movie => '',
3029: );
3030: my $p;
3031: if ($content) {
3032: $p = HTML::LCParser->new($content);
3033: } else {
3034: $p = HTML::LCParser->new($fullpath);
3035: }
3036: while (my $t=$p->get_token()) {
3037: if ($t->[0] eq 'S') {
3038: my ($tagname, $attr) = ($t->[1],$t->[2]);
3039: push(@state, $tagname);
3040: if (lc($tagname) eq 'allow') {
3041: &add_filetype($allfiles,$attr->{'src'},'src');
3042: }
3043: if (lc($tagname) eq 'img') {
3044: &add_filetype($allfiles,$attr->{'src'},'src');
3045: }
3046: if (lc($tagname) eq 'a') {
3047: &add_filetype($allfiles,$attr->{'href'},'href');
3048: }
3049: if (lc($tagname) eq 'script') {
3050: if ($attr->{'archive'} =~ /\.jar$/i) {
3051: &add_filetype($allfiles,$attr->{'archive'},'archive');
3052: } else {
3053: &add_filetype($allfiles,$attr->{'src'},'src');
3054: }
3055: }
3056: if (lc($tagname) eq 'link') {
3057: if (lc($attr->{'rel'}) eq 'stylesheet') {
3058: &add_filetype($allfiles,$attr->{'href'},'href');
3059: }
3060: }
3061: if (lc($tagname) eq 'object' ||
3062: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3063: foreach my $item (keys(%javafiles)) {
3064: $javafiles{$item} = '';
3065: }
3066: }
3067: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3068: my $name = lc($attr->{'name'});
3069: foreach my $item (keys(%javafiles)) {
3070: if ($name eq $item) {
3071: $javafiles{$item} = $attr->{'value'};
3072: last;
3073: }
3074: }
3075: foreach my $item (keys(%mediafiles)) {
3076: if ($name eq $item) {
3077: &add_filetype($allfiles, $attr->{'value'}, 'value');
3078: last;
3079: }
3080: }
3081: }
3082: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3083: foreach my $item (keys(%javafiles)) {
3084: if ($attr->{$item}) {
3085: $javafiles{$item} = $attr->{$item};
3086: last;
3087: }
3088: }
3089: foreach my $item (keys(%mediafiles)) {
3090: if ($attr->{$item}) {
3091: &add_filetype($allfiles,$attr->{$item},$item);
3092: last;
3093: }
3094: }
3095: }
3096: } elsif ($t->[0] eq 'E') {
3097: my ($tagname) = ($t->[1]);
3098: if ($javafiles{'codebase'} ne '') {
3099: $javafiles{'codebase'} .= '/';
3100: }
3101: if (lc($tagname) eq 'applet' ||
3102: lc($tagname) eq 'object' ||
3103: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3104: ) {
3105: foreach my $item (keys(%javafiles)) {
3106: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3107: my $file=$javafiles{'codebase'}.$javafiles{$item};
3108: &add_filetype($allfiles,$file,$item);
3109: }
3110: }
3111: }
3112: pop @state;
3113: }
3114: }
3115: return 'ok';
3116: }
3117:
3118: sub add_filetype {
3119: my ($allfiles,$file,$type)=@_;
3120: if (exists($allfiles->{$file})) {
3121: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3122: push(@{$allfiles->{$file}}, &escape($type));
3123: }
3124: } else {
3125: @{$allfiles->{$file}} = (&escape($type));
3126: }
3127: }
3128:
3129: sub removeuploadedurl {
3130: my ($url)=@_;
3131: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3132: return &removeuserfile($uname,$udom,$fname);
3133: }
3134:
3135: sub removeuserfile {
3136: my ($docuname,$docudom,$fname)=@_;
3137: my $home=&homeserver($docuname,$docudom);
3138: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3139: if ($result eq 'ok') {
3140: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3141: my $metafile = $fname.'.meta';
3142: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3143: my $url = "/uploaded/$docudom/$docuname/$fname";
3144: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3145: my $sqlresult =
3146: &update_portfolio_table($docuname,$docudom,$file,
3147: 'portfolio_metadata',$group,
3148: 'delete');
3149: }
3150: }
3151: return $result;
3152: }
3153:
3154: sub mkdiruserfile {
3155: my ($docuname,$docudom,$dir)=@_;
3156: my $home=&homeserver($docuname,$docudom);
3157: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3158: }
3159:
3160: sub renameuserfile {
3161: my ($docuname,$docudom,$old,$new)=@_;
3162: my $home=&homeserver($docuname,$docudom);
3163: my $result = &reply("renameuserfile:$docudom:$docuname:".
3164: &escape("$old").':'.&escape("$new"),$home);
3165: if ($result eq 'ok') {
3166: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3167: my $oldmeta = $old.'.meta';
3168: my $newmeta = $new.'.meta';
3169: my $metaresult =
3170: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3171: my $url = "/uploaded/$docudom/$docuname/$old";
3172: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3173: my $sqlresult =
3174: &update_portfolio_table($docuname,$docudom,$file,
3175: 'portfolio_metadata',$group,
3176: 'delete');
3177: }
3178: }
3179: return $result;
3180: }
3181:
3182: # ------------------------------------------------------------------------- Log
3183:
3184: sub log {
3185: my ($dom,$nam,$hom,$what)=@_;
3186: return critical("log:$dom:$nam:$what",$hom);
3187: }
3188:
3189: # ------------------------------------------------------------------ Course Log
3190: #
3191: # This routine flushes several buffers of non-mission-critical nature
3192: #
3193:
3194: sub flushcourselogs {
3195: &logthis('Flushing log buffers');
3196: #
3197: # course logs
3198: # This is a log of all transactions in a course, which can be used
3199: # for data mining purposes
3200: #
3201: # It also collects the courseid database, which lists last transaction
3202: # times and course titles for all courseids
3203: #
3204: my %courseidbuffer=();
3205: foreach my $crsid (keys(%courselogs)) {
3206: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3207: &escape($courselogs{$crsid}),
3208: $coursehombuf{$crsid}) eq 'ok') {
3209: delete $courselogs{$crsid};
3210: } else {
3211: &logthis('Failed to flush log buffer for '.$crsid);
3212: if (length($courselogs{$crsid})>40000) {
3213: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3214: " exceeded maximum size, deleting.</font>");
3215: delete $courselogs{$crsid};
3216: }
3217: }
3218: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3219: 'description' => $coursedescrbuf{$crsid},
3220: 'inst_code' => $courseinstcodebuf{$crsid},
3221: 'type' => $coursetypebuf{$crsid},
3222: 'owner' => $courseownerbuf{$crsid},
3223: };
3224: }
3225: #
3226: # Write course id database (reverse lookup) to homeserver of courses
3227: # Is used in pickcourse
3228: #
3229: foreach my $crs_home (keys(%courseidbuffer)) {
3230: my $response = &courseidput(&host_domain($crs_home),
3231: $courseidbuffer{$crs_home},
3232: $crs_home,'timeonly');
3233: }
3234: #
3235: # File accesses
3236: # Writes to the dynamic metadata of resources to get hit counts, etc.
3237: #
3238: foreach my $entry (keys(%accesshash)) {
3239: if ($entry =~ /___count$/) {
3240: my ($dom,$name);
3241: ($dom,$name,undef)=
3242: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3243: if (! defined($dom) || $dom eq '' ||
3244: ! defined($name) || $name eq '') {
3245: my $cid = $env{'request.course.id'};
3246: $dom = $env{'request.'.$cid.'.domain'};
3247: $name = $env{'request.'.$cid.'.num'};
3248: }
3249: my $value = $accesshash{$entry};
3250: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3251: my %temphash=($url => $value);
3252: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3253: if ($result eq 'ok') {
3254: delete $accesshash{$entry};
3255: } elsif ($result eq 'unknown_cmd') {
3256: # Target server has old code running on it.
3257: my %temphash=($entry => $value);
3258: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3259: delete $accesshash{$entry};
3260: }
3261: }
3262: } else {
3263: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3264: my %temphash=($entry => $accesshash{$entry});
3265: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3266: delete $accesshash{$entry};
3267: }
3268: }
3269: }
3270: #
3271: # Roles
3272: # Reverse lookup of user roles for course faculty/staff and co-authorship
3273: #
3274: foreach my $entry (keys(%userrolehash)) {
3275: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3276: split(/\:/,$entry);
3277: if (&Apache::lonnet::put('nohist_userroles',
3278: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3279: $rudom,$runame) eq 'ok') {
3280: delete $userrolehash{$entry};
3281: }
3282: }
3283: #
3284: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3285: #
3286: my %domrolebuffer = ();
3287: foreach my $entry (keys(%domainrolehash)) {
3288: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3289: if ($domrolebuffer{$rudom}) {
3290: $domrolebuffer{$rudom}.='&'.&escape($entry).
3291: '='.&escape($domainrolehash{$entry});
3292: } else {
3293: $domrolebuffer{$rudom}.=&escape($entry).
3294: '='.&escape($domainrolehash{$entry});
3295: }
3296: delete $domainrolehash{$entry};
3297: }
3298: foreach my $dom (keys(%domrolebuffer)) {
3299: my %servers = &get_servers($dom,'library');
3300: foreach my $tryserver (keys(%servers)) {
3301: unless (&reply('domroleput:'.$dom.':'.
3302: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3303: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3304: }
3305: }
3306: }
3307: $dumpcount++;
3308: }
3309:
3310: sub courselog {
3311: my $what=shift;
3312: $what=time.':'.$what;
3313: unless ($env{'request.course.id'}) { return ''; }
3314: $coursedombuf{$env{'request.course.id'}}=
3315: $env{'course.'.$env{'request.course.id'}.'.domain'};
3316: $coursenumbuf{$env{'request.course.id'}}=
3317: $env{'course.'.$env{'request.course.id'}.'.num'};
3318: $coursehombuf{$env{'request.course.id'}}=
3319: $env{'course.'.$env{'request.course.id'}.'.home'};
3320: $coursedescrbuf{$env{'request.course.id'}}=
3321: $env{'course.'.$env{'request.course.id'}.'.description'};
3322: $courseinstcodebuf{$env{'request.course.id'}}=
3323: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3324: $courseownerbuf{$env{'request.course.id'}}=
3325: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3326: $coursetypebuf{$env{'request.course.id'}}=
3327: $env{'course.'.$env{'request.course.id'}.'.type'};
3328: if (defined $courselogs{$env{'request.course.id'}}) {
3329: $courselogs{$env{'request.course.id'}}.='&'.$what;
3330: } else {
3331: $courselogs{$env{'request.course.id'}}.=$what;
3332: }
3333: if (length($courselogs{$env{'request.course.id'}})>4048) {
3334: &flushcourselogs();
3335: }
3336: }
3337:
3338: sub courseacclog {
3339: my $fnsymb=shift;
3340: unless ($env{'request.course.id'}) { return ''; }
3341: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3342: if ($fnsymb=~/$LONCAPA::assess_re/) {
3343: $what.=':POST';
3344: # FIXME: Probably ought to escape things....
3345: foreach my $key (keys(%env)) {
3346: if ($key=~/^form\.(.*)/) {
3347: my $formitem = $1;
3348: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3349: $what.=':'.$formitem.'='.$env{$key};
3350: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3351: $what.=':'.$formitem.'='.$env{$key};
3352: }
3353: }
3354: }
3355: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3356: # FIXME: We should not be depending on a form parameter that someone
3357: # editing lonsearchcat.pm might change in the future.
3358: if ($env{'form.phase'} eq 'course_search') {
3359: $what.= ':POST';
3360: # FIXME: Probably ought to escape things....
3361: foreach my $element ('courseexp','crsfulltext','crsrelated',
3362: 'crsdiscuss') {
3363: $what.=':'.$element.'='.$env{'form.'.$element};
3364: }
3365: }
3366: }
3367: &courselog($what);
3368: }
3369:
3370: sub countacc {
3371: my $url=&declutter(shift);
3372: return if (! defined($url) || $url eq '');
3373: unless ($env{'request.course.id'}) { return ''; }
3374: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3375: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3376: $accesshash{$key}++;
3377: }
3378:
3379: sub linklog {
3380: my ($from,$to)=@_;
3381: $from=&declutter($from);
3382: $to=&declutter($to);
3383: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3384: $accesshash{$to.'___'.$from.'___goto'}=1;
3385: }
3386:
3387: sub userrolelog {
3388: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3389: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3390: ($trole=~/^in/) || ($trole=~/^cc/) ||
3391: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3392: ($trole=~/^ta/) || ($trole=~/^co/)) {
3393: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3394: $userrolehash
3395: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3396: =$tend.':'.$tstart;
3397: }
3398: if (($env{'request.role'} =~ /dc\./) &&
3399: (($trole=~/^au/) || ($trole=~/^in/) ||
3400: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3401: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3402: ($trole=~/^co/))) {
3403: $userrolehash
3404: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3405: =$tend.':'.$tstart;
3406: }
3407: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3408: ($trole=~/^li/) || ($trole=~/^li/) ||
3409: ($trole=~/^au/) || ($trole=~/^dg/) ||
3410: ($trole=~/^sc/)) {
3411: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3412: $domainrolehash
3413: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3414: = $tend.':'.$tstart;
3415: }
3416: }
3417:
3418: sub courserolelog {
3419: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3420: if (($trole eq 'cc') || ($trole eq 'in') ||
3421: ($trole eq 'ep') || ($trole eq 'ad') ||
3422: ($trole eq 'ta') || ($trole eq 'st') ||
3423: ($trole=~/^cr/) || ($trole eq 'gr') ||
3424: ($trole eq 'co')) {
3425: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3426: my $cdom = $1;
3427: my $cnum = $2;
3428: my $sec = $3;
3429: my $namespace = 'rolelog';
3430: my %storehash = (
3431: role => $trole,
3432: start => $tstart,
3433: end => $tend,
3434: selfenroll => $selfenroll,
3435: context => $context,
3436: );
3437: if ($trole eq 'gr') {
3438: $namespace = 'groupslog';
3439: $storehash{'group'} = $sec;
3440: } else {
3441: $storehash{'section'} = $sec;
3442: }
3443: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3444: if (($trole ne 'st') || ($sec ne '')) {
3445: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3446: }
3447: }
3448: }
3449: return;
3450: }
3451:
3452: sub get_course_adv_roles {
3453: my ($cid,$codes) = @_;
3454: $cid=$env{'request.course.id'} unless (defined($cid));
3455: my %coursehash=&coursedescription($cid);
3456: my $crstype = &Apache::loncommon::course_type($cid);
3457: my %nothide=();
3458: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3459: if ($user !~ /:/) {
3460: $nothide{join(':',split(/[\@]/,$user))}=1;
3461: } else {
3462: $nothide{$user}=1;
3463: }
3464: }
3465: my %returnhash=();
3466: my %dumphash=
3467: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3468: my $now=time;
3469: my %privileged;
3470: foreach my $entry (keys(%dumphash)) {
3471: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3472: if (($tstart) && ($tstart<0)) { next; }
3473: if (($tend) && ($tend<$now)) { next; }
3474: if (($tstart) && ($now<$tstart)) { next; }
3475: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3476: if ($username eq '' || $domain eq '') { next; }
3477: unless (ref($privileged{$domain}) eq 'HASH') {
3478: my %dompersonnel =
3479: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3480: $privileged{$domain} = {};
3481: foreach my $server (keys(%dompersonnel)) {
3482: if (ref($dompersonnel{$server}) eq 'HASH') {
3483: foreach my $user (keys(%{$dompersonnel{$server}})) {
3484: my ($trole,$uname,$udom) = split(/:/,$user);
3485: $privileged{$udom}{$uname} = 1;
3486: }
3487: }
3488: }
3489: }
3490: if ((exists($privileged{$domain}{$username})) &&
3491: (!$nothide{$username.':'.$domain})) { next; }
3492: if ($role eq 'cr') { next; }
3493: if ($codes) {
3494: if ($section) { $role .= ':'.$section; }
3495: if ($returnhash{$role}) {
3496: $returnhash{$role}.=','.$username.':'.$domain;
3497: } else {
3498: $returnhash{$role}=$username.':'.$domain;
3499: }
3500: } else {
3501: my $key=&plaintext($role,$crstype);
3502: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3503: if ($returnhash{$key}) {
3504: $returnhash{$key}.=','.$username.':'.$domain;
3505: } else {
3506: $returnhash{$key}=$username.':'.$domain;
3507: }
3508: }
3509: }
3510: return %returnhash;
3511: }
3512:
3513: sub get_my_roles {
3514: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3515: unless (defined($uname)) { $uname=$env{'user.name'}; }
3516: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3517: my (%dumphash,%nothide);
3518: if ($context eq 'userroles') {
3519: my $extra = &freeze_escape({'skipcheck' => 1});
3520: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3521: } else {
3522: %dumphash=
3523: &dump('nohist_userroles',$udom,$uname);
3524: if ($hidepriv) {
3525: my %coursehash=&coursedescription($udom.'_'.$uname);
3526: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3527: if ($user !~ /:/) {
3528: $nothide{join(':',split(/[\@]/,$user))} = 1;
3529: } else {
3530: $nothide{$user} = 1;
3531: }
3532: }
3533: }
3534: }
3535: my %returnhash=();
3536: my $now=time;
3537: my %privileged;
3538: foreach my $entry (keys(%dumphash)) {
3539: my ($role,$tend,$tstart);
3540: if ($context eq 'userroles') {
3541: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3542: } else {
3543: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3544: }
3545: if (($tstart) && ($tstart<0)) { next; }
3546: my $status = 'active';
3547: if (($tend) && ($tend<=$now)) {
3548: $status = 'previous';
3549: }
3550: if (($tstart) && ($now<$tstart)) {
3551: $status = 'future';
3552: }
3553: if (ref($types) eq 'ARRAY') {
3554: if (!grep(/^\Q$status\E$/,@{$types})) {
3555: next;
3556: }
3557: } else {
3558: if ($status ne 'active') {
3559: next;
3560: }
3561: }
3562: my ($rolecode,$username,$domain,$section,$area);
3563: if ($context eq 'userroles') {
3564: ($area,$rolecode) = split(/_/,$entry);
3565: (undef,$domain,$username,$section) = split(/\//,$area);
3566: } else {
3567: ($role,$username,$domain,$section) = split(/\:/,$entry);
3568: }
3569: if (ref($roledoms) eq 'ARRAY') {
3570: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3571: next;
3572: }
3573: }
3574: if (ref($roles) eq 'ARRAY') {
3575: if (!grep(/^\Q$role\E$/,@{$roles})) {
3576: if ($role =~ /^cr\//) {
3577: if (!grep(/^cr$/,@{$roles})) {
3578: next;
3579: }
3580: } elsif ($role =~ /^gr\//) {
3581: if (!grep(/^gr$/,@{$roles})) {
3582: next;
3583: }
3584: } else {
3585: next;
3586: }
3587: }
3588: }
3589: if ($hidepriv) {
3590: if ($context eq 'userroles') {
3591: if ((&privileged($username,$domain)) &&
3592: (!$nothide{$username.':'.$domain})) {
3593: next;
3594: }
3595: } else {
3596: unless (ref($privileged{$domain}) eq 'HASH') {
3597: my %dompersonnel =
3598: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3599: $privileged{$domain} = {};
3600: if (keys(%dompersonnel)) {
3601: foreach my $server (keys(%dompersonnel)) {
3602: if (ref($dompersonnel{$server}) eq 'HASH') {
3603: foreach my $user (keys(%{$dompersonnel{$server}})) {
3604: my ($trole,$uname,$udom) = split(/:/,$user);
3605: $privileged{$udom}{$uname} = $trole;
3606: }
3607: }
3608: }
3609: }
3610: }
3611: if (exists($privileged{$domain}{$username})) {
3612: if (!$nothide{$username.':'.$domain}) {
3613: next;
3614: }
3615: }
3616: }
3617: }
3618: if ($withsec) {
3619: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3620: $tstart.':'.$tend;
3621: } else {
3622: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3623: }
3624: }
3625: return %returnhash;
3626: }
3627:
3628: # ----------------------------------------------------- Frontpage Announcements
3629: #
3630: #
3631:
3632: sub postannounce {
3633: my ($server,$text)=@_;
3634: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3635: unless ($text=~/\w/) { $text=''; }
3636: return &reply('setannounce:'.&escape($text),$server);
3637: }
3638:
3639: sub getannounce {
3640:
3641: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3642: my $announcement='';
3643: while (my $line = <$fh>) { $announcement .= $line; }
3644: close($fh);
3645: if ($announcement=~/\w/) {
3646: return
3647: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3648: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3649: } else {
3650: return '';
3651: }
3652: } else {
3653: return '';
3654: }
3655: }
3656:
3657: # ---------------------------------------------------------- Course ID routines
3658: # Deal with domain's nohist_courseid.db files
3659: #
3660:
3661: sub courseidput {
3662: my ($domain,$storehash,$coursehome,$caller) = @_;
3663: return unless (ref($storehash) eq 'HASH');
3664: my $outcome;
3665: if ($caller eq 'timeonly') {
3666: my $cids = '';
3667: foreach my $item (keys(%$storehash)) {
3668: $cids.=&escape($item).'&';
3669: }
3670: $cids=~s/\&$//;
3671: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3672: $coursehome);
3673: } else {
3674: my $items = '';
3675: foreach my $item (keys(%$storehash)) {
3676: $items.= &escape($item).'='.
3677: &freeze_escape($$storehash{$item}).'&';
3678: }
3679: $items=~s/\&$//;
3680: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3681: $coursehome);
3682: }
3683: if ($outcome eq 'unknown_cmd') {
3684: my $what;
3685: foreach my $cid (keys(%$storehash)) {
3686: $what .= &escape($cid).'=';
3687: foreach my $item ('description','inst_code','owner','type') {
3688: $what .= &escape($storehash->{$cid}{$item}).':';
3689: }
3690: $what =~ s/\:$/&/;
3691: }
3692: $what =~ s/\&$//;
3693: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3694: } else {
3695: return $outcome;
3696: }
3697: }
3698:
3699: sub courseiddump {
3700: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3701: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3702: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3703: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3704: my $as_hash = 1;
3705: my %returnhash;
3706: if (!$domfilter) { $domfilter=''; }
3707: my %libserv = &all_library();
3708: foreach my $tryserver (keys(%libserv)) {
3709: if ( ( $hostidflag == 1
3710: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3711: || (!defined($hostidflag)) ) {
3712:
3713: if (($domfilter eq '') ||
3714: (&host_domain($tryserver) eq $domfilter)) {
3715: my $rep =
3716: &reply('courseiddump:'.&host_domain($tryserver).':'.
3717: $sincefilter.':'.&escape($descfilter).':'.
3718: &escape($instcodefilter).':'.&escape($ownerfilter).
3719: ':'.&escape($coursefilter).':'.&escape($typefilter).
3720: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3721: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3722: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3723: &escape($cc_clone).':'.$cloneonly.':'.
3724: &escape($createdbefore).':'.&escape($createdafter).':'.
3725: &escape($creationcontext).':'.$domcloner,
3726: $tryserver);
3727: my @pairs=split(/\&/,$rep);
3728: foreach my $item (@pairs) {
3729: my ($key,$value)=split(/\=/,$item,2);
3730: $key = &unescape($key);
3731: next if ($key =~ /^error: 2 /);
3732: my $result = &thaw_unescape($value);
3733: if (ref($result) eq 'HASH') {
3734: $returnhash{$key}=$result;
3735: } else {
3736: my @responses = split(/:/,$value);
3737: my @items = ('description','inst_code','owner','type');
3738: for (my $i=0; $i<@responses; $i++) {
3739: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3740: }
3741: }
3742: }
3743: }
3744: }
3745: }
3746: return %returnhash;
3747: }
3748:
3749: sub courselastaccess {
3750: my ($cdom,$cnum,$hostidref) = @_;
3751: my %returnhash;
3752: if ($cdom && $cnum) {
3753: my $chome = &homeserver($cnum,$cdom);
3754: if ($chome ne 'no_host') {
3755: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3756: &extract_lastaccess(\%returnhash,$rep);
3757: }
3758: } else {
3759: if (!$cdom) { $cdom=''; }
3760: my %libserv = &all_library();
3761: foreach my $tryserver (keys(%libserv)) {
3762: if (ref($hostidref) eq 'ARRAY') {
3763: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3764: }
3765: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3766: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3767: &extract_lastaccess(\%returnhash,$rep);
3768: }
3769: }
3770: }
3771: return %returnhash;
3772: }
3773:
3774: sub extract_lastaccess {
3775: my ($returnhash,$rep) = @_;
3776: if (ref($returnhash) eq 'HASH') {
3777: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3778: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3779: $rep eq '') {
3780: my @pairs=split(/\&/,$rep);
3781: foreach my $item (@pairs) {
3782: my ($key,$value)=split(/\=/,$item,2);
3783: $key = &unescape($key);
3784: next if ($key =~ /^error: 2 /);
3785: $returnhash->{$key} = &thaw_unescape($value);
3786: }
3787: }
3788: }
3789: return;
3790: }
3791:
3792: # ---------------------------------------------------------- DC e-mail
3793:
3794: sub dcmailput {
3795: my ($domain,$msgid,$message,$server)=@_;
3796: my $status = &Apache::lonnet::critical(
3797: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3798: &escape($message),$server);
3799: return $status;
3800: }
3801:
3802: sub dcmaildump {
3803: my ($dom,$startdate,$enddate,$senders) = @_;
3804: my %returnhash=();
3805:
3806: if (defined(&domain($dom,'primary'))) {
3807: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3808: &escape($enddate).':';
3809: my @esc_senders=map { &escape($_)} @$senders;
3810: $cmd.=&escape(join('&',@esc_senders));
3811: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3812: my ($key,$value) = split(/\=/,$line,2);
3813: if (($key) && ($value)) {
3814: $returnhash{&unescape($key)} = &unescape($value);
3815: }
3816: }
3817: }
3818: return %returnhash;
3819: }
3820: # ---------------------------------------------------------- Domain roles
3821:
3822: sub get_domain_roles {
3823: my ($dom,$roles,$startdate,$enddate)=@_;
3824: if ((!defined($startdate)) || ($startdate eq '')) {
3825: $startdate = '.';
3826: }
3827: if ((!defined($enddate)) || ($enddate eq '')) {
3828: $enddate = '.';
3829: }
3830: my $rolelist;
3831: if (ref($roles) eq 'ARRAY') {
3832: $rolelist = join(':',@{$roles});
3833: }
3834: my %personnel = ();
3835:
3836: my %servers = &get_servers($dom,'library');
3837: foreach my $tryserver (keys(%servers)) {
3838: %{$personnel{$tryserver}}=();
3839: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3840: &escape($startdate).':'.
3841: &escape($enddate).':'.
3842: &escape($rolelist), $tryserver))) {
3843: my ($key,$value) = split(/\=/,$line,2);
3844: if (($key) && ($value)) {
3845: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3846: }
3847: }
3848: }
3849: return %personnel;
3850: }
3851:
3852: # ----------------------------------------------------------- Interval timing
3853:
3854: sub get_first_access {
3855: my ($type,$argsymb)=@_;
3856: my ($symb,$courseid,$udom,$uname)=&whichuser();
3857: if ($argsymb) { $symb=$argsymb; }
3858: my ($map,$id,$res)=&decode_symb($symb);
3859: if ($type eq 'course') {
3860: $res='course';
3861: } elsif ($type eq 'map') {
3862: $res=&symbread($map);
3863: } else {
3864: $res=$symb;
3865: }
3866: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3867: return $times{"$courseid\0$res"};
3868: }
3869:
3870: sub set_first_access {
3871: my ($type)=@_;
3872: my ($symb,$courseid,$udom,$uname)=&whichuser();
3873: my ($map,$id,$res)=&decode_symb($symb);
3874: if ($type eq 'course') {
3875: $res='course';
3876: } elsif ($type eq 'map') {
3877: $res=&symbread($map);
3878: } else {
3879: $res=$symb;
3880: }
3881: my $firstaccess=&get_first_access($type,$symb);
3882: if (!$firstaccess) {
3883: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3884: }
3885: return 'already_set';
3886: }
3887:
3888: # --------------------------------------------- Set Expire Date for Spreadsheet
3889:
3890: sub expirespread {
3891: my ($uname,$udom,$stype,$usymb)=@_;
3892: my $cid=$env{'request.course.id'};
3893: if ($cid) {
3894: my $now=time;
3895: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3896: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3897: $env{'course.'.$cid.'.num'}.
3898: ':nohist_expirationdates:'.
3899: &escape($key).'='.$now,
3900: $env{'course.'.$cid.'.home'})
3901: }
3902: return 'ok';
3903: }
3904:
3905: # ----------------------------------------------------- Devalidate Spreadsheets
3906:
3907: sub devalidate {
3908: my ($symb,$uname,$udom)=@_;
3909: my $cid=$env{'request.course.id'};
3910: if ($cid) {
3911: # delete the stored spreadsheets for
3912: # - the student level sheet of this user in course's homespace
3913: # - the assessment level sheet for this resource
3914: # for this user in user's homespace
3915: # - current conditional state info
3916: my $key=$uname.':'.$udom.':';
3917: my $status=
3918: &del('nohist_calculatedsheets',
3919: [$key.'studentcalc:'],
3920: $env{'course.'.$cid.'.domain'},
3921: $env{'course.'.$cid.'.num'})
3922: .' '.
3923: &del('nohist_calculatedsheets_'.$cid,
3924: [$key.'assesscalc:'.$symb],$udom,$uname);
3925: unless ($status eq 'ok ok') {
3926: &logthis('Could not devalidate spreadsheet '.
3927: $uname.' at '.$udom.' for '.
3928: $symb.': '.$status);
3929: }
3930: &delenv('user.state.'.$cid);
3931: }
3932: }
3933:
3934: sub get_scalar {
3935: my ($string,$end) = @_;
3936: my $value;
3937: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3938: $value = $1;
3939: } elsif ($$string =~ s/^([^&]*?)&//) {
3940: $value = $1;
3941: }
3942: return &unescape($value);
3943: }
3944:
3945: sub array2str {
3946: my (@array) = @_;
3947: my $result=&arrayref2str(\@array);
3948: $result=~s/^__ARRAY_REF__//;
3949: $result=~s/__END_ARRAY_REF__$//;
3950: return $result;
3951: }
3952:
3953: sub arrayref2str {
3954: my ($arrayref) = @_;
3955: my $result='__ARRAY_REF__';
3956: foreach my $elem (@$arrayref) {
3957: if(ref($elem) eq 'ARRAY') {
3958: $result.=&arrayref2str($elem).'&';
3959: } elsif(ref($elem) eq 'HASH') {
3960: $result.=&hashref2str($elem).'&';
3961: } elsif(ref($elem)) {
3962: #print("Got a ref of ".(ref($elem))." skipping.");
3963: } else {
3964: $result.=&escape($elem).'&';
3965: }
3966: }
3967: $result=~s/\&$//;
3968: $result .= '__END_ARRAY_REF__';
3969: return $result;
3970: }
3971:
3972: sub hash2str {
3973: my (%hash) = @_;
3974: my $result=&hashref2str(\%hash);
3975: $result=~s/^__HASH_REF__//;
3976: $result=~s/__END_HASH_REF__$//;
3977: return $result;
3978: }
3979:
3980: sub hashref2str {
3981: my ($hashref)=@_;
3982: my $result='__HASH_REF__';
3983: foreach my $key (sort(keys(%$hashref))) {
3984: if (ref($key) eq 'ARRAY') {
3985: $result.=&arrayref2str($key).'=';
3986: } elsif (ref($key) eq 'HASH') {
3987: $result.=&hashref2str($key).'=';
3988: } elsif (ref($key)) {
3989: $result.='=';
3990: #print("Got a ref of ".(ref($key))." skipping.");
3991: } else {
3992: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
3993: }
3994:
3995: if(ref($hashref->{$key}) eq 'ARRAY') {
3996: $result.=&arrayref2str($hashref->{$key}).'&';
3997: } elsif(ref($hashref->{$key}) eq 'HASH') {
3998: $result.=&hashref2str($hashref->{$key}).'&';
3999: } elsif(ref($hashref->{$key})) {
4000: $result.='&';
4001: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4002: } else {
4003: $result.=&escape($hashref->{$key}).'&';
4004: }
4005: }
4006: $result=~s/\&$//;
4007: $result .= '__END_HASH_REF__';
4008: return $result;
4009: }
4010:
4011: sub str2hash {
4012: my ($string)=@_;
4013: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4014: return %$hash;
4015: }
4016:
4017: sub str2hashref {
4018: my ($string) = @_;
4019:
4020: my %hash;
4021:
4022: if($string !~ /^__HASH_REF__/) {
4023: if (! ($string eq '' || !defined($string))) {
4024: $hash{'error'}='Not hash reference';
4025: }
4026: return (\%hash, $string);
4027: }
4028:
4029: $string =~ s/^__HASH_REF__//;
4030:
4031: while($string !~ /^__END_HASH_REF__/) {
4032: #key
4033: my $key='';
4034: if($string =~ /^__HASH_REF__/) {
4035: ($key, $string)=&str2hashref($string);
4036: if(defined($key->{'error'})) {
4037: $hash{'error'}='Bad data';
4038: return (\%hash, $string);
4039: }
4040: } elsif($string =~ /^__ARRAY_REF__/) {
4041: ($key, $string)=&str2arrayref($string);
4042: if($key->[0] eq 'Array reference error') {
4043: $hash{'error'}='Bad data';
4044: return (\%hash, $string);
4045: }
4046: } else {
4047: $string =~ s/^(.*?)=//;
4048: $key=&unescape($1);
4049: }
4050: $string =~ s/^=//;
4051:
4052: #value
4053: my $value='';
4054: if($string =~ /^__HASH_REF__/) {
4055: ($value, $string)=&str2hashref($string);
4056: if(defined($value->{'error'})) {
4057: $hash{'error'}='Bad data';
4058: return (\%hash, $string);
4059: }
4060: } elsif($string =~ /^__ARRAY_REF__/) {
4061: ($value, $string)=&str2arrayref($string);
4062: if($value->[0] eq 'Array reference error') {
4063: $hash{'error'}='Bad data';
4064: return (\%hash, $string);
4065: }
4066: } else {
4067: $value=&get_scalar(\$string,'__END_HASH_REF__');
4068: }
4069: $string =~ s/^&//;
4070:
4071: $hash{$key}=$value;
4072: }
4073:
4074: $string =~ s/^__END_HASH_REF__//;
4075:
4076: return (\%hash, $string);
4077: }
4078:
4079: sub str2array {
4080: my ($string)=@_;
4081: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4082: return @$array;
4083: }
4084:
4085: sub str2arrayref {
4086: my ($string) = @_;
4087: my @array;
4088:
4089: if($string !~ /^__ARRAY_REF__/) {
4090: if (! ($string eq '' || !defined($string))) {
4091: $array[0]='Array reference error';
4092: }
4093: return (\@array, $string);
4094: }
4095:
4096: $string =~ s/^__ARRAY_REF__//;
4097:
4098: while($string !~ /^__END_ARRAY_REF__/) {
4099: my $value='';
4100: if($string =~ /^__HASH_REF__/) {
4101: ($value, $string)=&str2hashref($string);
4102: if(defined($value->{'error'})) {
4103: $array[0] ='Array reference error';
4104: return (\@array, $string);
4105: }
4106: } elsif($string =~ /^__ARRAY_REF__/) {
4107: ($value, $string)=&str2arrayref($string);
4108: if($value->[0] eq 'Array reference error') {
4109: $array[0] ='Array reference error';
4110: return (\@array, $string);
4111: }
4112: } else {
4113: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4114: }
4115: $string =~ s/^&//;
4116:
4117: push(@array, $value);
4118: }
4119:
4120: $string =~ s/^__END_ARRAY_REF__//;
4121:
4122: return (\@array, $string);
4123: }
4124:
4125: # -------------------------------------------------------------------Temp Store
4126:
4127: sub tmpreset {
4128: my ($symb,$namespace,$domain,$stuname) = @_;
4129: if (!$symb) {
4130: $symb=&symbread();
4131: if (!$symb) { $symb= $env{'request.url'}; }
4132: }
4133: $symb=escape($symb);
4134:
4135: if (!$namespace) { $namespace=$env{'request.state'}; }
4136: $namespace=~s/\//\_/g;
4137: $namespace=~s/\W//g;
4138:
4139: if (!$domain) { $domain=$env{'user.domain'}; }
4140: if (!$stuname) { $stuname=$env{'user.name'}; }
4141: if ($domain eq 'public' && $stuname eq 'public') {
4142: $stuname=$ENV{'REMOTE_ADDR'};
4143: }
4144: my $path=LONCAPA::tempdir();
4145: my %hash;
4146: if (tie(%hash,'GDBM_File',
4147: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4148: &GDBM_WRCREAT(),0640)) {
4149: foreach my $key (keys(%hash)) {
4150: if ($key=~ /:$symb/) {
4151: delete($hash{$key});
4152: }
4153: }
4154: }
4155: }
4156:
4157: sub tmpstore {
4158: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4159:
4160: if (!$symb) {
4161: $symb=&symbread();
4162: if (!$symb) { $symb= $env{'request.url'}; }
4163: }
4164: $symb=escape($symb);
4165:
4166: if (!$namespace) {
4167: # I don't think we would ever want to store this for a course.
4168: # it seems this will only be used if we don't have a course.
4169: #$namespace=$env{'request.course.id'};
4170: #if (!$namespace) {
4171: $namespace=$env{'request.state'};
4172: #}
4173: }
4174: $namespace=~s/\//\_/g;
4175: $namespace=~s/\W//g;
4176: if (!$domain) { $domain=$env{'user.domain'}; }
4177: if (!$stuname) { $stuname=$env{'user.name'}; }
4178: if ($domain eq 'public' && $stuname eq 'public') {
4179: $stuname=$ENV{'REMOTE_ADDR'};
4180: }
4181: my $now=time;
4182: my %hash;
4183: my $path=LONCAPA::tempdir();
4184: if (tie(%hash,'GDBM_File',
4185: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4186: &GDBM_WRCREAT(),0640)) {
4187: $hash{"version:$symb"}++;
4188: my $version=$hash{"version:$symb"};
4189: my $allkeys='';
4190: foreach my $key (keys(%$storehash)) {
4191: $allkeys.=$key.':';
4192: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4193: }
4194: $hash{"$version:$symb:timestamp"}=$now;
4195: $allkeys.='timestamp';
4196: $hash{"$version:keys:$symb"}=$allkeys;
4197: if (untie(%hash)) {
4198: return 'ok';
4199: } else {
4200: return "error:$!";
4201: }
4202: } else {
4203: return "error:$!";
4204: }
4205: }
4206:
4207: # -----------------------------------------------------------------Temp Restore
4208:
4209: sub tmprestore {
4210: my ($symb,$namespace,$domain,$stuname) = @_;
4211:
4212: if (!$symb) {
4213: $symb=&symbread();
4214: if (!$symb) { $symb= $env{'request.url'}; }
4215: }
4216: $symb=escape($symb);
4217:
4218: if (!$namespace) { $namespace=$env{'request.state'}; }
4219:
4220: if (!$domain) { $domain=$env{'user.domain'}; }
4221: if (!$stuname) { $stuname=$env{'user.name'}; }
4222: if ($domain eq 'public' && $stuname eq 'public') {
4223: $stuname=$ENV{'REMOTE_ADDR'};
4224: }
4225: my %returnhash;
4226: $namespace=~s/\//\_/g;
4227: $namespace=~s/\W//g;
4228: my %hash;
4229: my $path=LONCAPA::tempdir();
4230: if (tie(%hash,'GDBM_File',
4231: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4232: &GDBM_READER(),0640)) {
4233: my $version=$hash{"version:$symb"};
4234: $returnhash{'version'}=$version;
4235: my $scope;
4236: for ($scope=1;$scope<=$version;$scope++) {
4237: my $vkeys=$hash{"$scope:keys:$symb"};
4238: my @keys=split(/:/,$vkeys);
4239: my $key;
4240: $returnhash{"$scope:keys"}=$vkeys;
4241: foreach $key (@keys) {
4242: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4243: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4244: }
4245: }
4246: if (!(untie(%hash))) {
4247: return "error:$!";
4248: }
4249: } else {
4250: return "error:$!";
4251: }
4252: return %returnhash;
4253: }
4254:
4255: # ----------------------------------------------------------------------- Store
4256:
4257: sub store {
4258: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4259: my $home='';
4260:
4261: if ($stuname) { $home=&homeserver($stuname,$domain); }
4262:
4263: $symb=&symbclean($symb);
4264: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4265:
4266: if (!$domain) { $domain=$env{'user.domain'}; }
4267: if (!$stuname) { $stuname=$env{'user.name'}; }
4268:
4269: &devalidate($symb,$stuname,$domain);
4270:
4271: $symb=escape($symb);
4272: if (!$namespace) {
4273: unless ($namespace=$env{'request.course.id'}) {
4274: return '';
4275: }
4276: }
4277: if (!$home) { $home=$env{'user.home'}; }
4278:
4279: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4280: $$storehash{'host'}=$perlvar{'lonHostID'};
4281:
4282: my $namevalue='';
4283: foreach my $key (keys(%$storehash)) {
4284: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4285: }
4286: $namevalue=~s/\&$//;
4287: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4288: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4289: }
4290:
4291: # -------------------------------------------------------------- Critical Store
4292:
4293: sub cstore {
4294: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4295: my $home='';
4296:
4297: if ($stuname) { $home=&homeserver($stuname,$domain); }
4298:
4299: $symb=&symbclean($symb);
4300: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4301:
4302: if (!$domain) { $domain=$env{'user.domain'}; }
4303: if (!$stuname) { $stuname=$env{'user.name'}; }
4304:
4305: &devalidate($symb,$stuname,$domain);
4306:
4307: $symb=escape($symb);
4308: if (!$namespace) {
4309: unless ($namespace=$env{'request.course.id'}) {
4310: return '';
4311: }
4312: }
4313: if (!$home) { $home=$env{'user.home'}; }
4314:
4315: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4316: $$storehash{'host'}=$perlvar{'lonHostID'};
4317:
4318: my $namevalue='';
4319: foreach my $key (keys(%$storehash)) {
4320: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4321: }
4322: $namevalue=~s/\&$//;
4323: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4324: return critical
4325: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4326: }
4327:
4328: # --------------------------------------------------------------------- Restore
4329:
4330: sub restore {
4331: my ($symb,$namespace,$domain,$stuname) = @_;
4332: my $home='';
4333:
4334: if ($stuname) { $home=&homeserver($stuname,$domain); }
4335:
4336: if (!$symb) {
4337: unless ($symb=escape(&symbread())) { return ''; }
4338: } else {
4339: $symb=&escape(&symbclean($symb));
4340: }
4341: if (!$namespace) {
4342: unless ($namespace=$env{'request.course.id'}) {
4343: return '';
4344: }
4345: }
4346: if (!$domain) { $domain=$env{'user.domain'}; }
4347: if (!$stuname) { $stuname=$env{'user.name'}; }
4348: if (!$home) { $home=$env{'user.home'}; }
4349: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4350:
4351: my %returnhash=();
4352: foreach my $line (split(/\&/,$answer)) {
4353: my ($name,$value)=split(/\=/,$line);
4354: $returnhash{&unescape($name)}=&thaw_unescape($value);
4355: }
4356: my $version;
4357: for ($version=1;$version<=$returnhash{'version'};$version++) {
4358: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4359: $returnhash{$item}=$returnhash{$version.':'.$item};
4360: }
4361: }
4362: return %returnhash;
4363: }
4364:
4365: # ---------------------------------------------------------- Course Description
4366: #
4367: #
4368:
4369: sub coursedescription {
4370: my ($courseid,$args)=@_;
4371: $courseid=~s/^\///;
4372: $courseid=~s/\_/\//g;
4373: my ($cdomain,$cnum)=split(/\//,$courseid);
4374: my $chome=&homeserver($cnum,$cdomain);
4375: my $normalid=$cdomain.'_'.$cnum;
4376: # need to always cache even if we get errors otherwise we keep
4377: # trying and trying and trying to get the course description.
4378: my %envhash=();
4379: my %returnhash=();
4380:
4381: my $expiretime=600;
4382: if ($env{'request.course.id'} eq $normalid) {
4383: $expiretime=120;
4384: }
4385:
4386: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4387: if (!$args->{'freshen_cache'}
4388: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4389: foreach my $key (keys(%env)) {
4390: next if ($key !~ /^\Q$prefix\E(.*)/);
4391: my ($setting) = $1;
4392: $returnhash{$setting} = $env{$key};
4393: }
4394: return %returnhash;
4395: }
4396:
4397: # get the data again
4398:
4399: if (!$args->{'one_time'}) {
4400: $envhash{'course.'.$normalid.'.last_cache'}=time;
4401: }
4402:
4403: if ($chome ne 'no_host') {
4404: %returnhash=&dump('environment',$cdomain,$cnum);
4405: if (!exists($returnhash{'con_lost'})) {
4406: my $username = $env{'user.name'}; # Defult username
4407: if(defined $args->{'user'}) {
4408: $username = $args->{'user'};
4409: }
4410: $returnhash{'home'}= $chome;
4411: $returnhash{'domain'} = $cdomain;
4412: $returnhash{'num'} = $cnum;
4413: if (!defined($returnhash{'type'})) {
4414: $returnhash{'type'} = 'Course';
4415: }
4416: while (my ($name,$value) = each %returnhash) {
4417: $envhash{'course.'.$normalid.'.'.$name}=$value;
4418: }
4419: $returnhash{'url'}=&clutter($returnhash{'url'});
4420: $returnhash{'fn'}=LONCAPA::tempdir() .
4421: $username.'_'.$cdomain.'_'.$cnum;
4422: $envhash{'course.'.$normalid.'.home'}=$chome;
4423: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4424: $envhash{'course.'.$normalid.'.num'}=$cnum;
4425: }
4426: }
4427: if (!$args->{'one_time'}) {
4428: &appenv(\%envhash);
4429: }
4430: return %returnhash;
4431: }
4432:
4433: sub update_released_required {
4434: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4435: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4436: $cid = $env{'request.course.id'};
4437: $cdom = $env{'course.'.$cid.'.domain'};
4438: $cnum = $env{'course.'.$cid.'.num'};
4439: $chome = $env{'course.'.$cid.'.home'};
4440: }
4441: if ($needsrelease) {
4442: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4443: my $needsupdate;
4444: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4445: $needsupdate = 1;
4446: } else {
4447: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4448: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4449: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4450: $needsupdate = 1;
4451: }
4452: }
4453: if ($needsupdate) {
4454: my %needshash = (
4455: 'internal.releaserequired' => $needsrelease,
4456: );
4457: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4458: if ($putresult eq 'ok') {
4459: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4460: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4461: if (ref($crsinfo{$cid}) eq 'HASH') {
4462: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4463: &courseidput($cdom,\%crsinfo,$chome,'notime');
4464: }
4465: }
4466: }
4467: }
4468: return;
4469: }
4470:
4471: # -------------------------------------------------See if a user is privileged
4472:
4473: sub privileged {
4474: my ($username,$domain)=@_;
4475: my $rolesdump=&reply("dump:$domain:$username:roles",
4476: &homeserver($username,$domain));
4477: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4478: ($rolesdump =~ /^error:/)) {
4479: return 0;
4480: }
4481: my $now=time;
4482: if ($rolesdump ne '') {
4483: foreach my $entry (split(/&/,$rolesdump)) {
4484: if ($entry!~/^rolesdef_/) {
4485: my ($area,$role)=split(/=/,$entry);
4486: $area=~s/\_\w\w$//;
4487: my ($trole,$tend,$tstart)=split(/_/,$role);
4488: if (($trole eq 'dc') || ($trole eq 'su')) {
4489: my $active=1;
4490: if ($tend) {
4491: if ($tend<$now) { $active=0; }
4492: }
4493: if ($tstart) {
4494: if ($tstart>$now) { $active=0; }
4495: }
4496: if ($active) { return 1; }
4497: }
4498: }
4499: }
4500: }
4501: return 0;
4502: }
4503:
4504: # -------------------------------------------------------- Get user privileges
4505:
4506: sub rolesinit {
4507: my ($domain,$username,$authhost)=@_;
4508: my $now=time;
4509: my %userroles = ('user.login.time' => $now);
4510: my $extra = &freeze_escape({'skipcheck' => 1});
4511: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4512: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4513: ($rolesdump =~ /^error:/)) {
4514: return \%userroles;
4515: }
4516: my %allroles=();
4517: my %allgroups=();
4518:
4519: if ($rolesdump ne '') {
4520: foreach my $entry (split(/&/,$rolesdump)) {
4521: if ($entry!~/^rolesdef_/) {
4522: my ($area,$role)=split(/=/,$entry);
4523: $area=~s/\_\w\w$//;
4524: my ($trole,$tend,$tstart,$group_privs);
4525: if ($role=~/^cr/) {
4526: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4527: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4528: ($tend,$tstart)=split('_',$trest);
4529: } else {
4530: $trole=$role;
4531: }
4532: } elsif ($role =~ m|^gr/|) {
4533: ($trole,$tend,$tstart) = split(/_/,$role);
4534: next if ($tstart eq '-1');
4535: ($trole,$group_privs) = split(/\//,$trole);
4536: $group_privs = &unescape($group_privs);
4537: } else {
4538: ($trole,$tend,$tstart)=split(/_/,$role);
4539: }
4540: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4541: $username);
4542: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4543: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4544: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4545: if (($area ne '') && ($trole ne '')) {
4546: my $spec=$trole.'.'.$area;
4547: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4548: if ($trole =~ /^cr\//) {
4549: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4550: } elsif ($trole eq 'gr') {
4551: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4552: } else {
4553: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4554: }
4555: }
4556: }
4557: }
4558: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4559: $userroles{'user.adv'} = $adv;
4560: $userroles{'user.author'} = $author;
4561: $env{'user.adv'}=$adv;
4562: }
4563: return \%userroles;
4564: }
4565:
4566: sub set_arearole {
4567: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4568: # log the associated role with the area
4569: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4570: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4571: }
4572:
4573: sub custom_roleprivs {
4574: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4575: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4576: my $homsvr=homeserver($rauthor,$rdomain);
4577: if (&hostname($homsvr) ne '') {
4578: my ($rdummy,$roledef)=
4579: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4580: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4581: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4582: if (defined($syspriv)) {
4583: if ($trest =~ /^$match_community$/) {
4584: $syspriv =~ s/bre\&S//;
4585: }
4586: $$allroles{'cm./'}.=':'.$syspriv;
4587: $$allroles{$spec.'./'}.=':'.$syspriv;
4588: }
4589: if ($tdomain ne '') {
4590: if (defined($dompriv)) {
4591: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4592: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4593: }
4594: if (($trest ne '') && (defined($coursepriv))) {
4595: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4596: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4597: }
4598: }
4599: }
4600: }
4601: }
4602:
4603: sub group_roleprivs {
4604: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4605: my $access = 1;
4606: my $now = time;
4607: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4608: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4609: if ($access) {
4610: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4611: $$allgroups{$course}{$group} .=':'.$group_privs;
4612: }
4613: }
4614:
4615: sub standard_roleprivs {
4616: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4617: if (defined($pr{$trole.':s'})) {
4618: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4619: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4620: }
4621: if ($tdomain ne '') {
4622: if (defined($pr{$trole.':d'})) {
4623: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4624: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4625: }
4626: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4627: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4628: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4629: }
4630: }
4631: }
4632:
4633: sub set_userprivs {
4634: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4635: my $author=0;
4636: my $adv=0;
4637: my %grouproles = ();
4638: if (keys(%{$allgroups}) > 0) {
4639: my @groupkeys;
4640: foreach my $role (keys(%{$allroles})) {
4641: push(@groupkeys,$role);
4642: }
4643: if (ref($groups_roles) eq 'HASH') {
4644: foreach my $key (keys(%{$groups_roles})) {
4645: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4646: push(@groupkeys,$key);
4647: }
4648: }
4649: }
4650: if (@groupkeys > 0) {
4651: foreach my $role (@groupkeys) {
4652: my ($trole,$area,$sec,$extendedarea);
4653: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4654: $trole = $1;
4655: $area = $2;
4656: $sec = $3;
4657: $extendedarea = $area.$sec;
4658: if (exists($$allgroups{$area})) {
4659: foreach my $group (keys(%{$$allgroups{$area}})) {
4660: my $spec = $trole.'.'.$extendedarea;
4661: $grouproles{$spec.'.'.$area.'/'.$group} =
4662: $$allgroups{$area}{$group};
4663: }
4664: }
4665: }
4666: }
4667: }
4668: }
4669: foreach my $group (keys(%grouproles)) {
4670: $$allroles{$group} = $grouproles{$group};
4671: }
4672: foreach my $role (keys(%{$allroles})) {
4673: my %thesepriv;
4674: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4675: foreach my $item (split(/:/,$$allroles{$role})) {
4676: if ($item ne '') {
4677: my ($privilege,$restrictions)=split(/&/,$item);
4678: if ($restrictions eq '') {
4679: $thesepriv{$privilege}='F';
4680: } elsif ($thesepriv{$privilege} ne 'F') {
4681: $thesepriv{$privilege}.=$restrictions;
4682: }
4683: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4684: }
4685: }
4686: my $thesestr='';
4687: foreach my $priv (sort(keys(%thesepriv))) {
4688: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4689: }
4690: $userroles->{'user.priv.'.$role} = $thesestr;
4691: }
4692: return ($author,$adv);
4693: }
4694:
4695: sub role_status {
4696: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4697: my @pwhere = ();
4698: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4699: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4700: unless (!defined($$role) || $$role eq '') {
4701: $$where=join('.',@pwhere);
4702: $$trolecode=$$role.'.'.$$where;
4703: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4704: $$tstatus='is';
4705: if ($$tstart && $$tstart>$update) {
4706: $$tstatus='future';
4707: if ($$tstart<$now) {
4708: if ($$tstart && $$tstart>$refresh) {
4709: if (($$where ne '') && ($$role ne '')) {
4710: my (%allroles,%allgroups,$group_privs,
4711: %groups_roles,@rolecodes);
4712: my %userroles = (
4713: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4714: );
4715: @rolecodes = ('cm');
4716: my $spec=$$role.'.'.$$where;
4717: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4718: if ($$role =~ /^cr\//) {
4719: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4720: push(@rolecodes,'cr');
4721: } elsif ($$role eq 'gr') {
4722: push(@rolecodes,$$role);
4723: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4724: $env{'user.name'});
4725: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4726: (undef,my $group_privs) = split(/\//,$trole);
4727: $group_privs = &unescape($group_privs);
4728: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4729: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4730: &get_groups_roles($tdomain,$trest,
4731: \%course_roles,\@rolecodes,
4732: \%groups_roles);
4733: } else {
4734: push(@rolecodes,$$role);
4735: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4736: }
4737: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4738: &appenv(\%userroles,\@rolecodes);
4739: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4740: }
4741: }
4742: $$tstatus = 'is';
4743: }
4744: }
4745: if ($$tend) {
4746: if ($$tend<$update) {
4747: $$tstatus='expired';
4748: } elsif ($$tend<$now) {
4749: $$tstatus='will_not';
4750: }
4751: }
4752: }
4753: }
4754: }
4755:
4756: sub get_groups_roles {
4757: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4758: return unless((ref($cdom_courseroles) eq 'HASH') &&
4759: (ref($rolecodes) eq 'ARRAY') &&
4760: (ref($groups_roles) eq 'HASH'));
4761: if (keys(%{$cdom_courseroles}) > 0) {
4762: my ($cnum) = ($rest =~ /^($match_courseid)/);
4763: if ($cdom ne '' && $cnum ne '') {
4764: foreach my $key (keys(%{$cdom_courseroles})) {
4765: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4766: my $crsrole = $1;
4767: my $crssec = $2;
4768: if ($crsrole =~ /^cr/) {
4769: unless (grep(/^cr$/,@{$rolecodes})) {
4770: push(@{$rolecodes},'cr');
4771: }
4772: } else {
4773: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4774: push(@{$rolecodes},$crsrole);
4775: }
4776: }
4777: my $rolekey = "$crsrole./$cdom/$cnum";
4778: if ($crssec ne '') {
4779: $rolekey .= "/$crssec";
4780: }
4781: $rolekey .= './';
4782: $groups_roles->{$rolekey} = $rolecodes;
4783: }
4784: }
4785: }
4786: }
4787: return;
4788: }
4789:
4790: sub delete_env_groupprivs {
4791: my ($where,$courseroles,$possroles) = @_;
4792: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4793: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4794: unless (ref($courseroles->{$udom}) eq 'HASH') {
4795: %{$courseroles->{$udom}} =
4796: &get_my_roles('','','userroles',['active'],
4797: $possroles,[$udom],1);
4798: }
4799: if (ref($courseroles->{$udom}) eq 'HASH') {
4800: foreach my $item (keys(%{$courseroles->{$udom}})) {
4801: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4802: my $area = '/'.$cdom.'/'.$cnum;
4803: my $privkey = "user.priv.$crsrole.$area";
4804: if ($crssec ne '') {
4805: $privkey .= '/'.$crssec;
4806: }
4807: $privkey .= ".$area/$group";
4808: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4809: }
4810: }
4811: return;
4812: }
4813:
4814: sub check_adhoc_privs {
4815: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4816: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4817: if ($env{$cckey}) {
4818: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4819: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4820: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4821: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4822: }
4823: } else {
4824: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4825: }
4826: }
4827:
4828: sub set_adhoc_privileges {
4829: # role can be cc or ca
4830: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4831: my $area = '/'.$dcdom.'/'.$pickedcourse;
4832: my $spec = $role.'.'.$area;
4833: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4834: $env{'user.name'});
4835: my %ccrole = ();
4836: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4837: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4838: &appenv(\%userroles,[$role,'cm']);
4839: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4840: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4841: &appenv( {'request.role' => $spec,
4842: 'request.role.domain' => $dcdom,
4843: 'request.course.sec' => ''
4844: }
4845: );
4846: my $tadv=0;
4847: if (&allowed('adv') eq 'F') { $tadv=1; }
4848: &appenv({'request.role.adv' => $tadv});
4849: }
4850: }
4851:
4852: # --------------------------------------------------------------- get interface
4853:
4854: sub get {
4855: my ($namespace,$storearr,$udomain,$uname)=@_;
4856: my $items='';
4857: foreach my $item (@$storearr) {
4858: $items.=&escape($item).'&';
4859: }
4860: $items=~s/\&$//;
4861: if (!$udomain) { $udomain=$env{'user.domain'}; }
4862: if (!$uname) { $uname=$env{'user.name'}; }
4863: my $uhome=&homeserver($uname,$udomain);
4864:
4865: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4866: my @pairs=split(/\&/,$rep);
4867: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4868: return @pairs;
4869: }
4870: my %returnhash=();
4871: my $i=0;
4872: foreach my $item (@$storearr) {
4873: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4874: $i++;
4875: }
4876: return %returnhash;
4877: }
4878:
4879: # --------------------------------------------------------------- del interface
4880:
4881: sub del {
4882: my ($namespace,$storearr,$udomain,$uname)=@_;
4883: my $items='';
4884: foreach my $item (@$storearr) {
4885: $items.=&escape($item).'&';
4886: }
4887:
4888: $items=~s/\&$//;
4889: if (!$udomain) { $udomain=$env{'user.domain'}; }
4890: if (!$uname) { $uname=$env{'user.name'}; }
4891: my $uhome=&homeserver($uname,$udomain);
4892: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4893: }
4894:
4895: # -------------------------------------------------------------- dump interface
4896:
4897: sub dump {
4898: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
4899: if (!$udomain) { $udomain=$env{'user.domain'}; }
4900: if (!$uname) { $uname=$env{'user.name'}; }
4901: my $uhome=&homeserver($uname,$udomain);
4902: if ($regexp) {
4903: $regexp=&escape($regexp);
4904: } else {
4905: $regexp='.';
4906: }
4907: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
4908: my @pairs=split(/\&/,$rep);
4909: my %returnhash=();
4910: if (!($rep =~ /^error/ )) {
4911: foreach my $item (@pairs) {
4912: my ($key,$value)=split(/=/,$item,2);
4913: $key = &unescape($key);
4914: next if ($key =~ /^error: 2 /);
4915: $returnhash{$key}=&thaw_unescape($value);
4916: }
4917: }
4918: return %returnhash;
4919: }
4920:
4921:
4922: # --------------------------------------------------------- dumpstore interface
4923:
4924: sub dumpstore {
4925: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4926: if (!$udomain) { $udomain=$env{'user.domain'}; }
4927: if (!$uname) { $uname=$env{'user.name'}; }
4928: my $uhome=&homeserver($uname,$udomain);
4929: if ($regexp) {
4930: $regexp=&escape($regexp);
4931: } else {
4932: $regexp='.';
4933: }
4934: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4935: my @pairs=split(/\&/,$rep);
4936: my %returnhash=();
4937: foreach my $item (@pairs) {
4938: my ($key,$value)=split(/=/,$item,2);
4939: next if ($key =~ /^error: 2 /);
4940: $returnhash{$key}=&thaw_unescape($value);
4941: }
4942: return %returnhash;
4943: }
4944:
4945: # -------------------------------------------------------------- keys interface
4946:
4947: sub getkeys {
4948: my ($namespace,$udomain,$uname)=@_;
4949: if (!$udomain) { $udomain=$env{'user.domain'}; }
4950: if (!$uname) { $uname=$env{'user.name'}; }
4951: my $uhome=&homeserver($uname,$udomain);
4952: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4953: my @keyarray=();
4954: foreach my $key (split(/\&/,$rep)) {
4955: next if ($key =~ /^error: 2 /);
4956: push(@keyarray,&unescape($key));
4957: }
4958: return @keyarray;
4959: }
4960:
4961: # --------------------------------------------------------------- currentdump
4962: sub currentdump {
4963: my ($courseid,$sdom,$sname)=@_;
4964: $courseid = $env{'request.course.id'} if (! defined($courseid));
4965: $sdom = $env{'user.domain'} if (! defined($sdom));
4966: $sname = $env{'user.name'} if (! defined($sname));
4967: my $uhome = &homeserver($sname,$sdom);
4968: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4969: return if ($rep =~ /^(error:|no_such_host)/);
4970: #
4971: my %returnhash=();
4972: #
4973: if ($rep eq "unknown_cmd") {
4974: # an old lond will not know currentdump
4975: # Do a dump and make it look like a currentdump
4976: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4977: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4978: my %hash = @tmp;
4979: @tmp=();
4980: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4981: } else {
4982: my @pairs=split(/\&/,$rep);
4983: foreach my $pair (@pairs) {
4984: my ($key,$value)=split(/=/,$pair,2);
4985: my ($symb,$param) = split(/:/,$key);
4986: $returnhash{&unescape($symb)}->{&unescape($param)} =
4987: &thaw_unescape($value);
4988: }
4989: }
4990: return %returnhash;
4991: }
4992:
4993: sub convert_dump_to_currentdump{
4994: my %hash = %{shift()};
4995: my %returnhash;
4996: # Code ripped from lond, essentially. The only difference
4997: # here is the unescaping done by lonnet::dump(). Conceivably
4998: # we might run in to problems with parameter names =~ /^v\./
4999: while (my ($key,$value) = each(%hash)) {
5000: my ($v,$symb,$param) = split(/:/,$key);
5001: $symb = &unescape($symb);
5002: $param = &unescape($param);
5003: next if ($v eq 'version' || $symb eq 'keys');
5004: next if (exists($returnhash{$symb}) &&
5005: exists($returnhash{$symb}->{$param}) &&
5006: $returnhash{$symb}->{'v.'.$param} > $v);
5007: $returnhash{$symb}->{$param}=$value;
5008: $returnhash{$symb}->{'v.'.$param}=$v;
5009: }
5010: #
5011: # Remove all of the keys in the hashes which keep track of
5012: # the version of the parameter.
5013: while (my ($symb,$param_hash) = each(%returnhash)) {
5014: # use a foreach because we are going to delete from the hash.
5015: foreach my $key (keys(%$param_hash)) {
5016: delete($param_hash->{$key}) if ($key =~ /^v\./);
5017: }
5018: }
5019: return \%returnhash;
5020: }
5021:
5022: # ------------------------------------------------------ critical inc interface
5023:
5024: sub cinc {
5025: return &inc(@_,'critical');
5026: }
5027:
5028: # --------------------------------------------------------------- inc interface
5029:
5030: sub inc {
5031: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5032: if (!$udomain) { $udomain=$env{'user.domain'}; }
5033: if (!$uname) { $uname=$env{'user.name'}; }
5034: my $uhome=&homeserver($uname,$udomain);
5035: my $items='';
5036: if (! ref($store)) {
5037: # got a single value, so use that instead
5038: $items = &escape($store).'=&';
5039: } elsif (ref($store) eq 'SCALAR') {
5040: $items = &escape($$store).'=&';
5041: } elsif (ref($store) eq 'ARRAY') {
5042: $items = join('=&',map {&escape($_);} @{$store});
5043: } elsif (ref($store) eq 'HASH') {
5044: while (my($key,$value) = each(%{$store})) {
5045: $items.= &escape($key).'='.&escape($value).'&';
5046: }
5047: }
5048: $items=~s/\&$//;
5049: if ($critical) {
5050: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5051: } else {
5052: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5053: }
5054: }
5055:
5056: # --------------------------------------------------------------- put interface
5057:
5058: sub put {
5059: my ($namespace,$storehash,$udomain,$uname)=@_;
5060: if (!$udomain) { $udomain=$env{'user.domain'}; }
5061: if (!$uname) { $uname=$env{'user.name'}; }
5062: my $uhome=&homeserver($uname,$udomain);
5063: my $items='';
5064: foreach my $item (keys(%$storehash)) {
5065: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5066: }
5067: $items=~s/\&$//;
5068: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5069: }
5070:
5071: # ------------------------------------------------------------ newput interface
5072:
5073: sub newput {
5074: my ($namespace,$storehash,$udomain,$uname)=@_;
5075: if (!$udomain) { $udomain=$env{'user.domain'}; }
5076: if (!$uname) { $uname=$env{'user.name'}; }
5077: my $uhome=&homeserver($uname,$udomain);
5078: my $items='';
5079: foreach my $key (keys(%$storehash)) {
5080: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5081: }
5082: $items=~s/\&$//;
5083: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5084: }
5085:
5086: # --------------------------------------------------------- putstore interface
5087:
5088: sub putstore {
5089: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5090: if (!$udomain) { $udomain=$env{'user.domain'}; }
5091: if (!$uname) { $uname=$env{'user.name'}; }
5092: my $uhome=&homeserver($uname,$udomain);
5093: my $items='';
5094: foreach my $key (keys(%$storehash)) {
5095: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5096: }
5097: $items=~s/\&$//;
5098: my $esc_symb=&escape($symb);
5099: my $esc_v=&escape($version);
5100: my $reply =
5101: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5102: $uhome);
5103: if ($reply eq 'unknown_cmd') {
5104: # gfall back to way things use to be done
5105: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5106: $uname);
5107: }
5108: return $reply;
5109: }
5110:
5111: sub old_putstore {
5112: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5113: if (!$udomain) { $udomain=$env{'user.domain'}; }
5114: if (!$uname) { $uname=$env{'user.name'}; }
5115: my $uhome=&homeserver($uname,$udomain);
5116: my %newstorehash;
5117: foreach my $item (keys(%$storehash)) {
5118: my $key = $version.':'.&escape($symb).':'.$item;
5119: $newstorehash{$key} = $storehash->{$item};
5120: }
5121: my $items='';
5122: my %allitems = ();
5123: foreach my $item (keys(%newstorehash)) {
5124: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5125: my $key = $1.':keys:'.$2;
5126: $allitems{$key} .= $3.':';
5127: }
5128: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5129: }
5130: foreach my $item (keys(%allitems)) {
5131: $allitems{$item} =~ s/\:$//;
5132: $items.= $item.'='.$allitems{$item}.'&';
5133: }
5134: $items=~s/\&$//;
5135: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5136: }
5137:
5138: # ------------------------------------------------------ critical put interface
5139:
5140: sub cput {
5141: my ($namespace,$storehash,$udomain,$uname)=@_;
5142: if (!$udomain) { $udomain=$env{'user.domain'}; }
5143: if (!$uname) { $uname=$env{'user.name'}; }
5144: my $uhome=&homeserver($uname,$udomain);
5145: my $items='';
5146: foreach my $item (keys(%$storehash)) {
5147: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5148: }
5149: $items=~s/\&$//;
5150: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5151: }
5152:
5153: # -------------------------------------------------------------- eget interface
5154:
5155: sub eget {
5156: my ($namespace,$storearr,$udomain,$uname)=@_;
5157: my $items='';
5158: foreach my $item (@$storearr) {
5159: $items.=&escape($item).'&';
5160: }
5161: $items=~s/\&$//;
5162: if (!$udomain) { $udomain=$env{'user.domain'}; }
5163: if (!$uname) { $uname=$env{'user.name'}; }
5164: my $uhome=&homeserver($uname,$udomain);
5165: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5166: my @pairs=split(/\&/,$rep);
5167: my %returnhash=();
5168: my $i=0;
5169: foreach my $item (@$storearr) {
5170: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5171: $i++;
5172: }
5173: return %returnhash;
5174: }
5175:
5176: # ------------------------------------------------------------ tmpput interface
5177: sub tmpput {
5178: my ($storehash,$server,$context)=@_;
5179: my $items='';
5180: foreach my $item (keys(%$storehash)) {
5181: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5182: }
5183: $items=~s/\&$//;
5184: if (defined($context)) {
5185: $items .= ':'.&escape($context);
5186: }
5187: return &reply("tmpput:$items",$server);
5188: }
5189:
5190: # ------------------------------------------------------------ tmpget interface
5191: sub tmpget {
5192: my ($token,$server)=@_;
5193: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5194: my $rep=&reply("tmpget:$token",$server);
5195: my %returnhash;
5196: foreach my $item (split(/\&/,$rep)) {
5197: my ($key,$value)=split(/=/,$item);
5198: next if ($key =~ /^error: 2 /);
5199: $returnhash{&unescape($key)}=&thaw_unescape($value);
5200: }
5201: return %returnhash;
5202: }
5203:
5204: # ------------------------------------------------------------ tmpdel interface
5205: sub tmpdel {
5206: my ($token,$server)=@_;
5207: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5208: return &reply("tmpdel:$token",$server);
5209: }
5210:
5211: # -------------------------------------------------- portfolio access checking
5212:
5213: sub portfolio_access {
5214: my ($requrl) = @_;
5215: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5216: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5217: if ($result) {
5218: my %setters;
5219: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5220: my ($startblock,$endblock) =
5221: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5222: if ($startblock && $endblock) {
5223: return 'B';
5224: }
5225: } else {
5226: my ($startblock,$endblock) =
5227: &Apache::loncommon::blockcheck(\%setters,'port');
5228: if ($startblock && $endblock) {
5229: return 'B';
5230: }
5231: }
5232: }
5233: if ($result eq 'ok') {
5234: return 'F';
5235: } elsif ($result =~ /^[^:]+:guest_/) {
5236: return 'A';
5237: }
5238: return '';
5239: }
5240:
5241: sub get_portfolio_access {
5242: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5243:
5244: if (!ref($access_hash)) {
5245: my $current_perms = &get_portfile_permissions($udom,$unum);
5246: my %access_controls = &get_access_controls($current_perms,$group,
5247: $file_name);
5248: $access_hash = $access_controls{$file_name};
5249: }
5250:
5251: my ($public,$guest,@domains,@users,@courses,@groups);
5252: my $now = time;
5253: if (ref($access_hash) eq 'HASH') {
5254: foreach my $key (keys(%{$access_hash})) {
5255: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5256: if ($start > $now) {
5257: next;
5258: }
5259: if ($end && $end<$now) {
5260: next;
5261: }
5262: if ($scope eq 'public') {
5263: $public = $key;
5264: last;
5265: } elsif ($scope eq 'guest') {
5266: $guest = $key;
5267: } elsif ($scope eq 'domains') {
5268: push(@domains,$key);
5269: } elsif ($scope eq 'users') {
5270: push(@users,$key);
5271: } elsif ($scope eq 'course') {
5272: push(@courses,$key);
5273: } elsif ($scope eq 'group') {
5274: push(@groups,$key);
5275: }
5276: }
5277: if ($public) {
5278: return 'ok';
5279: }
5280: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5281: if ($guest) {
5282: return $guest;
5283: }
5284: } else {
5285: if (@domains > 0) {
5286: foreach my $domkey (@domains) {
5287: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5288: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5289: return 'ok';
5290: }
5291: }
5292: }
5293: }
5294: if (@users > 0) {
5295: foreach my $userkey (@users) {
5296: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5297: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5298: if (ref($item) eq 'HASH') {
5299: if (($item->{'uname'} eq $env{'user.name'}) &&
5300: ($item->{'udom'} eq $env{'user.domain'})) {
5301: return 'ok';
5302: }
5303: }
5304: }
5305: }
5306: }
5307: }
5308: my %roleshash;
5309: my @courses_and_groups = @courses;
5310: push(@courses_and_groups,@groups);
5311: if (@courses_and_groups > 0) {
5312: my (%allgroups,%allroles);
5313: my ($start,$end,$role,$sec,$group);
5314: foreach my $envkey (%env) {
5315: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5316: my $cid = $2.'_'.$3;
5317: if ($1 eq 'gr') {
5318: $group = $4;
5319: $allgroups{$cid}{$group} = $env{$envkey};
5320: } else {
5321: if ($4 eq '') {
5322: $sec = 'none';
5323: } else {
5324: $sec = $4;
5325: }
5326: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5327: }
5328: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5329: my $cid = $2.'_'.$3;
5330: if ($4 eq '') {
5331: $sec = 'none';
5332: } else {
5333: $sec = $4;
5334: }
5335: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5336: }
5337: }
5338: if (keys(%allroles) == 0) {
5339: return;
5340: }
5341: foreach my $key (@courses_and_groups) {
5342: my %content = %{$$access_hash{$key}};
5343: my $cnum = $content{'number'};
5344: my $cdom = $content{'domain'};
5345: my $cid = $cdom.'_'.$cnum;
5346: if (!exists($allroles{$cid})) {
5347: next;
5348: }
5349: foreach my $role_id (keys(%{$content{'roles'}})) {
5350: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5351: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5352: my @status = @{$content{'roles'}{$role_id}{'access'}};
5353: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5354: foreach my $role (keys(%{$allroles{$cid}})) {
5355: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5356: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5357: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5358: if (grep/^all$/,@sections) {
5359: return 'ok';
5360: } else {
5361: if (grep/^$sec$/,@sections) {
5362: return 'ok';
5363: }
5364: }
5365: }
5366: }
5367: if (keys(%{$allgroups{$cid}}) == 0) {
5368: if (grep/^none$/,@groups) {
5369: return 'ok';
5370: }
5371: } else {
5372: if (grep/^all$/,@groups) {
5373: return 'ok';
5374: }
5375: foreach my $group (keys(%{$allgroups{$cid}})) {
5376: if (grep/^$group$/,@groups) {
5377: return 'ok';
5378: }
5379: }
5380: }
5381: }
5382: }
5383: }
5384: }
5385: }
5386: if ($guest) {
5387: return $guest;
5388: }
5389: }
5390: }
5391: return;
5392: }
5393:
5394: sub course_group_datechecker {
5395: my ($dates,$now,$status) = @_;
5396: my ($start,$end) = split(/\./,$dates);
5397: if (!$start && !$end) {
5398: return 'ok';
5399: }
5400: if (grep/^active$/,@{$status}) {
5401: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5402: return 'ok';
5403: }
5404: }
5405: if (grep/^previous$/,@{$status}) {
5406: if ($end > $now ) {
5407: return 'ok';
5408: }
5409: }
5410: if (grep/^future$/,@{$status}) {
5411: if ($start > $now) {
5412: return 'ok';
5413: }
5414: }
5415: return;
5416: }
5417:
5418: sub parse_portfolio_url {
5419: my ($url) = @_;
5420:
5421: my ($type,$udom,$unum,$group,$file_name);
5422:
5423: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5424: $type = 1;
5425: $udom = $1;
5426: $unum = $2;
5427: $file_name = $3;
5428: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5429: $type = 2;
5430: $udom = $1;
5431: $unum = $2;
5432: $group = $3;
5433: $file_name = $3.'/'.$4;
5434: }
5435: if (wantarray) {
5436: return ($type,$udom,$unum,$file_name,$group);
5437: }
5438: return $type;
5439: }
5440:
5441: sub is_portfolio_url {
5442: my ($url) = @_;
5443: return scalar(&parse_portfolio_url($url));
5444: }
5445:
5446: sub is_portfolio_file {
5447: my ($file) = @_;
5448: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5449: return 1;
5450: }
5451: return;
5452: }
5453:
5454: sub usertools_access {
5455: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5456: my ($access,%tools);
5457: if ($context eq '') {
5458: $context = 'tools';
5459: }
5460: if ($context eq 'requestcourses') {
5461: %tools = (
5462: official => 1,
5463: unofficial => 1,
5464: community => 1,
5465: );
5466: } else {
5467: %tools = (
5468: aboutme => 1,
5469: blog => 1,
5470: portfolio => 1,
5471: );
5472: }
5473: return if (!defined($tools{$tool}));
5474:
5475: if ((!defined($udom)) || (!defined($uname))) {
5476: $udom = $env{'user.domain'};
5477: $uname = $env{'user.name'};
5478: }
5479:
5480: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5481: if ($action ne 'reload') {
5482: if ($context eq 'requestcourses') {
5483: return $env{'environment.canrequest.'.$tool};
5484: } else {
5485: return $env{'environment.availabletools.'.$tool};
5486: }
5487: }
5488: }
5489:
5490: my ($toolstatus,$inststatus);
5491:
5492: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5493: ($action ne 'reload')) {
5494: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5495: $inststatus = $env{'environment.inststatus'};
5496: } else {
5497: if (ref($userenvref) eq 'HASH') {
5498: $toolstatus = $userenvref->{$context.'.'.$tool};
5499: $inststatus = $userenvref->{'inststatus'};
5500: } else {
5501: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5502: $toolstatus = $userenv{$context.'.'.$tool};
5503: $inststatus = $userenv{'inststatus'};
5504: }
5505: }
5506:
5507: if ($toolstatus ne '') {
5508: if ($toolstatus) {
5509: $access = 1;
5510: } else {
5511: $access = 0;
5512: }
5513: return $access;
5514: }
5515:
5516: my ($is_adv,%domdef);
5517: if (ref($is_advref) eq 'HASH') {
5518: $is_adv = $is_advref->{'is_adv'};
5519: } else {
5520: $is_adv = &is_advanced_user($udom,$uname);
5521: }
5522: if (ref($domdefref) eq 'HASH') {
5523: %domdef = %{$domdefref};
5524: } else {
5525: %domdef = &get_domain_defaults($udom);
5526: }
5527: if (ref($domdef{$tool}) eq 'HASH') {
5528: if ($is_adv) {
5529: if ($domdef{$tool}{'_LC_adv'} ne '') {
5530: if ($domdef{$tool}{'_LC_adv'}) {
5531: $access = 1;
5532: } else {
5533: $access = 0;
5534: }
5535: return $access;
5536: }
5537: }
5538: if ($inststatus ne '') {
5539: my ($hasaccess,$hasnoaccess);
5540: foreach my $affiliation (split(/:/,$inststatus)) {
5541: if ($domdef{$tool}{$affiliation} ne '') {
5542: if ($domdef{$tool}{$affiliation}) {
5543: $hasaccess = 1;
5544: } else {
5545: $hasnoaccess = 1;
5546: }
5547: }
5548: }
5549: if ($hasaccess || $hasnoaccess) {
5550: if ($hasaccess) {
5551: $access = 1;
5552: } elsif ($hasnoaccess) {
5553: $access = 0;
5554: }
5555: return $access;
5556: }
5557: } else {
5558: if ($domdef{$tool}{'default'} ne '') {
5559: if ($domdef{$tool}{'default'}) {
5560: $access = 1;
5561: } elsif ($domdef{$tool}{'default'} == 0) {
5562: $access = 0;
5563: }
5564: return $access;
5565: }
5566: }
5567: } else {
5568: if ($context eq 'tools') {
5569: $access = 1;
5570: } else {
5571: $access = 0;
5572: }
5573: return $access;
5574: }
5575: }
5576:
5577: sub is_course_owner {
5578: my ($cdom,$cnum,$udom,$uname) = @_;
5579: if (($udom eq '') || ($uname eq '')) {
5580: $udom = $env{'user.domain'};
5581: $uname = $env{'user.name'};
5582: }
5583: unless (($udom eq '') || ($uname eq '')) {
5584: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5585: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5586: return 1;
5587: } else {
5588: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5589: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5590: return 1;
5591: }
5592: }
5593: }
5594: }
5595: return;
5596: }
5597:
5598: sub is_advanced_user {
5599: my ($udom,$uname) = @_;
5600: if ($udom ne '' && $uname ne '') {
5601: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5602: if (wantarray) {
5603: return ($env{'user.adv'},$env{'user.author'});
5604: } else {
5605: return $env{'user.adv'};
5606: }
5607: }
5608: }
5609: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5610: my %allroles;
5611: my ($is_adv,$is_author);
5612: foreach my $role (keys(%roleshash)) {
5613: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5614: my $area = '/'.$tdomain.'/'.$trest;
5615: if ($sec ne '') {
5616: $area .= '/'.$sec;
5617: }
5618: if (($area ne '') && ($trole ne '')) {
5619: my $spec=$trole.'.'.$area;
5620: if ($trole =~ /^cr\//) {
5621: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5622: } elsif ($trole ne 'gr') {
5623: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5624: }
5625: if ($trole eq 'au') {
5626: $is_author = 1;
5627: }
5628: }
5629: }
5630: foreach my $role (keys(%allroles)) {
5631: last if ($is_adv);
5632: foreach my $item (split(/:/,$allroles{$role})) {
5633: if ($item ne '') {
5634: my ($privilege,$restrictions)=split(/&/,$item);
5635: if ($privilege eq 'adv') {
5636: $is_adv = 1;
5637: last;
5638: }
5639: }
5640: }
5641: }
5642: if (wantarray) {
5643: return ($is_adv,$is_author);
5644: }
5645: return $is_adv;
5646: }
5647:
5648: sub check_can_request {
5649: my ($dom,$can_request,$request_domains) = @_;
5650: my $canreq = 0;
5651: my ($types,$typename) = &Apache::loncommon::course_types();
5652: my @options = ('approval','validate','autolimit');
5653: my $optregex = join('|',@options);
5654: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5655: foreach my $type (@{$types}) {
5656: if (&usertools_access($env{'user.name'},
5657: $env{'user.domain'},
5658: $type,undef,'requestcourses')) {
5659: $canreq ++;
5660: if (ref($request_domains) eq 'HASH') {
5661: push(@{$request_domains->{$type}},$env{'user.domain'});
5662: }
5663: if ($dom eq $env{'user.domain'}) {
5664: $can_request->{$type} = 1;
5665: }
5666: }
5667: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5668: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5669: if (@curr > 0) {
5670: foreach my $item (@curr) {
5671: if (ref($request_domains) eq 'HASH') {
5672: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5673: if ($otherdom ne '') {
5674: if (ref($request_domains->{$type}) eq 'ARRAY') {
5675: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5676: push(@{$request_domains->{$type}},$otherdom);
5677: }
5678: } else {
5679: push(@{$request_domains->{$type}},$otherdom);
5680: }
5681: }
5682: }
5683: }
5684: unless($dom eq $env{'user.domain'}) {
5685: $canreq ++;
5686: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5687: $can_request->{$type} = 1;
5688: }
5689: }
5690: }
5691: }
5692: }
5693: }
5694: return $canreq;
5695: }
5696:
5697: # ---------------------------------------------- Custom access rule evaluation
5698:
5699: sub customaccess {
5700: my ($priv,$uri)=@_;
5701: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5702: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5703: $udom = &LONCAPA::clean_domain($udom);
5704: $ucrs = &LONCAPA::clean_username($ucrs);
5705: my $access=0;
5706: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5707: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5708: if ($type eq 'user') {
5709: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5710: my ($tdom,$tuname)=split(m{/},$scope);
5711: if ($tdom) {
5712: if ($tdom ne $env{'user.domain'}) { next; }
5713: }
5714: if ($tuname) {
5715: if ($tuname ne $env{'user.name'}) { next; }
5716: }
5717: $access=($effect eq 'allow');
5718: last;
5719: }
5720: } else {
5721: if ($role) {
5722: if ($role ne $urole) { next; }
5723: }
5724: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5725: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5726: if ($tdom) {
5727: if ($tdom ne $udom) { next; }
5728: }
5729: if ($tcrs) {
5730: if ($tcrs ne $ucrs) { next; }
5731: }
5732: if ($tsec) {
5733: if ($tsec ne $usec) { next; }
5734: }
5735: $access=($effect eq 'allow');
5736: last;
5737: }
5738: if ($realm eq '' && $role eq '') {
5739: $access=($effect eq 'allow');
5740: }
5741: }
5742: }
5743: return $access;
5744: }
5745:
5746: # ------------------------------------------------- Check for a user privilege
5747:
5748: sub allowed {
5749: my ($priv,$uri,$symb,$role)=@_;
5750: my $ver_orguri=$uri;
5751: $uri=&deversion($uri);
5752: my $orguri=$uri;
5753: $uri=&declutter($uri);
5754:
5755: if ($priv eq 'evb') {
5756: # Evade communication block restrictions for specified role in a course
5757: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5758: return $1;
5759: } else {
5760: return;
5761: }
5762: }
5763:
5764: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5765: # Free bre access to adm and meta resources
5766: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5767: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5768: && ($priv eq 'bre')) {
5769: return 'F';
5770: }
5771:
5772: # Free bre access to user's own portfolio contents
5773: my ($space,$domain,$name,@dir)=split('/',$uri);
5774: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5775: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5776: my %setters;
5777: my ($startblock,$endblock) =
5778: &Apache::loncommon::blockcheck(\%setters,'port');
5779: if ($startblock && $endblock) {
5780: return 'B';
5781: } else {
5782: return 'F';
5783: }
5784: }
5785:
5786: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5787: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5788: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5789: if (exists($env{'request.course.id'})) {
5790: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5791: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5792: if (($domain eq $cdom) && ($name eq $cnum)) {
5793: my $courseprivid=$env{'request.course.id'};
5794: $courseprivid=~s/\_/\//;
5795: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5796: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5797: return $1;
5798: } else {
5799: if ($env{'request.course.sec'}) {
5800: $courseprivid.='/'.$env{'request.course.sec'};
5801: }
5802: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5803: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5804: return $2;
5805: }
5806: }
5807: }
5808: }
5809: }
5810:
5811: # Free bre to public access
5812:
5813: if ($priv eq 'bre') {
5814: my $copyright=&metadata($uri,'copyright');
5815: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5816: return 'F';
5817: }
5818: if ($copyright eq 'priv') {
5819: $uri=~/([^\/]+)\/([^\/]+)\//;
5820: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5821: return '';
5822: }
5823: }
5824: if ($copyright eq 'domain') {
5825: $uri=~/([^\/]+)\/([^\/]+)\//;
5826: unless (($env{'user.domain'} eq $1) ||
5827: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5828: return '';
5829: }
5830: }
5831: if ($env{'request.role'}=~ /li\.\//) {
5832: # Library role, so allow browsing of resources in this domain.
5833: return 'F';
5834: }
5835: if ($copyright eq 'custom') {
5836: unless (&customaccess($priv,$uri)) { return ''; }
5837: }
5838: }
5839: # Domain coordinator is trying to create a course
5840: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5841: # uri is the requested domain in this case.
5842: # comparison to 'request.role.domain' shows if the user has selected
5843: # a role of dc for the domain in question.
5844: return 'F' if ($uri eq $env{'request.role.domain'});
5845: }
5846:
5847: my $thisallowed='';
5848: my $statecond=0;
5849: my $courseprivid='';
5850:
5851: my $ownaccess;
5852: # Community Coordinator or Assistant Co-author browsing resource space.
5853: if (($priv eq 'bro') && ($env{'user.author'})) {
5854: if ($uri eq '') {
5855: $ownaccess = 1;
5856: } else {
5857: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5858: my $udom = $env{'user.domain'};
5859: my $uname = $env{'user.name'};
5860: if ($uri =~ m{^\Q$udom\E/?$}) {
5861: $ownaccess = 1;
5862: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5863: unless ($uri =~ m{\.\./}) {
5864: $ownaccess = 1;
5865: }
5866: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5867: my $now = time;
5868: if ($uri =~ m{^([^/]+)/?$}) {
5869: my $adom = $1;
5870: foreach my $key (keys(%env)) {
5871: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5872: my ($start,$end) = split('.',$env{$key});
5873: if (($now >= $start) && (!$end || $end < $now)) {
5874: $ownaccess = 1;
5875: last;
5876: }
5877: }
5878: }
5879: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5880: my $adom = $1;
5881: my $aname = $2;
5882: foreach my $role ('ca','aa') {
5883: if ($env{"user.role.$role./$adom/$aname"}) {
5884: my ($start,$end) =
5885: split('.',$env{"user.role.$role./$adom/$aname"});
5886: if (($now >= $start) && (!$end || $end < $now)) {
5887: $ownaccess = 1;
5888: last;
5889: }
5890: }
5891: }
5892: }
5893: }
5894: }
5895: }
5896: }
5897:
5898: # Course
5899:
5900: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5901: unless (($priv eq 'bro') && (!$ownaccess)) {
5902: $thisallowed.=$1;
5903: }
5904: }
5905:
5906: # Domain
5907:
5908: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5909: =~/\Q$priv\E\&([^\:]*)/) {
5910: unless (($priv eq 'bro') && (!$ownaccess)) {
5911: $thisallowed.=$1;
5912: }
5913: }
5914:
5915: # User who is not author or co-author might still be able to edit
5916: # resource of an author in the domain (e.g., if Domain Coordinator).
5917: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
5918: (&allowed('mdc',$env{'request.course.id'}))) {
5919: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
5920: $thisallowed.=$1;
5921: }
5922: }
5923:
5924: # Course: uri itself is a course
5925: my $courseuri=$uri;
5926: $courseuri=~s/\_(\d)/\/$1/;
5927: $courseuri=~s/^([^\/])/\/$1/;
5928:
5929: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5930: =~/\Q$priv\E\&([^\:]*)/) {
5931: unless (($priv eq 'bro') && (!$ownaccess)) {
5932: $thisallowed.=$1;
5933: }
5934: }
5935:
5936: # URI is an uploaded document for this course, default permissions don't matter
5937: # not allowing 'edit' access (editupload) to uploaded course docs
5938: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5939: $thisallowed='';
5940: my ($match)=&is_on_map($uri);
5941: if ($match) {
5942: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5943: =~/\Q$priv\E\&([^\:]*)/) {
5944: $thisallowed.=$1;
5945: }
5946: } else {
5947: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5948: if ($refuri) {
5949: if ($refuri =~ m|^/adm/|) {
5950: $thisallowed='F';
5951: } else {
5952: $refuri=&declutter($refuri);
5953: my ($match) = &is_on_map($refuri);
5954: if ($match) {
5955: $thisallowed='F';
5956: }
5957: }
5958: }
5959: }
5960: }
5961:
5962: if ($priv eq 'bre'
5963: && $thisallowed ne 'F'
5964: && $thisallowed ne '2'
5965: && &is_portfolio_url($uri)) {
5966: $thisallowed = &portfolio_access($uri);
5967: }
5968:
5969: # Full access at system, domain or course-wide level? Exit.
5970: if ($thisallowed=~/F/) {
5971: return 'F';
5972: }
5973:
5974: # If this is generating or modifying users, exit with special codes
5975:
5976: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5977: if (($priv eq 'cca') || ($priv eq 'caa')) {
5978: my ($audom,$auname)=split('/',$uri);
5979: # no author name given, so this just checks on the general right to make a co-author in this domain
5980: unless ($auname) { return $thisallowed; }
5981: # an author name is given, so we are about to actually make a co-author for a certain account
5982: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5983: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5984: ($audom ne $env{'request.role.domain'}))) { return ''; }
5985: }
5986: return $thisallowed;
5987: }
5988: #
5989: # Gathered so far: system, domain and course wide privileges
5990: #
5991: # Course: See if uri or referer is an individual resource that is part of
5992: # the course
5993:
5994: if ($env{'request.course.id'}) {
5995:
5996: $courseprivid=$env{'request.course.id'};
5997: if ($env{'request.course.sec'}) {
5998: $courseprivid.='/'.$env{'request.course.sec'};
5999: }
6000: $courseprivid=~s/\_/\//;
6001: my $checkreferer=1;
6002: my ($match,$cond)=&is_on_map($uri);
6003: if ($match) {
6004: $statecond=$cond;
6005: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6006: =~/\Q$priv\E\&([^\:]*)/) {
6007: $thisallowed.=$1;
6008: $checkreferer=0;
6009: }
6010: }
6011:
6012: if ($checkreferer) {
6013: my $refuri=$env{'httpref.'.$orguri};
6014: unless ($refuri) {
6015: foreach my $key (keys(%env)) {
6016: if ($key=~/^httpref\..*\*/) {
6017: my $pattern=$key;
6018: $pattern=~s/^httpref\.\/res\///;
6019: $pattern=~s/\*/\[\^\/\]\+/g;
6020: $pattern=~s/\//\\\//g;
6021: if ($orguri=~/$pattern/) {
6022: $refuri=$env{$key};
6023: }
6024: }
6025: }
6026: }
6027:
6028: if ($refuri) {
6029: $refuri=&declutter($refuri);
6030: my ($match,$cond)=&is_on_map($refuri);
6031: if ($match) {
6032: my $refstatecond=$cond;
6033: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6034: =~/\Q$priv\E\&([^\:]*)/) {
6035: $thisallowed.=$1;
6036: $uri=$refuri;
6037: $statecond=$refstatecond;
6038: }
6039: }
6040: }
6041: }
6042: }
6043:
6044: #
6045: # Gathered now: all privileges that could apply, and condition number
6046: #
6047: #
6048: # Full or no access?
6049: #
6050:
6051: if ($thisallowed=~/F/) {
6052: return 'F';
6053: }
6054:
6055: unless ($thisallowed) {
6056: return '';
6057: }
6058:
6059: # Restrictions exist, deal with them
6060: #
6061: # C:according to course preferences
6062: # R:according to resource settings
6063: # L:unless locked
6064: # X:according to user session state
6065: #
6066:
6067: # Possibly locked functionality, check all courses
6068: # Locks might take effect only after 10 minutes cache expiration for other
6069: # courses, and 2 minutes for current course
6070:
6071: my $envkey;
6072: if ($thisallowed=~/L/) {
6073: foreach $envkey (keys(%env)) {
6074: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6075: my $courseid=$2;
6076: my $roleid=$1.'.'.$2;
6077: $courseid=~s/^\///;
6078: my $expiretime=600;
6079: if ($env{'request.role'} eq $roleid) {
6080: $expiretime=120;
6081: }
6082: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6083: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6084: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6085: &coursedescription($courseid,{'freshen_cache' => 1});
6086: }
6087: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6088: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6089: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6090: &log($env{'user.domain'},$env{'user.name'},
6091: $env{'user.home'},
6092: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6093: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6094: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6095: return '';
6096: }
6097: }
6098: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6099: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6100: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6101: &log($env{'user.domain'},$env{'user.name'},
6102: $env{'user.home'},
6103: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6104: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6105: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6106: return '';
6107: }
6108: }
6109: }
6110: }
6111: }
6112:
6113: #
6114: # Rest of the restrictions depend on selected course
6115: #
6116:
6117: unless ($env{'request.course.id'}) {
6118: if ($thisallowed eq 'A') {
6119: return 'A';
6120: } elsif ($thisallowed eq 'B') {
6121: return 'B';
6122: } else {
6123: return '1';
6124: }
6125: }
6126:
6127: #
6128: # Now user is definitely in a course
6129: #
6130:
6131:
6132: # Course preferences
6133:
6134: if ($thisallowed=~/C/) {
6135: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6136: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6137: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6138: =~/\Q$rolecode\E/) {
6139: if (($priv ne 'pch') && ($priv ne 'plc')) {
6140: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6141: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6142: $env{'request.course.id'});
6143: }
6144: return '';
6145: }
6146:
6147: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6148: =~/\Q$unamedom\E/) {
6149: if (($priv ne 'pch') && ($priv ne 'plc')) {
6150: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6151: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6152: $env{'request.course.id'});
6153: }
6154: return '';
6155: }
6156: }
6157:
6158: # Resource preferences
6159:
6160: if ($thisallowed=~/R/) {
6161: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6162: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6163: if (($priv ne 'pch') && ($priv ne 'plc')) {
6164: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6165: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6166: }
6167: return '';
6168: }
6169: }
6170:
6171: # Restricted by state or randomout?
6172:
6173: if ($thisallowed=~/X/) {
6174: if ($env{'acc.randomout'}) {
6175: if (!$symb) { $symb=&symbread($uri,1); }
6176: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6177: return '';
6178: }
6179: }
6180: if (&condval($statecond)) {
6181: return '2';
6182: } else {
6183: return '';
6184: }
6185: }
6186:
6187: if ($thisallowed eq 'A') {
6188: return 'A';
6189: } elsif ($thisallowed eq 'B') {
6190: return 'B';
6191: }
6192: return 'F';
6193: }
6194: #
6195: # Removes the versino from a URI and
6196: # splits it in to its filename and path to the filename.
6197: # Seems like File::Basename could have done this more clearly.
6198: # Parameters:
6199: # $uri - input URI
6200: # Returns:
6201: # Two element list consisting of
6202: # $pathname - the URI up to and excluding the trailing /
6203: # $filename - The part of the URI following the last /
6204: # NOTE:
6205: # Another realization of this is simply:
6206: # use File::Basename;
6207: # ...
6208: # $uri = shift;
6209: # $filename = basename($uri);
6210: # $path = dirname($uri);
6211: # return ($filename, $path);
6212: #
6213: # The implementation below is probably faster however.
6214: #
6215: sub split_uri_for_cond {
6216: my $uri=&deversion(&declutter(shift));
6217: my @uriparts=split(/\//,$uri);
6218: my $filename=pop(@uriparts);
6219: my $pathname=join('/',@uriparts);
6220: return ($pathname,$filename);
6221: }
6222: # --------------------------------------------------- Is a resource on the map?
6223:
6224: sub is_on_map {
6225: my ($pathname,$filename) = &split_uri_for_cond(shift);
6226: #Trying to find the conditional for the file
6227: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6228: /\&\Q$filename\E\:([\d\|]+)\&/);
6229: if ($match) {
6230: return (1,$1);
6231: } else {
6232: return (0,0);
6233: }
6234: }
6235:
6236: # --------------------------------------------------------- Get symb from alias
6237:
6238: sub get_symb_from_alias {
6239: my $symb=shift;
6240: my ($map,$resid,$url)=&decode_symb($symb);
6241: # Already is a symb
6242: if ($url) { return $symb; }
6243: # Must be an alias
6244: my $aliassymb='';
6245: my %bighash;
6246: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6247: &GDBM_READER(),0640)) {
6248: my $rid=$bighash{'mapalias_'.$symb};
6249: if ($rid) {
6250: my ($mapid,$resid)=split(/\./,$rid);
6251: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6252: $resid,$bighash{'src_'.$rid});
6253: }
6254: untie %bighash;
6255: }
6256: return $aliassymb;
6257: }
6258:
6259: # ----------------------------------------------------------------- Define Role
6260:
6261: sub definerole {
6262: if (allowed('mcr','/')) {
6263: my ($rolename,$sysrole,$domrole,$courole)=@_;
6264: foreach my $role (split(':',$sysrole)) {
6265: my ($crole,$cqual)=split(/\&/,$role);
6266: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6267: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6268: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6269: return "refused:s:$crole&$cqual";
6270: }
6271: }
6272: }
6273: foreach my $role (split(':',$domrole)) {
6274: my ($crole,$cqual)=split(/\&/,$role);
6275: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6276: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6277: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6278: return "refused:d:$crole&$cqual";
6279: }
6280: }
6281: }
6282: foreach my $role (split(':',$courole)) {
6283: my ($crole,$cqual)=split(/\&/,$role);
6284: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6285: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6286: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6287: return "refused:c:$crole&$cqual";
6288: }
6289: }
6290: }
6291: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6292: "$env{'user.domain'}:$env{'user.name'}:".
6293: "rolesdef_$rolename=".
6294: escape($sysrole.'_'.$domrole.'_'.$courole);
6295: return reply($command,$env{'user.home'});
6296: } else {
6297: return 'refused';
6298: }
6299: }
6300:
6301: # ---------------- Make a metadata query against the network of library servers
6302:
6303: sub metadata_query {
6304: my ($query,$custom,$customshow,$server_array)=@_;
6305: my %rhash;
6306: my %libserv = &all_library();
6307: my @server_list = (defined($server_array) ? @$server_array
6308: : keys(%libserv) );
6309: for my $server (@server_list) {
6310: unless ($custom or $customshow) {
6311: my $reply=&reply("querysend:".&escape($query),$server);
6312: $rhash{$server}=$reply;
6313: }
6314: else {
6315: my $reply=&reply("querysend:".&escape($query).':'.
6316: &escape($custom).':'.&escape($customshow),
6317: $server);
6318: $rhash{$server}=$reply;
6319: }
6320: }
6321: return \%rhash;
6322: }
6323:
6324: # ----------------------------------------- Send log queries and wait for reply
6325:
6326: sub log_query {
6327: my ($uname,$udom,$query,%filters)=@_;
6328: my $uhome=&homeserver($uname,$udom);
6329: if ($uhome eq 'no_host') { return 'error: no_host'; }
6330: my $uhost=&hostname($uhome);
6331: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6332: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6333: $uhome);
6334: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6335: return get_query_reply($queryid);
6336: }
6337:
6338: # -------------------------- Update MySQL table for portfolio file
6339:
6340: sub update_portfolio_table {
6341: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6342: if ($group ne '') {
6343: $file_name =~s /^\Q$group\E//;
6344: }
6345: my $homeserver = &homeserver($uname,$udom);
6346: my $queryid=
6347: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6348: ':'.&escape($file_name).':'.$action,$homeserver);
6349: my $reply = &get_query_reply($queryid);
6350: return $reply;
6351: }
6352:
6353: # -------------------------- Update MySQL allusers table
6354:
6355: sub update_allusers_table {
6356: my ($uname,$udom,$names) = @_;
6357: my $homeserver = &homeserver($uname,$udom);
6358: my $queryid=
6359: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6360: 'lastname='.&escape($names->{'lastname'}).'%%'.
6361: 'firstname='.&escape($names->{'firstname'}).'%%'.
6362: 'middlename='.&escape($names->{'middlename'}).'%%'.
6363: 'generation='.&escape($names->{'generation'}).'%%'.
6364: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6365: 'id='.&escape($names->{'id'}),$homeserver);
6366: return;
6367: }
6368:
6369: # ------- Request retrieval of institutional classlists for course(s)
6370:
6371: sub fetch_enrollment_query {
6372: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6373: my $homeserver;
6374: my $maxtries = 1;
6375: if ($context eq 'automated') {
6376: $homeserver = $perlvar{'lonHostID'};
6377: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6378: } else {
6379: $homeserver = &homeserver($cnum,$dom);
6380: }
6381: my $host=&hostname($homeserver);
6382: my $cmd = '';
6383: foreach my $affiliate (keys(%{$affiliatesref})) {
6384: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6385: }
6386: $cmd =~ s/%%$//;
6387: $cmd = &escape($cmd);
6388: my $query = 'fetchenrollment';
6389: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6390: unless ($queryid=~/^\Q$host\E\_/) {
6391: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6392: return 'error: '.$queryid;
6393: }
6394: my $reply = &get_query_reply($queryid);
6395: my $tries = 1;
6396: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6397: $reply = &get_query_reply($queryid);
6398: $tries ++;
6399: }
6400: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6401: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6402: } else {
6403: my @responses = split(/:/,$reply);
6404: if ($homeserver eq $perlvar{'lonHostID'}) {
6405: foreach my $line (@responses) {
6406: my ($key,$value) = split(/=/,$line,2);
6407: $$replyref{$key} = $value;
6408: }
6409: } else {
6410: my $pathname = LONCAPA::tempdir();
6411: foreach my $line (@responses) {
6412: my ($key,$value) = split(/=/,$line);
6413: $$replyref{$key} = $value;
6414: if ($value > 0) {
6415: foreach my $item (@{$$affiliatesref{$key}}) {
6416: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6417: my $destname = $pathname.'/'.$filename;
6418: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6419: if ($xml_classlist =~ /^error/) {
6420: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6421: } else {
6422: if ( open(FILE,">$destname") ) {
6423: print FILE &unescape($xml_classlist);
6424: close(FILE);
6425: } else {
6426: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6427: }
6428: }
6429: }
6430: }
6431: }
6432: }
6433: return 'ok';
6434: }
6435: return 'error';
6436: }
6437:
6438: sub get_query_reply {
6439: my $queryid=shift;
6440: my $replyfile=LONCAPA::tempdir().$queryid;
6441: my $reply='';
6442: for (1..100) {
6443: sleep 2;
6444: if (-e $replyfile.'.end') {
6445: if (open(my $fh,$replyfile)) {
6446: $reply = join('',<$fh>);
6447: close($fh);
6448: } else { return 'error: reply_file_error'; }
6449: return &unescape($reply);
6450: }
6451: }
6452: return 'timeout:'.$queryid;
6453: }
6454:
6455: sub courselog_query {
6456: #
6457: # possible filters:
6458: # url: url or symb
6459: # username
6460: # domain
6461: # action: view, submit, grade
6462: # start: timestamp
6463: # end: timestamp
6464: #
6465: my (%filters)=@_;
6466: unless ($env{'request.course.id'}) { return 'no_course'; }
6467: if ($filters{'url'}) {
6468: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6469: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6470: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6471: }
6472: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6473: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6474: return &log_query($cname,$cdom,'courselog',%filters);
6475: }
6476:
6477: sub userlog_query {
6478: #
6479: # possible filters:
6480: # action: log check role
6481: # start: timestamp
6482: # end: timestamp
6483: #
6484: my ($uname,$udom,%filters)=@_;
6485: return &log_query($uname,$udom,'userlog',%filters);
6486: }
6487:
6488: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6489:
6490: sub auto_run {
6491: my ($cnum,$cdom) = @_;
6492: my $response = 0;
6493: my $settings;
6494: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6495: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6496: $settings = $domconfig{'autoenroll'};
6497: if ($settings->{'run'} eq '1') {
6498: $response = 1;
6499: }
6500: } else {
6501: my $homeserver;
6502: if (&is_course($cdom,$cnum)) {
6503: $homeserver = &homeserver($cnum,$cdom);
6504: } else {
6505: $homeserver = &domain($cdom,'primary');
6506: }
6507: if ($homeserver ne 'no_host') {
6508: $response = &reply('autorun:'.$cdom,$homeserver);
6509: }
6510: }
6511: return $response;
6512: }
6513:
6514: sub auto_get_sections {
6515: my ($cnum,$cdom,$inst_coursecode) = @_;
6516: my $homeserver;
6517: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6518: $homeserver = &homeserver($cnum,$cdom);
6519: }
6520: if (!defined($homeserver)) {
6521: if ($cdom =~ /^$match_domain$/) {
6522: $homeserver = &domain($cdom,'primary');
6523: }
6524: }
6525: my @secs;
6526: if (defined($homeserver)) {
6527: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6528: unless ($response eq 'refused') {
6529: @secs = split(/:/,$response);
6530: }
6531: }
6532: return @secs;
6533: }
6534:
6535: sub auto_new_course {
6536: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6537: my $homeserver = &homeserver($cnum,$cdom);
6538: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6539: return $response;
6540: }
6541:
6542: sub auto_validate_courseID {
6543: my ($cnum,$cdom,$inst_course_id) = @_;
6544: my $homeserver = &homeserver($cnum,$cdom);
6545: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6546: return $response;
6547: }
6548:
6549: sub auto_validate_instcode {
6550: my ($cnum,$cdom,$instcode,$owner) = @_;
6551: my ($homeserver,$response);
6552: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6553: $homeserver = &homeserver($cnum,$cdom);
6554: }
6555: if (!defined($homeserver)) {
6556: if ($cdom =~ /^$match_domain$/) {
6557: $homeserver = &domain($cdom,'primary');
6558: }
6559: }
6560: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6561: &escape($instcode).':'.&escape($owner),$homeserver));
6562: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6563: return ($outcome,$description);
6564: }
6565:
6566: sub auto_create_password {
6567: my ($cnum,$cdom,$authparam,$udom) = @_;
6568: my ($homeserver,$response);
6569: my $create_passwd = 0;
6570: my $authchk = '';
6571: if ($udom =~ /^$match_domain$/) {
6572: $homeserver = &domain($udom,'primary');
6573: }
6574: if ($homeserver eq '') {
6575: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6576: $homeserver = &homeserver($cnum,$cdom);
6577: }
6578: }
6579: if ($homeserver eq '') {
6580: $authchk = 'nodomain';
6581: } else {
6582: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6583: if ($response eq 'refused') {
6584: $authchk = 'refused';
6585: } else {
6586: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6587: }
6588: }
6589: return ($authparam,$create_passwd,$authchk);
6590: }
6591:
6592: sub auto_photo_permission {
6593: my ($cnum,$cdom,$students) = @_;
6594: my $homeserver = &homeserver($cnum,$cdom);
6595: my ($outcome,$perm_reqd,$conditions) =
6596: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6597: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6598: return (undef,undef);
6599: }
6600: return ($outcome,$perm_reqd,$conditions);
6601: }
6602:
6603: sub auto_checkphotos {
6604: my ($uname,$udom,$pid) = @_;
6605: my $homeserver = &homeserver($uname,$udom);
6606: my ($result,$resulttype);
6607: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6608: &escape($uname).':'.&escape($pid),
6609: $homeserver));
6610: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6611: return (undef,undef);
6612: }
6613: if ($outcome) {
6614: ($result,$resulttype) = split(/:/,$outcome);
6615: }
6616: return ($result,$resulttype);
6617: }
6618:
6619: sub auto_photochoice {
6620: my ($cnum,$cdom) = @_;
6621: my $homeserver = &homeserver($cnum,$cdom);
6622: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6623: &escape($cdom),
6624: $homeserver)));
6625: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6626: return (undef,undef);
6627: }
6628: return ($update,$comment);
6629: }
6630:
6631: sub auto_photoupdate {
6632: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6633: my $homeserver = &homeserver($cnum,$dom);
6634: my $host=&hostname($homeserver);
6635: my $cmd = '';
6636: my $maxtries = 1;
6637: foreach my $affiliate (keys(%{$affiliatesref})) {
6638: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6639: }
6640: $cmd =~ s/%%$//;
6641: $cmd = &escape($cmd);
6642: my $query = 'institutionalphotos';
6643: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6644: unless ($queryid=~/^\Q$host\E\_/) {
6645: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6646: return 'error: '.$queryid;
6647: }
6648: my $reply = &get_query_reply($queryid);
6649: my $tries = 1;
6650: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6651: $reply = &get_query_reply($queryid);
6652: $tries ++;
6653: }
6654: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6655: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6656: } else {
6657: my @responses = split(/:/,$reply);
6658: my $outcome = shift(@responses);
6659: foreach my $item (@responses) {
6660: my ($key,$value) = split(/=/,$item);
6661: $$photo{$key} = $value;
6662: }
6663: return $outcome;
6664: }
6665: return 'error';
6666: }
6667:
6668: sub auto_instcode_format {
6669: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6670: $cat_order) = @_;
6671: my $courses = '';
6672: my @homeservers;
6673: if ($caller eq 'global') {
6674: my %servers = &get_servers($codedom,'library');
6675: foreach my $tryserver (keys(%servers)) {
6676: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6677: push(@homeservers,$tryserver);
6678: }
6679: }
6680: } elsif ($caller eq 'requests') {
6681: if ($codedom =~ /^$match_domain$/) {
6682: my $chome = &domain($codedom,'primary');
6683: unless ($chome eq 'no_host') {
6684: push(@homeservers,$chome);
6685: }
6686: }
6687: } else {
6688: push(@homeservers,&homeserver($caller,$codedom));
6689: }
6690: foreach my $code (keys(%{$instcodes})) {
6691: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6692: }
6693: chop($courses);
6694: my $ok_response = 0;
6695: my $response;
6696: while (@homeservers > 0 && $ok_response == 0) {
6697: my $server = shift(@homeservers);
6698: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6699: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6700: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6701: split(/:/,$response);
6702: %{$codes} = (%{$codes},&str2hash($codes_str));
6703: push(@{$codetitles},&str2array($codetitles_str));
6704: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6705: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6706: $ok_response = 1;
6707: }
6708: }
6709: if ($ok_response) {
6710: return 'ok';
6711: } else {
6712: return $response;
6713: }
6714: }
6715:
6716: sub auto_instcode_defaults {
6717: my ($domain,$returnhash,$code_order) = @_;
6718: my @homeservers;
6719:
6720: my %servers = &get_servers($domain,'library');
6721: foreach my $tryserver (keys(%servers)) {
6722: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6723: push(@homeservers,$tryserver);
6724: }
6725: }
6726:
6727: my $response;
6728: foreach my $server (@homeservers) {
6729: $response=&reply('autoinstcodedefaults:'.$domain,$server);
6730: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6731:
6732: foreach my $pair (split(/\&/,$response)) {
6733: my ($name,$value)=split(/\=/,$pair);
6734: if ($name eq 'code_order') {
6735: @{$code_order} = split(/\&/,&unescape($value));
6736: } else {
6737: $returnhash->{&unescape($name)}=&unescape($value);
6738: }
6739: }
6740: return 'ok';
6741: }
6742:
6743: return $response;
6744: }
6745:
6746: sub auto_possible_instcodes {
6747: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6748: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6749: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6750: return;
6751: }
6752: my (@homeservers,$uhome);
6753: if (defined(&domain($domain,'primary'))) {
6754: $uhome=&domain($domain,'primary');
6755: push(@homeservers,&domain($domain,'primary'));
6756: } else {
6757: my %servers = &get_servers($domain,'library');
6758: foreach my $tryserver (keys(%servers)) {
6759: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6760: push(@homeservers,$tryserver);
6761: }
6762: }
6763: }
6764: my $response;
6765: foreach my $server (@homeservers) {
6766: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6767: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6768: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6769: split(':',$response);
6770: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6771: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
6772: foreach my $item (split('&',$cat_title)) {
6773: my ($name,$value)=split('=',$item);
6774: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
6775: }
6776: foreach my $item (split('&',$cat_order)) {
6777: my ($name,$value)=split('=',$item);
6778: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
6779: }
6780: return 'ok';
6781: }
6782: return $response;
6783: }
6784:
6785: sub auto_courserequest_checks {
6786: my ($dom) = @_;
6787: my ($homeserver,%validations);
6788: if ($dom =~ /^$match_domain$/) {
6789: $homeserver = &domain($dom,'primary');
6790: }
6791: unless ($homeserver eq 'no_host') {
6792: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6793: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6794: my @items = split(/&/,$response);
6795: foreach my $item (@items) {
6796: my ($key,$value) = split('=',$item);
6797: $validations{&unescape($key)} = &thaw_unescape($value);
6798: }
6799: }
6800: }
6801: return %validations;
6802: }
6803:
6804: sub auto_courserequest_validation {
6805: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6806: my ($homeserver,$response);
6807: if ($dom =~ /^$match_domain$/) {
6808: $homeserver = &domain($dom,'primary');
6809: }
6810: unless ($homeserver eq 'no_host') {
6811:
6812: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
6813: ':'.&escape($crstype).':'.&escape($inststatuslist).
6814: ':'.&escape($instcode).':'.&escape($instseclist),
6815: $homeserver));
6816: }
6817: return $response;
6818: }
6819:
6820: sub auto_validate_class_sec {
6821: my ($cdom,$cnum,$owners,$inst_class) = @_;
6822: my $homeserver = &homeserver($cnum,$cdom);
6823: my $ownerlist;
6824: if (ref($owners) eq 'ARRAY') {
6825: $ownerlist = join(',',@{$owners});
6826: } else {
6827: $ownerlist = $owners;
6828: }
6829: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
6830: &escape($ownerlist).':'.$cdom,$homeserver);
6831: return $response;
6832: }
6833:
6834: # ------------------------------------------------------- Course Group routines
6835:
6836: sub get_coursegroups {
6837: my ($cdom,$cnum,$group,$namespace) = @_;
6838: return(&dump($namespace,$cdom,$cnum,$group));
6839: }
6840:
6841: sub modify_coursegroup {
6842: my ($cdom,$cnum,$groupsettings) = @_;
6843: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6844: }
6845:
6846: sub toggle_coursegroup_status {
6847: my ($cdom,$cnum,$group,$action) = @_;
6848: my ($from_namespace,$to_namespace);
6849: if ($action eq 'delete') {
6850: $from_namespace = 'coursegroups';
6851: $to_namespace = 'deleted_groups';
6852: } else {
6853: $from_namespace = 'deleted_groups';
6854: $to_namespace = 'coursegroups';
6855: }
6856: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
6857: if (my $tmp = &error(%curr_group)) {
6858: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6859: return ('read error',$tmp);
6860: } else {
6861: my %savedsettings = %curr_group;
6862: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
6863: my $deloutcome;
6864: if ($result eq 'ok') {
6865: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
6866: } else {
6867: return ('write error',$result);
6868: }
6869: if ($deloutcome eq 'ok') {
6870: return 'ok';
6871: } else {
6872: return ('delete error',$deloutcome);
6873: }
6874: }
6875: }
6876:
6877: sub modify_group_roles {
6878: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
6879: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6880: my $role = 'gr/'.&escape($userprivs);
6881: my ($uname,$udom) = split(/:/,$user);
6882: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
6883: if ($result eq 'ok') {
6884: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6885: }
6886: return $result;
6887: }
6888:
6889: sub modify_coursegroup_membership {
6890: my ($cdom,$cnum,$membership) = @_;
6891: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6892: return $result;
6893: }
6894:
6895: sub get_active_groups {
6896: my ($udom,$uname,$cdom,$cnum) = @_;
6897: my $now = time;
6898: my %groups = ();
6899: foreach my $key (keys(%env)) {
6900: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
6901: my ($start,$end) = split(/\./,$env{$key});
6902: if (($end!=0) && ($end<$now)) { next; }
6903: if (($start!=0) && ($start>$now)) { next; }
6904: if ($1 eq $cdom && $2 eq $cnum) {
6905: $groups{$3} = $env{$key} ;
6906: }
6907: }
6908: }
6909: return %groups;
6910: }
6911:
6912: sub get_group_membership {
6913: my ($cdom,$cnum,$group) = @_;
6914: return(&dump('groupmembership',$cdom,$cnum,$group));
6915: }
6916:
6917: sub get_users_groups {
6918: my ($udom,$uname,$courseid) = @_;
6919: my @usersgroups;
6920: my $cachetime=1800;
6921:
6922: my $hashid="$udom:$uname:$courseid";
6923: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6924: if (defined($cached)) {
6925: @usersgroups = split(/:/,$grouplist);
6926: } else {
6927: $grouplist = '';
6928: my $courseurl = &courseid_to_courseurl($courseid);
6929: my $extra = &freeze_escape({'skipcheck' => 1});
6930: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
6931: my $access_end = $env{'course.'.$courseid.
6932: '.default_enrollment_end_date'};
6933: my $now = time;
6934: foreach my $key (keys(%roleshash)) {
6935: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6936: my $group = $1;
6937: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6938: my $start = $2;
6939: my $end = $1;
6940: if ($start == -1) { next; } # deleted from group
6941: if (($start!=0) && ($start>$now)) { next; }
6942: if (($end!=0) && ($end<$now)) {
6943: if ($access_end && $access_end < $now) {
6944: if ($access_end - $end < 86400) {
6945: push(@usersgroups,$group);
6946: }
6947: }
6948: next;
6949: }
6950: push(@usersgroups,$group);
6951: }
6952: }
6953: }
6954: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6955: $grouplist = join(':',@usersgroups);
6956: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6957: }
6958: return @usersgroups;
6959: }
6960:
6961: sub devalidate_getgroups_cache {
6962: my ($udom,$uname,$cdom,$cnum)=@_;
6963: my $courseid = $cdom.'_'.$cnum;
6964:
6965: my $hashid="$udom:$uname:$courseid";
6966: &devalidate_cache_new('getgroups',$hashid);
6967: }
6968:
6969: # ------------------------------------------------------------------ Plain Text
6970:
6971: sub plaintext {
6972: my ($short,$type,$cid,$forcedefault) = @_;
6973: if ($short =~ m{^cr/}) {
6974: return (split('/',$short))[-1];
6975: }
6976: if (!defined($cid)) {
6977: $cid = $env{'request.course.id'};
6978: }
6979: my %rolenames = (
6980: Course => 'std',
6981: Community => 'alt1',
6982: );
6983: if ($cid ne '') {
6984: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6985: unless ($forcedefault) {
6986: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6987: &Apache::lonlocal::mt_escape(\$roletext);
6988: return &Apache::lonlocal::mt($roletext);
6989: }
6990: }
6991: }
6992: if ((defined($type)) && (defined($rolenames{$type})) &&
6993: (defined($rolenames{$type})) &&
6994: (defined($prp{$short}{$rolenames{$type}}))) {
6995: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6996: } elsif ($cid ne '') {
6997: my $crstype = $env{'course.'.$cid.'.type'};
6998: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6999: (defined($prp{$short}{$rolenames{$crstype}}))) {
7000: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7001: }
7002: }
7003: return &Apache::lonlocal::mt($prp{$short}{'std'});
7004: }
7005:
7006: # ----------------------------------------------------------------- Assign Role
7007:
7008: sub assignrole {
7009: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7010: $context)=@_;
7011: my $mrole;
7012: if ($role =~ /^cr\//) {
7013: my $cwosec=$url;
7014: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7015: unless (&allowed('ccr',$cwosec)) {
7016: my $refused = 1;
7017: if ($context eq 'requestcourses') {
7018: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7019: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7020: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7021: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7022: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7023: if ($crsenv{'internal.courseowner'} eq
7024: $env{'user.name'}.':'.$env{'user.domain'}) {
7025: $refused = '';
7026: }
7027: }
7028: }
7029: }
7030: }
7031: if ($refused) {
7032: &logthis('Refused custom assignrole: '.
7033: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7034: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7035: return 'refused';
7036: }
7037: }
7038: $mrole='cr';
7039: } elsif ($role =~ /^gr\//) {
7040: my $cwogrp=$url;
7041: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7042: unless (&allowed('mdg',$cwogrp)) {
7043: &logthis('Refused group assignrole: '.
7044: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7045: $env{'user.name'}.' at '.$env{'user.domain'});
7046: return 'refused';
7047: }
7048: $mrole='gr';
7049: } else {
7050: my $cwosec=$url;
7051: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7052: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7053: my $refused;
7054: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7055: if (!(&allowed('c'.$role,$url))) {
7056: $refused = 1;
7057: }
7058: } else {
7059: $refused = 1;
7060: }
7061: if ($refused) {
7062: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7063: if (!$selfenroll && $context eq 'course') {
7064: my %crsenv;
7065: if ($role eq 'cc' || $role eq 'co') {
7066: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7067: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7068: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7069: if ($crsenv{'internal.courseowner'} eq
7070: $env{'user.name'}.':'.$env{'user.domain'}) {
7071: $refused = '';
7072: }
7073: }
7074: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7075: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7076: if ($crsenv{'internal.courseowner'} eq
7077: $env{'user.name'}.':'.$env{'user.domain'}) {
7078: $refused = '';
7079: }
7080: }
7081: }
7082: }
7083: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7084: $refused = '';
7085: } elsif ($context eq 'requestcourses') {
7086: my @possroles = ('st','ta','ep','in','cc','co');
7087: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7088: my $wrongcc;
7089: if ($cnum =~ /^$match_community$/) {
7090: $wrongcc = 1 if ($role eq 'cc');
7091: } else {
7092: $wrongcc = 1 if ($role eq 'co');
7093: }
7094: unless ($wrongcc) {
7095: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7096: if ($crsenv{'internal.courseowner'} eq
7097: $env{'user.name'}.':'.$env{'user.domain'}) {
7098: $refused = '';
7099: }
7100: }
7101: }
7102: }
7103: if ($refused) {
7104: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7105: ' '.$role.' '.$end.' '.$start.' by '.
7106: $env{'user.name'}.' at '.$env{'user.domain'});
7107: return 'refused';
7108: }
7109: }
7110: } elsif ($role eq 'au') {
7111: if ($url ne '/'.$udom.'/') {
7112: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7113: ' to assign author role for '.$uname.':'.$udom.
7114: ' in domain: '.$url.' refused (wrong domain).');
7115: return 'refused';
7116: }
7117: }
7118: $mrole=$role;
7119: }
7120: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7121: "$udom:$uname:$url".'_'."$mrole=$role";
7122: if ($end) { $command.='_'.$end; }
7123: if ($start) {
7124: if ($end) {
7125: $command.='_'.$start;
7126: } else {
7127: $command.='_0_'.$start;
7128: }
7129: }
7130: my $origstart = $start;
7131: my $origend = $end;
7132: my $delflag;
7133: # actually delete
7134: if ($deleteflag) {
7135: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7136: # modify command to delete the role
7137: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7138: "$udom:$uname:$url".'_'."$mrole";
7139: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7140: # set start and finish to negative values for userrolelog
7141: $start=-1;
7142: $end=-1;
7143: $delflag = 1;
7144: }
7145: }
7146: # send command
7147: my $answer=&reply($command,&homeserver($uname,$udom));
7148: # log new user role if status is ok
7149: if ($answer eq 'ok') {
7150: &userrolelog($role,$uname,$udom,$url,$start,$end);
7151: # for course roles, perform group memberships changes triggered by role change.
7152: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7153: unless ($role =~ /^gr/) {
7154: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7155: $origstart,$selfenroll,$context);
7156: }
7157: if ($role eq 'cc') {
7158: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7159: }
7160: }
7161: return $answer;
7162: }
7163:
7164: sub autoupdate_coowners {
7165: my ($url,$end,$start,$uname,$udom) = @_;
7166: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7167: if (($cdom ne '') && ($cnum ne '')) {
7168: my $now = time;
7169: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7170: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7171: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7172: my $instcode = $coursehash{'internal.coursecode'};
7173: if ($instcode ne '') {
7174: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7175: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7176: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7177: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7178: if ($result eq 'valid') {
7179: if ($coursehash{'internal.co-owners'}) {
7180: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7181: push(@newcoowners,$coowner);
7182: }
7183: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7184: push(@newcoowners,$uname.':'.$udom);
7185: }
7186: @newcoowners = sort(@newcoowners);
7187: } else {
7188: push(@newcoowners,$uname.':'.$udom);
7189: }
7190: } else {
7191: if ($coursehash{'internal.co-owners'}) {
7192: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7193: unless ($coowner eq $uname.':'.$udom) {
7194: push(@newcoowners,$coowner);
7195: }
7196: }
7197: unless (@newcoowners > 0) {
7198: $delcoowners = 1;
7199: $coowners = '';
7200: }
7201: }
7202: }
7203: if (@newcoowners || $delcoowners) {
7204: &store_coowners($cdom,$cnum,$coursehash{'home'},
7205: $delcoowners,@newcoowners);
7206: }
7207: }
7208: }
7209: }
7210: }
7211: }
7212: }
7213:
7214: sub store_coowners {
7215: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7216: my $cid = $cdom.'_'.$cnum;
7217: my ($coowners,$delresult,$putresult);
7218: if (@newcoowners) {
7219: $coowners = join(',',@newcoowners);
7220: my %coownershash = (
7221: 'internal.co-owners' => $coowners,
7222: );
7223: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7224: if ($putresult eq 'ok') {
7225: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7226: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7227: }
7228: }
7229: }
7230: if ($delcoowners) {
7231: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7232: if ($delresult eq 'ok') {
7233: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7234: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7235: }
7236: }
7237: }
7238: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7239: my %crsinfo =
7240: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7241: if (ref($crsinfo{$cid}) eq 'HASH') {
7242: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7243: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7244: }
7245: }
7246: }
7247:
7248: # -------------------------------------------------- Modify user authentication
7249: # Overrides without validation
7250:
7251: sub modifyuserauth {
7252: my ($udom,$uname,$umode,$upass)=@_;
7253: my $uhome=&homeserver($uname,$udom);
7254: unless (&allowed('mau',$udom)) { return 'refused'; }
7255: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7256: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7257: ' in domain '.$env{'request.role.domain'});
7258: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7259: &escape($upass),$uhome);
7260: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7261: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7262: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7263: &log($udom,,$uname,$uhome,
7264: 'Authentication changed by '.$env{'user.domain'}.', '.
7265: $env{'user.name'}.', '.$umode.
7266: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7267: unless ($reply eq 'ok') {
7268: &logthis('Authentication mode error: '.$reply);
7269: return 'error: '.$reply;
7270: }
7271: return 'ok';
7272: }
7273:
7274: # --------------------------------------------------------------- Modify a user
7275:
7276: sub modifyuser {
7277: my ($udom, $uname, $uid,
7278: $umode, $upass, $first,
7279: $middle, $last, $gene,
7280: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7281: $udom= &LONCAPA::clean_domain($udom);
7282: $uname=&LONCAPA::clean_username($uname);
7283: my $showcandelete = 'none';
7284: if (ref($candelete) eq 'ARRAY') {
7285: if (@{$candelete} > 0) {
7286: $showcandelete = join(', ',@{$candelete});
7287: }
7288: }
7289: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7290: $umode.', '.$first.', '.$middle.', '.
7291: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7292: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7293: ' desiredhome not specified').
7294: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7295: ' in domain '.$env{'request.role.domain'});
7296: my $uhome=&homeserver($uname,$udom,'true');
7297: my $newuser;
7298: if ($uhome eq 'no_host') {
7299: $newuser = 1;
7300: }
7301: # ----------------------------------------------------------------- Create User
7302: if (($uhome eq 'no_host') &&
7303: (($umode && $upass) || ($umode eq 'localauth'))) {
7304: my $unhome='';
7305: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7306: $unhome = $desiredhome;
7307: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7308: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7309: } else { # load balancing routine for determining $unhome
7310: my $loadm=10000000;
7311: my %servers = &get_servers($udom,'library');
7312: foreach my $tryserver (keys(%servers)) {
7313: my $answer=reply('load',$tryserver);
7314: if (($answer=~/\d+/) && ($answer<$loadm)) {
7315: $loadm=$answer;
7316: $unhome=$tryserver;
7317: }
7318: }
7319: }
7320: if (($unhome eq '') || ($unhome eq 'no_host')) {
7321: return 'error: unable to find a home server for '.$uname.
7322: ' in domain '.$udom;
7323: }
7324: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7325: &escape($upass),$unhome);
7326: unless ($reply eq 'ok') {
7327: return 'error: '.$reply;
7328: }
7329: $uhome=&homeserver($uname,$udom,'true');
7330: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7331: return 'error: unable verify users home machine.';
7332: }
7333: } # End of creation of new user
7334: # ---------------------------------------------------------------------- Add ID
7335: if ($uid) {
7336: $uid=~tr/A-Z/a-z/;
7337: my %uidhash=&idrget($udom,$uname);
7338: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7339: && (!$forceid)) {
7340: unless ($uid eq $uidhash{$uname}) {
7341: return 'error: user id "'.$uid.'" does not match '.
7342: 'current user id "'.$uidhash{$uname}.'".';
7343: }
7344: } else {
7345: &idput($udom,($uname => $uid));
7346: }
7347: }
7348: # -------------------------------------------------------------- Add names, etc
7349: my @tmp=&get('environment',
7350: ['firstname','middlename','lastname','generation','id',
7351: 'permanentemail','inststatus'],
7352: $udom,$uname);
7353: my (%names,%oldnames);
7354: if ($tmp[0] =~ m/^error:.*/) {
7355: %names=();
7356: } else {
7357: %names = @tmp;
7358: %oldnames = %names;
7359: }
7360: #
7361: # If name, email and/or uid are blank (e.g., because an uploaded file
7362: # of users did not contain them), do not overwrite existing values
7363: # unless field is in $candelete array ref.
7364: #
7365:
7366: my @fields = ('firstname','middlename','lastname','generation',
7367: 'permanentemail','id');
7368: my %newvalues;
7369: if (ref($candelete) eq 'ARRAY') {
7370: foreach my $field (@fields) {
7371: if (grep(/^\Q$field\E$/,@{$candelete})) {
7372: if ($field eq 'firstname') {
7373: $names{$field} = $first;
7374: } elsif ($field eq 'middlename') {
7375: $names{$field} = $middle;
7376: } elsif ($field eq 'lastname') {
7377: $names{$field} = $last;
7378: } elsif ($field eq 'generation') {
7379: $names{$field} = $gene;
7380: } elsif ($field eq 'permanentemail') {
7381: $names{$field} = $email;
7382: } elsif ($field eq 'id') {
7383: $names{$field} = $uid;
7384: }
7385: }
7386: }
7387: }
7388: if ($first) { $names{'firstname'} = $first; }
7389: if (defined($middle)) { $names{'middlename'} = $middle; }
7390: if ($last) { $names{'lastname'} = $last; }
7391: if (defined($gene)) { $names{'generation'} = $gene; }
7392: if ($email) {
7393: $email=~s/[^\w\@\.\-\,]//gs;
7394: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7395: }
7396: if ($uid) { $names{'id'} = $uid; }
7397: if (defined($inststatus)) {
7398: $names{'inststatus'} = '';
7399: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7400: if (ref($usertypes) eq 'HASH') {
7401: my @okstatuses;
7402: foreach my $item (split(/:/,$inststatus)) {
7403: if (defined($usertypes->{$item})) {
7404: push(@okstatuses,$item);
7405: }
7406: }
7407: if (@okstatuses) {
7408: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7409: }
7410: }
7411: }
7412: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7413: $umode.', '.$first.', '.$middle.', '.
7414: $last.', '.$gene.', '.$email.', '.$inststatus;
7415: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7416: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7417: } else {
7418: $logmsg .= ' during self creation';
7419: }
7420: my $changed;
7421: if ($newuser) {
7422: $changed = 1;
7423: } else {
7424: foreach my $field (@fields) {
7425: if ($names{$field} ne $oldnames{$field}) {
7426: $changed = 1;
7427: last;
7428: }
7429: }
7430: }
7431: unless ($changed) {
7432: $logmsg = 'No changes in user information needed for: '.$logmsg;
7433: &logthis($logmsg);
7434: return 'ok';
7435: }
7436: my $reply = &put('environment', \%names, $udom,$uname);
7437: if ($reply ne 'ok') {
7438: return 'error: '.$reply;
7439: }
7440: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7441: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7442: }
7443: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7444: &devalidate_cache_new('namescache',$uname.':'.$udom);
7445: $logmsg = 'Success modifying user '.$logmsg;
7446: &logthis($logmsg);
7447: return 'ok';
7448: }
7449:
7450: # -------------------------------------------------------------- Modify student
7451:
7452: sub modifystudent {
7453: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7454: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7455: $selfenroll,$context,$inststatus)=@_;
7456: if (!$cid) {
7457: unless ($cid=$env{'request.course.id'}) {
7458: return 'not_in_class';
7459: }
7460: }
7461: # --------------------------------------------------------------- Make the user
7462: my $reply=&modifyuser
7463: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7464: $desiredhome,$email,$inststatus);
7465: unless ($reply eq 'ok') { return $reply; }
7466: # This will cause &modify_student_enrollment to get the uid from the
7467: # students environment
7468: $uid = undef if (!$forceid);
7469: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7470: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7471: return $reply;
7472: }
7473:
7474: sub modify_student_enrollment {
7475: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7476: my ($cdom,$cnum,$chome);
7477: if (!$cid) {
7478: unless ($cid=$env{'request.course.id'}) {
7479: return 'not_in_class';
7480: }
7481: $cdom=$env{'course.'.$cid.'.domain'};
7482: $cnum=$env{'course.'.$cid.'.num'};
7483: } else {
7484: ($cdom,$cnum)=split(/_/,$cid);
7485: }
7486: $chome=$env{'course.'.$cid.'.home'};
7487: if (!$chome) {
7488: $chome=&homeserver($cnum,$cdom);
7489: }
7490: if (!$chome) { return 'unknown_course'; }
7491: # Make sure the user exists
7492: my $uhome=&homeserver($uname,$udom);
7493: if (($uhome eq '') || ($uhome eq 'no_host')) {
7494: return 'error: no such user';
7495: }
7496: # Get student data if we were not given enough information
7497: if (!defined($first) || $first eq '' ||
7498: !defined($last) || $last eq '' ||
7499: !defined($uid) || $uid eq '' ||
7500: !defined($middle) || $middle eq '' ||
7501: !defined($gene) || $gene eq '') {
7502: # They did not supply us with enough data to enroll the student, so
7503: # we need to pick up more information.
7504: my %tmp = &get('environment',
7505: ['firstname','middlename','lastname', 'generation','id']
7506: ,$udom,$uname);
7507:
7508: #foreach my $key (keys(%tmp)) {
7509: # &logthis("key $key = ".$tmp{$key});
7510: #}
7511: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7512: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7513: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7514: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7515: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7516: }
7517: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7518: my $user = "$uname:$udom";
7519: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
7520: my $reply=cput('classlist',
7521: {$user =>
7522: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7523: $cdom,$cnum);
7524: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7525: &devalidate_getsection_cache($udom,$uname,$cid);
7526: } else {
7527: return 'error: '.$reply;
7528: }
7529: # Add student role to user
7530: my $uurl='/'.$cid;
7531: $uurl=~s/\_/\//g;
7532: if ($usec) {
7533: $uurl.='/'.$usec;
7534: }
7535: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7536: $selfenroll,$context);
7537: if ($result ne 'ok') {
7538: if ($old_entry{$user} ne '') {
7539: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7540: } else {
7541: $reply = &del('classlist',[$user],$cdom,$cnum);
7542: }
7543: }
7544: return $result;
7545: }
7546:
7547: sub format_name {
7548: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7549: my $name;
7550: if ($first ne 'lastname') {
7551: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7552: } else {
7553: if ($lastname=~/\S/) {
7554: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7555: $name=~s/\s+,/,/;
7556: } else {
7557: $name.= $firstname.' '.$middlename.' '.$generation;
7558: }
7559: }
7560: $name=~s/^\s+//;
7561: $name=~s/\s+$//;
7562: $name=~s/\s+/ /g;
7563: return $name;
7564: }
7565:
7566: # ------------------------------------------------- Write to course preferences
7567:
7568: sub writecoursepref {
7569: my ($courseid,%prefs)=@_;
7570: $courseid=~s/^\///;
7571: $courseid=~s/\_/\//g;
7572: my ($cdomain,$cnum)=split(/\//,$courseid);
7573: my $chome=homeserver($cnum,$cdomain);
7574: if (($chome eq '') || ($chome eq 'no_host')) {
7575: return 'error: no such course';
7576: }
7577: my $cstring='';
7578: foreach my $pref (keys(%prefs)) {
7579: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7580: }
7581: $cstring=~s/\&$//;
7582: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7583: }
7584:
7585: # ---------------------------------------------------------- Make/modify course
7586:
7587: sub createcourse {
7588: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7589: $course_owner,$crstype,$cnum,$context,$category)=@_;
7590: $url=&declutter($url);
7591: my $cid='';
7592: if ($context eq 'requestcourses') {
7593: my $can_create = 0;
7594: my ($ownername,$ownerdom) = split(':',$course_owner);
7595: if ($udom eq $ownerdom) {
7596: if (&usertools_access($ownername,$ownerdom,$category,undef,
7597: $context)) {
7598: $can_create = 1;
7599: }
7600: } else {
7601: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7602: $category);
7603: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7604: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7605: if (@curr > 0) {
7606: my @options = qw(approval validate autolimit);
7607: my $optregex = join('|',@options);
7608: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7609: $can_create = 1;
7610: }
7611: }
7612: }
7613: }
7614: if ($can_create) {
7615: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7616: unless (&allowed('ccc',$udom)) {
7617: return 'refused';
7618: }
7619: }
7620: } else {
7621: return 'refused';
7622: }
7623: } elsif (!&allowed('ccc',$udom)) {
7624: return 'refused';
7625: }
7626: # --------------------------------------------------------------- Get Unique ID
7627: my $uname;
7628: if ($cnum =~ /^$match_courseid$/) {
7629: my $chome=&homeserver($cnum,$udom,'true');
7630: if (($chome eq '') || ($chome eq 'no_host')) {
7631: $uname = $cnum;
7632: } else {
7633: $uname = &generate_coursenum($udom,$crstype);
7634: }
7635: } else {
7636: $uname = &generate_coursenum($udom,$crstype);
7637: }
7638: return $uname if ($uname =~ /^error/);
7639: # -------------------------------------------------- Check supplied server name
7640: if (!defined($course_server)) {
7641: if (defined(&domain($udom,'primary'))) {
7642: $course_server = &domain($udom,'primary');
7643: } else {
7644: $course_server = $env{'user.home'};
7645: }
7646: }
7647: my %host_servers =
7648: &Apache::lonnet::get_servers($udom,'library');
7649: unless ($host_servers{$course_server}) {
7650: return 'error: invalid home server for course: '.$course_server;
7651: }
7652: # ------------------------------------------------------------- Make the course
7653: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7654: $course_server);
7655: unless ($reply eq 'ok') { return 'error: '.$reply; }
7656: my $uhome=&homeserver($uname,$udom,'true');
7657: if (($uhome eq '') || ($uhome eq 'no_host')) {
7658: return 'error: no such course';
7659: }
7660: # ----------------------------------------------------------------- Course made
7661: # log existence
7662: my $now = time;
7663: my $newcourse = {
7664: $udom.'_'.$uname => {
7665: description => $description,
7666: inst_code => $inst_code,
7667: owner => $course_owner,
7668: type => $crstype,
7669: creator => $env{'user.name'}.':'.
7670: $env{'user.domain'},
7671: created => $now,
7672: context => $context,
7673: },
7674: };
7675: &courseidput($udom,$newcourse,$uhome,'notime');
7676: # set toplevel url
7677: my $topurl=$url;
7678: unless ($nonstandard) {
7679: # ------------------------------------------ For standard courses, make top url
7680: my $mapurl=&clutter($url);
7681: if ($mapurl eq '/res/') { $mapurl=''; }
7682: $env{'form.initmap'}=(<<ENDINITMAP);
7683: <map>
7684: <resource id="1" type="start"></resource>
7685: <resource id="2" src="$mapurl"></resource>
7686: <resource id="3" type="finish"></resource>
7687: <link index="1" from="1" to="2"></link>
7688: <link index="2" from="2" to="3"></link>
7689: </map>
7690: ENDINITMAP
7691: $topurl=&declutter(
7692: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7693: );
7694: }
7695: # ----------------------------------------------------------- Write preferences
7696: &writecoursepref($udom.'_'.$uname,
7697: ('description' => $description,
7698: 'url' => $topurl,
7699: 'internal.creator' => $env{'user.name'}.':'.
7700: $env{'user.domain'},
7701: 'internal.created' => $now,
7702: 'internal.creationcontext' => $context)
7703: );
7704: return '/'.$udom.'/'.$uname;
7705: }
7706:
7707: # ------------------------------------------------------------------- Create ID
7708: sub generate_coursenum {
7709: my ($udom,$crstype) = @_;
7710: my $domdesc = &domain($udom);
7711: return 'error: invalid domain' if ($domdesc eq '');
7712: my $first;
7713: if ($crstype eq 'Community') {
7714: $first = '0';
7715: } else {
7716: $first = int(1+rand(9));
7717: }
7718: my $uname=$first.
7719: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7720: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7721: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7722: # ----------------------------------------------- Make sure that does not exist
7723: my $uhome=&homeserver($uname,$udom,'true');
7724: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7725: if ($crstype eq 'Community') {
7726: $first = '0';
7727: } else {
7728: $first = int(1+rand(9));
7729: }
7730: $uname=$first.
7731: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7732: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7733: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7734: $uhome=&homeserver($uname,$udom,'true');
7735: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7736: return 'error: unable to generate unique course-ID';
7737: }
7738: }
7739: return $uname;
7740: }
7741:
7742: sub is_course {
7743: my ($cdom,$cnum) = @_;
7744: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
7745: undef,'.');
7746: if (exists($courses{$cdom.'_'.$cnum})) {
7747: return 1;
7748: }
7749: return 0;
7750: }
7751:
7752: sub store_userdata {
7753: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
7754: my $result;
7755: if ($datakey ne '') {
7756: if (ref($storehash) eq 'HASH') {
7757: if ($udom eq '' || $uname eq '') {
7758: $udom = $env{'user.domain'};
7759: $uname = $env{'user.name'};
7760: }
7761: my $uhome=&homeserver($uname,$udom);
7762: if (($uhome eq '') || ($uhome eq 'no_host')) {
7763: $result = 'error: no_host';
7764: } else {
7765: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7766: $storehash->{'host'} = $perlvar{'lonHostID'};
7767:
7768: my $namevalue='';
7769: foreach my $key (keys(%{$storehash})) {
7770: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7771: }
7772: $namevalue=~s/\&$//;
7773: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7774: $namevalue,$uhome);
7775: }
7776: } else {
7777: $result = 'error: data to store was not a hash reference';
7778: }
7779: } else {
7780: $result= 'error: invalid requestkey';
7781: }
7782: return $result;
7783: }
7784:
7785: # ---------------------------------------------------------- Assign Custom Role
7786:
7787: sub assigncustomrole {
7788: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
7789: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
7790: $end,$start,$deleteflag,$selfenroll,$context);
7791: }
7792:
7793: # ----------------------------------------------------------------- Revoke Role
7794:
7795: sub revokerole {
7796: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
7797: my $now=time;
7798: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
7799: }
7800:
7801: # ---------------------------------------------------------- Revoke Custom Role
7802:
7803: sub revokecustomrole {
7804: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
7805: my $now=time;
7806: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
7807: $deleteflag,$selfenroll,$context);
7808: }
7809:
7810: # ------------------------------------------------------------ Disk usage
7811: sub diskusage {
7812: my ($udom,$uname,$directorypath,$getpropath)=@_;
7813: $directorypath =~ s/\/$//;
7814: my $listing=&reply('du2:'.&escape($directorypath).':'
7815: .&escape($getpropath).':'.&escape($uname).':'
7816: .&escape($udom),homeserver($uname,$udom));
7817: if ($listing eq 'unknown_cmd') {
7818: if ($getpropath) {
7819: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7820: }
7821: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7822: }
7823: return $listing;
7824: }
7825:
7826: sub is_locked {
7827: my ($file_name, $domain, $user, $which) = @_;
7828: my @check;
7829: my $is_locked;
7830: push (@check,$file_name);
7831: my %locked = &get('file_permissions',\@check,
7832: $env{'user.domain'},$env{'user.name'});
7833: my ($tmp)=keys(%locked);
7834: if ($tmp=~/^error:/) { undef(%locked); }
7835:
7836: if (ref($locked{$file_name}) eq 'ARRAY') {
7837: $is_locked = 'false';
7838: foreach my $entry (@{$locked{$file_name}}) {
7839: if (ref($entry) eq 'ARRAY') {
7840: $is_locked = 'true';
7841: if (ref($which) eq 'ARRAY') {
7842: push(@{$which},$entry);
7843: } else {
7844: last;
7845: }
7846: }
7847: }
7848: } else {
7849: $is_locked = 'false';
7850: }
7851: return $is_locked;
7852: }
7853:
7854: sub declutter_portfile {
7855: my ($file) = @_;
7856: $file =~ s{^(/portfolio/|portfolio/)}{/};
7857: return $file;
7858: }
7859:
7860: # ------------------------------------------------------------- Mark as Read Only
7861:
7862: sub mark_as_readonly {
7863: my ($domain,$user,$files,$what) = @_;
7864: my %current_permissions = &dump('file_permissions',$domain,$user);
7865: my ($tmp)=keys(%current_permissions);
7866: if ($tmp=~/^error:/) { undef(%current_permissions); }
7867: foreach my $file (@{$files}) {
7868: $file = &declutter_portfile($file);
7869: push(@{$current_permissions{$file}},$what);
7870: }
7871: &put('file_permissions',\%current_permissions,$domain,$user);
7872: return;
7873: }
7874:
7875: # ------------------------------------------------------------Save Selected Files
7876:
7877: sub save_selected_files {
7878: my ($user, $path, @files) = @_;
7879: my $filename = $user."savedfiles";
7880: my @other_files = &files_not_in_path($user, $path);
7881: open (OUT, '>'.$tmpdir.$filename);
7882: foreach my $file (@files) {
7883: print (OUT $env{'form.currentpath'}.$file."\n");
7884: }
7885: foreach my $file (@other_files) {
7886: print (OUT $file."\n");
7887: }
7888: close (OUT);
7889: return 'ok';
7890: }
7891:
7892: sub clear_selected_files {
7893: my ($user) = @_;
7894: my $filename = $user."savedfiles";
7895: open (OUT, '>'.LONCAPA::tempdir().$filename);
7896: print (OUT undef);
7897: close (OUT);
7898: return ("ok");
7899: }
7900:
7901: sub files_in_path {
7902: my ($user, $path) = @_;
7903: my $filename = $user."savedfiles";
7904: my %return_files;
7905: open (IN, '<'.LONCAPA::tempdir().$filename);
7906: while (my $line_in = <IN>) {
7907: chomp ($line_in);
7908: my @paths_and_file = split (m!/!, $line_in);
7909: my $file_part = pop (@paths_and_file);
7910: my $path_part = join ('/', @paths_and_file);
7911: $path_part.='/';
7912: my $path_and_file = $path_part.$file_part;
7913: if ($path_part eq $path) {
7914: $return_files{$file_part}= 'selected';
7915: }
7916: }
7917: close (IN);
7918: return (\%return_files);
7919: }
7920:
7921: # called in portfolio select mode, to show files selected NOT in current directory
7922: sub files_not_in_path {
7923: my ($user, $path) = @_;
7924: my $filename = $user."savedfiles";
7925: my @return_files;
7926: my $path_part;
7927: open(IN, '<'.LONCAPA::.$filename);
7928: while (my $line = <IN>) {
7929: #ok, I know it's clunky, but I want it to work
7930: my @paths_and_file = split(m|/|, $line);
7931: my $file_part = pop(@paths_and_file);
7932: chomp($file_part);
7933: my $path_part = join('/', @paths_and_file);
7934: $path_part .= '/';
7935: my $path_and_file = $path_part.$file_part;
7936: if ($path_part ne $path) {
7937: push(@return_files, ($path_and_file));
7938: }
7939: }
7940: close(OUT);
7941: return (@return_files);
7942: }
7943:
7944: #----------------------------------------------Get portfolio file permissions
7945:
7946: sub get_portfile_permissions {
7947: my ($domain,$user) = @_;
7948: my %current_permissions = &dump('file_permissions',$domain,$user);
7949: my ($tmp)=keys(%current_permissions);
7950: if ($tmp=~/^error:/) { undef(%current_permissions); }
7951: return \%current_permissions;
7952: }
7953:
7954: #---------------------------------------------Get portfolio file access controls
7955:
7956: sub get_access_controls {
7957: my ($current_permissions,$group,$file) = @_;
7958: my %access;
7959: my $real_file = $file;
7960: $file =~ s/\.meta$//;
7961: if (defined($file)) {
7962: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7963: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
7964: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
7965: }
7966: }
7967: } else {
7968: foreach my $key (keys(%{$current_permissions})) {
7969: if ($key =~ /\0accesscontrol$/) {
7970: if (defined($group)) {
7971: if ($key !~ m-^\Q$group\E/-) {
7972: next;
7973: }
7974: }
7975: my ($fullpath) = split(/\0/,$key);
7976: if (ref($$current_permissions{$key}) eq 'HASH') {
7977: foreach my $control (keys(%{$$current_permissions{$key}})) {
7978: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7979: }
7980: }
7981: }
7982: }
7983: }
7984: return %access;
7985: }
7986:
7987: sub modify_access_controls {
7988: my ($file_name,$changes,$domain,$user)=@_;
7989: my ($outcome,$deloutcome);
7990: my %store_permissions;
7991: my %new_values;
7992: my %new_control;
7993: my %translation;
7994: my @deletions = ();
7995: my $now = time;
7996: if (exists($$changes{'activate'})) {
7997: if (ref($$changes{'activate'}) eq 'HASH') {
7998: my @newitems = sort(keys(%{$$changes{'activate'}}));
7999: my $numnew = scalar(@newitems);
8000: for (my $i=0; $i<$numnew; $i++) {
8001: my $newkey = $newitems[$i];
8002: my $newid = &Apache::loncommon::get_cgi_id();
8003: if ($newkey =~ /^\d+:/) {
8004: $newkey =~ s/^(\d+)/$newid/;
8005: $translation{$1} = $newid;
8006: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8007: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8008: $translation{$1} = $newid;
8009: }
8010: $new_values{$file_name."\0".$newkey} =
8011: $$changes{'activate'}{$newitems[$i]};
8012: $new_control{$newkey} = $now;
8013: }
8014: }
8015: }
8016: my %todelete;
8017: my %changed_items;
8018: foreach my $action ('delete','update') {
8019: if (exists($$changes{$action})) {
8020: if (ref($$changes{$action}) eq 'HASH') {
8021: foreach my $key (keys(%{$$changes{$action}})) {
8022: my ($itemnum) = ($key =~ /^([^:]+):/);
8023: if ($action eq 'delete') {
8024: $todelete{$itemnum} = 1;
8025: } else {
8026: $changed_items{$itemnum} = $key;
8027: }
8028: }
8029: }
8030: }
8031: }
8032: # get lock on access controls for file.
8033: my $lockhash = {
8034: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8035: ':'.$env{'user.domain'},
8036: };
8037: my $tries = 0;
8038: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8039:
8040: while (($gotlock ne 'ok') && $tries <3) {
8041: $tries ++;
8042: sleep 1;
8043: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8044: }
8045: if ($gotlock eq 'ok') {
8046: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8047: my ($tmp)=keys(%curr_permissions);
8048: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8049: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8050: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8051: if (ref($curr_controls) eq 'HASH') {
8052: foreach my $control_item (keys(%{$curr_controls})) {
8053: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8054: if (defined($todelete{$itemnum})) {
8055: push(@deletions,$file_name."\0".$control_item);
8056: } else {
8057: if (defined($changed_items{$itemnum})) {
8058: $new_control{$changed_items{$itemnum}} = $now;
8059: push(@deletions,$file_name."\0".$control_item);
8060: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8061: } else {
8062: $new_control{$control_item} = $$curr_controls{$control_item};
8063: }
8064: }
8065: }
8066: }
8067: }
8068: my ($group);
8069: if (&is_course($domain,$user)) {
8070: ($group,my $file) = split(/\//,$file_name,2);
8071: }
8072: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8073: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8074: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8075: # remove lock
8076: my @del_lock = ($file_name."\0".'locked_access_records');
8077: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8078: my $sqlresult =
8079: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8080: $group);
8081: } else {
8082: $outcome = "error: could not obtain lockfile\n";
8083: }
8084: return ($outcome,$deloutcome,\%new_values,\%translation);
8085: }
8086:
8087: sub make_public_indefinitely {
8088: my ($requrl) = @_;
8089: my $now = time;
8090: my $action = 'activate';
8091: my $aclnum = 0;
8092: if (&is_portfolio_url($requrl)) {
8093: my (undef,$udom,$unum,$file_name,$group) =
8094: &parse_portfolio_url($requrl);
8095: my $current_perms = &get_portfile_permissions($udom,$unum);
8096: my %access_controls = &get_access_controls($current_perms,
8097: $group,$file_name);
8098: foreach my $key (keys(%{$access_controls{$file_name}})) {
8099: my ($num,$scope,$end,$start) =
8100: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8101: if ($scope eq 'public') {
8102: if ($start <= $now && $end == 0) {
8103: $action = 'none';
8104: } else {
8105: $action = 'update';
8106: $aclnum = $num;
8107: }
8108: last;
8109: }
8110: }
8111: if ($action eq 'none') {
8112: return 'ok';
8113: } else {
8114: my %changes;
8115: my $newend = 0;
8116: my $newstart = $now;
8117: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8118: $changes{$action}{$newkey} = {
8119: type => 'public',
8120: time => {
8121: start => $newstart,
8122: end => $newend,
8123: },
8124: };
8125: my ($outcome,$deloutcome,$new_values,$translation) =
8126: &modify_access_controls($file_name,\%changes,$udom,$unum);
8127: return $outcome;
8128: }
8129: } else {
8130: return 'invalid';
8131: }
8132: }
8133:
8134: #------------------------------------------------------Get Marked as Read Only
8135:
8136: sub get_marked_as_readonly {
8137: my ($domain,$user,$what,$group) = @_;
8138: my $current_permissions = &get_portfile_permissions($domain,$user);
8139: my @readonly_files;
8140: my $cmp1=$what;
8141: if (ref($what)) { $cmp1=join('',@{$what}) };
8142: while (my ($file_name,$value) = each(%{$current_permissions})) {
8143: if (defined($group)) {
8144: if ($file_name !~ m-^\Q$group\E/-) {
8145: next;
8146: }
8147: }
8148: if (ref($value) eq "ARRAY"){
8149: foreach my $stored_what (@{$value}) {
8150: my $cmp2=$stored_what;
8151: if (ref($stored_what) eq 'ARRAY') {
8152: $cmp2=join('',@{$stored_what});
8153: }
8154: if ($cmp1 eq $cmp2) {
8155: push(@readonly_files, $file_name);
8156: last;
8157: } elsif (!defined($what)) {
8158: push(@readonly_files, $file_name);
8159: last;
8160: }
8161: }
8162: }
8163: }
8164: return @readonly_files;
8165: }
8166: #-----------------------------------------------------------Get Marked as Read Only Hash
8167:
8168: sub get_marked_as_readonly_hash {
8169: my ($current_permissions,$group,$what) = @_;
8170: my %readonly_files;
8171: while (my ($file_name,$value) = each(%{$current_permissions})) {
8172: if (defined($group)) {
8173: if ($file_name !~ m-^\Q$group\E/-) {
8174: next;
8175: }
8176: }
8177: if (ref($value) eq "ARRAY"){
8178: foreach my $stored_what (@{$value}) {
8179: if (ref($stored_what) eq 'ARRAY') {
8180: foreach my $lock_descriptor(@{$stored_what}) {
8181: if ($lock_descriptor eq 'graded') {
8182: $readonly_files{$file_name} = 'graded';
8183: } elsif ($lock_descriptor eq 'handback') {
8184: $readonly_files{$file_name} = 'handback';
8185: } else {
8186: if (!exists($readonly_files{$file_name})) {
8187: $readonly_files{$file_name} = 'locked';
8188: }
8189: }
8190: }
8191: }
8192: }
8193: }
8194: }
8195: return %readonly_files;
8196: }
8197: # ------------------------------------------------------------ Unmark as Read Only
8198:
8199: sub unmark_as_readonly {
8200: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8201: # for portfolio submissions, $what contains [$symb,$crsid]
8202: my ($domain,$user,$what,$file_name,$group) = @_;
8203: $file_name = &declutter_portfile($file_name);
8204: my $symb_crs = $what;
8205: if (ref($what)) { $symb_crs=join('',@$what); }
8206: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8207: my ($tmp)=keys(%current_permissions);
8208: if ($tmp=~/^error:/) { undef(%current_permissions); }
8209: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8210: foreach my $file (@readonly_files) {
8211: my $clean_file = &declutter_portfile($file);
8212: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8213: my $current_locks = $current_permissions{$file};
8214: my @new_locks;
8215: my @del_keys;
8216: if (ref($current_locks) eq "ARRAY"){
8217: foreach my $locker (@{$current_locks}) {
8218: my $compare=$locker;
8219: if (ref($locker) eq 'ARRAY') {
8220: $compare=join('',@{$locker});
8221: if ($compare ne $symb_crs) {
8222: push(@new_locks, $locker);
8223: }
8224: }
8225: }
8226: if (scalar(@new_locks) > 0) {
8227: $current_permissions{$file} = \@new_locks;
8228: } else {
8229: push(@del_keys, $file);
8230: &del('file_permissions',\@del_keys, $domain, $user);
8231: delete($current_permissions{$file});
8232: }
8233: }
8234: }
8235: &put('file_permissions',\%current_permissions,$domain,$user);
8236: return;
8237: }
8238:
8239: # ------------------------------------------------------------ Directory lister
8240:
8241: sub dirlist {
8242: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8243: $uri=~s/^\///;
8244: $uri=~s/\/$//;
8245: my ($udom, $uname);
8246: if ($getuserdir) {
8247: $udom = $userdomain;
8248: $uname = $username;
8249: } else {
8250: (undef,$udom,$uname)=split(/\//,$uri);
8251: if(defined($userdomain)) {
8252: $udom = $userdomain;
8253: }
8254: if(defined($username)) {
8255: $uname = $username;
8256: }
8257: }
8258: my ($dirRoot,$listing,@listing_results);
8259:
8260: $dirRoot = $perlvar{'lonDocRoot'};
8261: if (defined($getpropath)) {
8262: $dirRoot = &propath($udom,$uname);
8263: $dirRoot =~ s/\/$//;
8264: } elsif (defined($getuserdir)) {
8265: my $subdir=$uname.'__';
8266: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8267: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8268: ."/$udom/$subdir/$uname";
8269: } elsif (defined($alternateRoot)) {
8270: $dirRoot = $alternateRoot;
8271: }
8272:
8273: if($udom) {
8274: if($uname) {
8275: my $uhome = &homeserver($uname,$udom);
8276: if ($uhome eq 'no_host') {
8277: return ([],'no_host');
8278: }
8279: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8280: .$getuserdir.':'.&escape($dirRoot)
8281: .':'.&escape($uname).':'.&escape($udom),$uhome);
8282: if ($listing eq 'unknown_cmd') {
8283: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8284: } else {
8285: @listing_results = map { &unescape($_); } split(/:/,$listing);
8286: }
8287: if ($listing eq 'unknown_cmd') {
8288: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8289: @listing_results = split(/:/,$listing);
8290: } else {
8291: @listing_results = map { &unescape($_); } split(/:/,$listing);
8292: }
8293: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8294: ($listing eq 'rejected') || ($listing eq 'refused') ||
8295: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8296: return ([],$listing);
8297: } else {
8298: return (\@listing_results);
8299: }
8300: } elsif(!$alternateRoot) {
8301: my (%allusers,%listerror);
8302: my %servers = &get_servers($udom,'library');
8303: foreach my $tryserver (keys(%servers)) {
8304: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8305: &escape($udom),$tryserver);
8306: if ($listing eq 'unknown_cmd') {
8307: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8308: $udom, $tryserver);
8309: } else {
8310: @listing_results = map { &unescape($_); } split(/:/,$listing);
8311: }
8312: if ($listing eq 'unknown_cmd') {
8313: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8314: $udom, $tryserver);
8315: @listing_results = split(/:/,$listing);
8316: } else {
8317: @listing_results =
8318: map { &unescape($_); } split(/:/,$listing);
8319: }
8320: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8321: ($listing eq 'rejected') || ($listing eq 'refused') ||
8322: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8323: $listerror{$tryserver} = $listing;
8324: } else {
8325: foreach my $line (@listing_results) {
8326: my ($entry) = split(/&/,$line,2);
8327: $allusers{$entry} = 1;
8328: }
8329: }
8330: }
8331: my @alluserslist=();
8332: foreach my $user (sort(keys(%allusers))) {
8333: push(@alluserslist,$user.'&user');
8334: }
8335: return (\@alluserslist);
8336: } else {
8337: return ([],'missing username');
8338: }
8339: } elsif(!defined($getpropath)) {
8340: my $path = $perlvar{'lonDocRoot'}.'/res/';
8341: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8342: return (\@all_domains);
8343: } else {
8344: return ([],'missing domain');
8345: }
8346: }
8347:
8348: # --------------------------------------------- GetFileTimestamp
8349: # This function utilizes dirlist and returns the date stamp for
8350: # when it was last modified. It will also return an error of -1
8351: # if an error occurs
8352:
8353: sub GetFileTimestamp {
8354: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8355: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8356: $studentName = &LONCAPA::clean_username($studentName);
8357: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8358: undef,$getuserdir);
8359: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8360: return -1;
8361: }
8362: if (ref($fileref) eq 'ARRAY') {
8363: my @stats = split('&',$fileref->[0]);
8364: # @stats contains first the filename, then the stat output
8365: return $stats[10]; # so this is 10 instead of 9.
8366: } else {
8367: return -1;
8368: }
8369: }
8370:
8371: sub stat_file {
8372: my ($uri) = @_;
8373: $uri = &clutter_with_no_wrapper($uri);
8374:
8375: my ($udom,$uname,$file);
8376: if ($uri =~ m-^/(uploaded|editupload)/-) {
8377: ($udom,$uname,$file) =
8378: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8379: $file = 'userfiles/'.$file;
8380: }
8381: if ($uri =~ m-^/res/-) {
8382: ($udom,$uname) =
8383: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8384: $file = $uri;
8385: }
8386:
8387: if (!$udom || !$uname || !$file) {
8388: # unable to handle the uri
8389: return ();
8390: }
8391: my $getpropath;
8392: if ($file =~ /^userfiles\//) {
8393: $getpropath = 1;
8394: }
8395: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8396: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8397: return ();
8398: } else {
8399: if (ref($listref) eq 'ARRAY') {
8400: my @stats = split('&',$listref->[0]);
8401: shift(@stats); #filename is first
8402: return @stats;
8403: }
8404: }
8405: return ();
8406: }
8407:
8408: # -------------------------------------------------------- Value of a Condition
8409:
8410: # gets the value of a specific preevaluated condition
8411: # stored in the string $env{user.state.<cid>}
8412: # or looks up a condition reference in the bighash and if if hasn't
8413: # already been evaluated recurses into docondval to get the value of
8414: # the condition, then memoizing it to
8415: # $env{user.state.<cid>.<condition>}
8416: sub directcondval {
8417: my $number=shift;
8418: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8419: &Apache::lonuserstate::evalstate();
8420: }
8421: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8422: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8423: } elsif ($number =~ /^_/) {
8424: my $sub_condition;
8425: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8426: &GDBM_READER(),0640)) {
8427: $sub_condition=$bighash{'conditions'.$number};
8428: untie(%bighash);
8429: }
8430: my $value = &docondval($sub_condition);
8431: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8432: return $value;
8433: }
8434: if ($env{'user.state.'.$env{'request.course.id'}}) {
8435: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8436: } else {
8437: return 2;
8438: }
8439: }
8440:
8441: # get the collection of conditions for this resource
8442: sub condval {
8443: my $condidx=shift;
8444: my $allpathcond='';
8445: foreach my $cond (split(/\|/,$condidx)) {
8446: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8447: $allpathcond.=
8448: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8449: }
8450: }
8451: $allpathcond=~s/\|$//;
8452: return &docondval($allpathcond);
8453: }
8454:
8455: #evaluates an expression of conditions
8456: sub docondval {
8457: my ($allpathcond) = @_;
8458: my $result=0;
8459: if ($env{'request.course.id'}
8460: && defined($allpathcond)) {
8461: my $operand='|';
8462: my @stack;
8463: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8464: if ($chunk eq '(') {
8465: push @stack,($operand,$result);
8466: } elsif ($chunk eq ')') {
8467: my $before=pop @stack;
8468: if (pop @stack eq '&') {
8469: $result=$result>$before?$before:$result;
8470: } else {
8471: $result=$result>$before?$result:$before;
8472: }
8473: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8474: $operand=$chunk;
8475: } else {
8476: my $new=directcondval($chunk);
8477: if ($operand eq '&') {
8478: $result=$result>$new?$new:$result;
8479: } else {
8480: $result=$result>$new?$result:$new;
8481: }
8482: }
8483: }
8484: }
8485: return $result;
8486: }
8487:
8488: # ---------------------------------------------------- Devalidate courseresdata
8489:
8490: sub devalidatecourseresdata {
8491: my ($coursenum,$coursedomain)=@_;
8492: my $hashid=$coursenum.':'.$coursedomain;
8493: &devalidate_cache_new('courseres',$hashid);
8494: }
8495:
8496:
8497: # --------------------------------------------------- Course Resourcedata Query
8498: #
8499: # Parameters:
8500: # $coursenum - Number of the course.
8501: # $coursedomain - Domain at which the course was created.
8502: # Returns:
8503: # A hash of the course parameters along (I think) with timestamps
8504: # and version info.
8505:
8506: sub get_courseresdata {
8507: my ($coursenum,$coursedomain)=@_;
8508: my $coursehom=&homeserver($coursenum,$coursedomain);
8509: my $hashid=$coursenum.':'.$coursedomain;
8510: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8511: my %dumpreply;
8512: unless (defined($cached)) {
8513: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8514: $result=\%dumpreply;
8515: my ($tmp) = keys(%dumpreply);
8516: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8517: &do_cache_new('courseres',$hashid,$result,600);
8518: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8519: return $tmp;
8520: } elsif ($tmp =~ /^(error)/) {
8521: $result=undef;
8522: &do_cache_new('courseres',$hashid,$result,600);
8523: }
8524: }
8525: return $result;
8526: }
8527:
8528: sub devalidateuserresdata {
8529: my ($uname,$udom)=@_;
8530: my $hashid="$udom:$uname";
8531: &devalidate_cache_new('userres',$hashid);
8532: }
8533:
8534: sub get_userresdata {
8535: my ($uname,$udom)=@_;
8536: #most student don\'t have any data set, check if there is some data
8537: if (&EXT_cache_status($udom,$uname)) { return undef; }
8538:
8539: my $hashid="$udom:$uname";
8540: my ($result,$cached)=&is_cached_new('userres',$hashid);
8541: if (!defined($cached)) {
8542: my %resourcedata=&dump('resourcedata',$udom,$uname);
8543: $result=\%resourcedata;
8544: &do_cache_new('userres',$hashid,$result,600);
8545: }
8546: my ($tmp)=keys(%$result);
8547: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8548: return $result;
8549: }
8550: #error 2 occurs when the .db doesn't exist
8551: if ($tmp!~/error: 2 /) {
8552: &logthis("<font color=\"blue\">WARNING:".
8553: " Trying to get resource data for ".
8554: $uname." at ".$udom.": ".
8555: $tmp."</font>");
8556: } elsif ($tmp=~/error: 2 /) {
8557: #&EXT_cache_set($udom,$uname);
8558: &do_cache_new('userres',$hashid,undef,600);
8559: undef($tmp); # not really an error so don't send it back
8560: }
8561: return $tmp;
8562: }
8563: #----------------------------------------------- resdata - return resource data
8564: # Purpose:
8565: # Return resource data for either users or for a course.
8566: # Parameters:
8567: # $name - Course/user name.
8568: # $domain - Name of the domain the user/course is registered on.
8569: # $type - Type of thing $name is (must be 'course' or 'user'
8570: # @which - Array of names of resources desired.
8571: # Returns:
8572: # The value of the first reasource in @which that is found in the
8573: # resource hash.
8574: # Exceptional Conditions:
8575: # If the $type passed in is not valid (not the string 'course' or
8576: # 'user', an undefined reference is returned.
8577: # If none of the resources are found, an undef is returned
8578: sub resdata {
8579: my ($name,$domain,$type,@which)=@_;
8580: my $result;
8581: if ($type eq 'course') {
8582: $result=&get_courseresdata($name,$domain);
8583: } elsif ($type eq 'user') {
8584: $result=&get_userresdata($name,$domain);
8585: }
8586: if (!ref($result)) { return $result; }
8587: foreach my $item (@which) {
8588: if (defined($result->{$item->[0]})) {
8589: return [$result->{$item->[0]},$item->[1]];
8590: }
8591: }
8592: return undef;
8593: }
8594:
8595: #
8596: # EXT resource caching routines
8597: #
8598:
8599: sub clear_EXT_cache_status {
8600: &delenv('cache.EXT.');
8601: }
8602:
8603: sub EXT_cache_status {
8604: my ($target_domain,$target_user) = @_;
8605: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8606: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8607: # We know already the user has no data
8608: return 1;
8609: } else {
8610: return 0;
8611: }
8612: }
8613:
8614: sub EXT_cache_set {
8615: my ($target_domain,$target_user) = @_;
8616: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8617: #&appenv({$cachename => time});
8618: }
8619:
8620: # --------------------------------------------------------- Value of a Variable
8621: sub EXT {
8622:
8623: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8624: unless ($varname) { return ''; }
8625: #get real user name/domain, courseid and symb
8626: my $courseid;
8627: my $publicuser;
8628: if ($symbparm) {
8629: $symbparm=&get_symb_from_alias($symbparm);
8630: }
8631: if (!($uname && $udom)) {
8632: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8633: if (!$symbparm) { $symbparm=$cursymb; }
8634: } else {
8635: $courseid=$env{'request.course.id'};
8636: }
8637: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8638: my $rest;
8639: if (defined($therest[0])) {
8640: $rest=join('.',@therest);
8641: } else {
8642: $rest='';
8643: }
8644:
8645: my $qualifierrest=$qualifier;
8646: if ($rest) { $qualifierrest.='.'.$rest; }
8647: my $spacequalifierrest=$space;
8648: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8649: if ($realm eq 'user') {
8650: # --------------------------------------------------------------- user.resource
8651: if ($space eq 'resource') {
8652: if ( (defined($Apache::lonhomework::parsing_a_problem)
8653: || defined($Apache::lonhomework::parsing_a_task))
8654: &&
8655: ($symbparm eq &symbread()) ) {
8656: # if we are in the middle of processing the resource the
8657: # get the value we are planning on committing
8658: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8659: return $Apache::lonhomework::results{$qualifierrest};
8660: } else {
8661: return $Apache::lonhomework::history{$qualifierrest};
8662: }
8663: } else {
8664: my %restored;
8665: if ($publicuser || $env{'request.state'} eq 'construct') {
8666: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8667: } else {
8668: %restored=&restore($symbparm,$courseid,$udom,$uname);
8669: }
8670: return $restored{$qualifierrest};
8671: }
8672: # ----------------------------------------------------------------- user.access
8673: } elsif ($space eq 'access') {
8674: # FIXME - not supporting calls for a specific user
8675: return &allowed($qualifier,$rest);
8676: # ------------------------------------------ user.preferences, user.environment
8677: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8678: if (($uname eq $env{'user.name'}) &&
8679: ($udom eq $env{'user.domain'})) {
8680: return $env{join('.',('environment',$qualifierrest))};
8681: } else {
8682: my %returnhash;
8683: if (!$publicuser) {
8684: %returnhash=&userenvironment($udom,$uname,
8685: $qualifierrest);
8686: }
8687: return $returnhash{$qualifierrest};
8688: }
8689: # ----------------------------------------------------------------- user.course
8690: } elsif ($space eq 'course') {
8691: # FIXME - not supporting calls for a specific user
8692: return $env{join('.',('request.course',$qualifier))};
8693: # ------------------------------------------------------------------- user.role
8694: } elsif ($space eq 'role') {
8695: # FIXME - not supporting calls for a specific user
8696: my ($role,$where)=split(/\./,$env{'request.role'});
8697: if ($qualifier eq 'value') {
8698: return $role;
8699: } elsif ($qualifier eq 'extent') {
8700: return $where;
8701: }
8702: # ----------------------------------------------------------------- user.domain
8703: } elsif ($space eq 'domain') {
8704: return $udom;
8705: # ------------------------------------------------------------------- user.name
8706: } elsif ($space eq 'name') {
8707: return $uname;
8708: # ---------------------------------------------------- Any other user namespace
8709: } else {
8710: my %reply;
8711: if (!$publicuser) {
8712: %reply=&get($space,[$qualifierrest],$udom,$uname);
8713: }
8714: return $reply{$qualifierrest};
8715: }
8716: } elsif ($realm eq 'query') {
8717: # ---------------------------------------------- pull stuff out of query string
8718: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8719: [$spacequalifierrest]);
8720: return $env{'form.'.$spacequalifierrest};
8721: } elsif ($realm eq 'request') {
8722: # ------------------------------------------------------------- request.browser
8723: if ($space eq 'browser') {
8724: return $env{'browser.'.$qualifier};
8725: # ------------------------------------------------------------ request.filename
8726: } else {
8727: return $env{'request.'.$spacequalifierrest};
8728: }
8729: } elsif ($realm eq 'course') {
8730: # ---------------------------------------------------------- course.description
8731: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
8732: } elsif ($realm eq 'resource') {
8733:
8734: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
8735: if (!$symbparm) { $symbparm=&symbread(); }
8736: }
8737:
8738: if ($space eq 'title') {
8739: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8740: return &gettitle($symbparm);
8741: }
8742:
8743: if ($space eq 'map') {
8744: my ($map) = &decode_symb($symbparm);
8745: return &symbread($map);
8746: }
8747: if ($space eq 'filename') {
8748: if ($symbparm) {
8749: return &clutter((&decode_symb($symbparm))[2]);
8750: }
8751: return &hreflocation('',$env{'request.filename'});
8752: }
8753:
8754: my ($section, $group, @groups);
8755: my ($courselevelm,$courselevel);
8756: if ($symbparm && defined($courseid) &&
8757: $courseid eq $env{'request.course.id'}) {
8758:
8759: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
8760:
8761: # ----------------------------------------------------- Cascading lookup scheme
8762: my $symbp=$symbparm;
8763: my $mapp=&deversion((&decode_symb($symbp))[0]);
8764:
8765: my $symbparm=$symbp.'.'.$spacequalifierrest;
8766: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8767:
8768: if (($env{'user.name'} eq $uname) &&
8769: ($env{'user.domain'} eq $udom)) {
8770: $section=$env{'request.course.sec'};
8771: @groups = split(/:/,$env{'request.course.groups'});
8772: @groups=&sort_course_groups($courseid,@groups);
8773: } else {
8774: if (! defined($usection)) {
8775: $section=&getsection($udom,$uname,$courseid);
8776: } else {
8777: $section = $usection;
8778: }
8779: @groups = &get_users_groups($udom,$uname,$courseid);
8780: }
8781:
8782: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8783: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8784: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8785:
8786: $courselevel=$courseid.'.'.$spacequalifierrest;
8787: my $courselevelr=$courseid.'.'.$symbparm;
8788: $courselevelm=$courseid.'.'.$mapparm;
8789:
8790: # ----------------------------------------------------------- first, check user
8791:
8792: my $userreply=&resdata($uname,$udom,'user',
8793: ([$courselevelr,'resource'],
8794: [$courselevelm,'map' ],
8795: [$courselevel, 'course' ]));
8796: if (defined($userreply)) { return &get_reply($userreply); }
8797:
8798: # ------------------------------------------------ second, check some of course
8799: my $coursereply;
8800: if (@groups > 0) {
8801: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8802: $mapparm,$spacequalifierrest);
8803: if (defined($coursereply)) { return &get_reply($coursereply); }
8804: }
8805:
8806: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8807: $env{'course.'.$courseid.'.domain'},
8808: 'course',
8809: ([$seclevelr, 'resource'],
8810: [$seclevelm, 'map' ],
8811: [$seclevel, 'course' ],
8812: [$courselevelr,'resource']));
8813: if (defined($coursereply)) { return &get_reply($coursereply); }
8814:
8815: # ------------------------------------------------------ third, check map parms
8816: my %parmhash=();
8817: my $thisparm='';
8818: if (tie(%parmhash,'GDBM_File',
8819: $env{'request.course.fn'}.'_parms.db',
8820: &GDBM_READER(),0640)) {
8821: $thisparm=$parmhash{$symbparm};
8822: untie(%parmhash);
8823: }
8824: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
8825: }
8826: # ------------------------------------------ fourth, look in resource metadata
8827:
8828: $spacequalifierrest=~s/\./\_/;
8829: my $filename;
8830: if (!$symbparm) { $symbparm=&symbread(); }
8831: if ($symbparm) {
8832: $filename=(&decode_symb($symbparm))[2];
8833: } else {
8834: $filename=$env{'request.filename'};
8835: }
8836: my $metadata=&metadata($filename,$spacequalifierrest);
8837: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8838: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
8839: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8840:
8841: # ---------------------------------------------- fourth, look in rest of course
8842: if ($symbparm && defined($courseid) &&
8843: $courseid eq $env{'request.course.id'}) {
8844: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8845: $env{'course.'.$courseid.'.domain'},
8846: 'course',
8847: ([$courselevelm,'map' ],
8848: [$courselevel, 'course']));
8849: if (defined($coursereply)) { return &get_reply($coursereply); }
8850: }
8851: # ------------------------------------------------------------------ Cascade up
8852: unless ($space eq '0') {
8853: my @parts=split(/_/,$space);
8854: my $id=pop(@parts);
8855: my $part=join('_',@parts);
8856: if ($part eq '') { $part='0'; }
8857: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
8858: $symbparm,$udom,$uname,$section,1);
8859: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
8860: }
8861: if ($recurse) { return undef; }
8862: my $pack_def=&packages_tab_default($filename,$varname);
8863: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
8864: # ---------------------------------------------------- Any other user namespace
8865: } elsif ($realm eq 'environment') {
8866: # ----------------------------------------------------------------- environment
8867: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8868: return $env{'environment.'.$spacequalifierrest};
8869: } else {
8870: if ($uname eq 'anonymous' && $udom eq '') {
8871: return '';
8872: }
8873: my %returnhash=&userenvironment($udom,$uname,
8874: $spacequalifierrest);
8875: return $returnhash{$spacequalifierrest};
8876: }
8877: } elsif ($realm eq 'system') {
8878: # ----------------------------------------------------------------- system.time
8879: if ($space eq 'time') {
8880: return time;
8881: }
8882: } elsif ($realm eq 'server') {
8883: # ----------------------------------------------------------------- system.time
8884: if ($space eq 'name') {
8885: return $ENV{'SERVER_NAME'};
8886: }
8887: }
8888: return '';
8889: }
8890:
8891: sub get_reply {
8892: my ($reply_value) = @_;
8893: if (ref($reply_value) eq 'ARRAY') {
8894: if (wantarray) {
8895: return @$reply_value;
8896: }
8897: return $reply_value->[0];
8898: } else {
8899: return $reply_value;
8900: }
8901: }
8902:
8903: sub check_group_parms {
8904: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8905: my @groupitems = ();
8906: my $resultitem;
8907: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
8908: foreach my $group (@{$groups}) {
8909: foreach my $level (@levels) {
8910: my $item = $courseid.'.['.$group.'].'.$level->[0];
8911: push(@groupitems,[$item,$level->[1]]);
8912: }
8913: }
8914: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8915: $env{'course.'.$courseid.'.domain'},
8916: 'course',@groupitems);
8917: return $coursereply;
8918: }
8919:
8920: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
8921: my ($courseid,@groups) = @_;
8922: @groups = sort(@groups);
8923: return @groups;
8924: }
8925:
8926: sub packages_tab_default {
8927: my ($uri,$varname)=@_;
8928: my (undef,$part,$name)=split(/\./,$varname);
8929:
8930: my (@extension,@specifics,$do_default);
8931: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
8932: my ($pack_type,$pack_part)=split(/_/,$package,2);
8933: if ($pack_type eq 'default') {
8934: $do_default=1;
8935: } elsif ($pack_type eq 'extension') {
8936: push(@extension,[$package,$pack_type,$pack_part]);
8937: } elsif ($pack_part eq $part || $pack_type eq 'part') {
8938: # only look at packages defaults for packages that this id is
8939: push(@specifics,[$package,$pack_type,$pack_part]);
8940: }
8941: }
8942: # first look for a package that matches the requested part id
8943: foreach my $package (@specifics) {
8944: my (undef,$pack_type,$pack_part)=@{$package};
8945: next if ($pack_part ne $part);
8946: if (defined($packagetab{"$pack_type&$name&default"})) {
8947: return $packagetab{"$pack_type&$name&default"};
8948: }
8949: }
8950: # look for any possible matching non extension_ package
8951: foreach my $package (@specifics) {
8952: my (undef,$pack_type,$pack_part)=@{$package};
8953: if (defined($packagetab{"$pack_type&$name&default"})) {
8954: return $packagetab{"$pack_type&$name&default"};
8955: }
8956: if ($pack_type eq 'part') { $pack_part='0'; }
8957: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8958: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
8959: }
8960: }
8961: # look for any posible extension_ match
8962: foreach my $package (@extension) {
8963: my ($package,$pack_type)=@{$package};
8964: if (defined($packagetab{"$pack_type&$name&default"})) {
8965: return $packagetab{"$pack_type&$name&default"};
8966: }
8967: if (defined($packagetab{$package."&$name&default"})) {
8968: return $packagetab{$package."&$name&default"};
8969: }
8970: }
8971: # look for a global default setting
8972: if ($do_default && defined($packagetab{"default&$name&default"})) {
8973: return $packagetab{"default&$name&default"};
8974: }
8975: return undef;
8976: }
8977:
8978: sub add_prefix_and_part {
8979: my ($prefix,$part)=@_;
8980: my $keyroot;
8981: if (defined($prefix) && $prefix !~ /^__/) {
8982: # prefix that has a part already
8983: $keyroot=$prefix;
8984: } elsif (defined($prefix)) {
8985: # prefix that is missing a part
8986: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8987: } else {
8988: # no prefix at all
8989: if (defined($part)) { $keyroot='_'.$part; }
8990: }
8991: return $keyroot;
8992: }
8993:
8994: # ---------------------------------------------------------------- Get metadata
8995:
8996: my %metaentry;
8997: my %importedpartids;
8998: sub metadata {
8999: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9000: $uri=&declutter($uri);
9001: # if it is a non metadata possible uri return quickly
9002: if (($uri eq '') ||
9003: (($uri =~ m|^/*adm/|) &&
9004: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9005: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9006: return undef;
9007: }
9008: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9009: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9010: return undef;
9011: }
9012: my $filename=$uri;
9013: $uri=~s/\.meta$//;
9014: #
9015: # Is the metadata already cached?
9016: # Look at timestamp of caching
9017: # Everything is cached by the main uri, libraries are never directly cached
9018: #
9019: if (!defined($liburi)) {
9020: my ($result,$cached)=&is_cached_new('meta',$uri);
9021: if (defined($cached)) { return $result->{':'.$what}; }
9022: }
9023: {
9024: # Imported parts would go here
9025: my %importedids=();
9026: my @origfileimportpartids=();
9027: my $importedparts=0;
9028: #
9029: # Is this a recursive call for a library?
9030: #
9031: # if (! exists($metacache{$uri})) {
9032: # $metacache{$uri}={};
9033: # }
9034: my $cachetime = 60*60;
9035: if ($liburi) {
9036: $liburi=&declutter($liburi);
9037: $filename=$liburi;
9038: } else {
9039: &devalidate_cache_new('meta',$uri);
9040: undef(%metaentry);
9041: }
9042: my %metathesekeys=();
9043: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9044: my $metastring;
9045: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9046: my $which = &hreflocation('','/'.($liburi || $uri));
9047: $metastring =
9048: &Apache::lonnet::ssi_body($which,
9049: ('grade_target' => 'meta'));
9050: $cachetime = 1; # only want this cached in the child not long term
9051: } elsif (($uri !~ m -^(editupload)/-) &&
9052: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9053: my $file=&filelocation('',&clutter($filename));
9054: #push(@{$metaentry{$uri.'.file'}},$file);
9055: $metastring=&getfile($file);
9056: }
9057: my $parser=HTML::LCParser->new(\$metastring);
9058: my $token;
9059: undef %metathesekeys;
9060: while ($token=$parser->get_token) {
9061: if ($token->[0] eq 'S') {
9062: if (defined($token->[2]->{'package'})) {
9063: #
9064: # This is a package - get package info
9065: #
9066: my $package=$token->[2]->{'package'};
9067: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9068: if (defined($token->[2]->{'id'})) {
9069: $keyroot.='_'.$token->[2]->{'id'};
9070: }
9071: if ($metaentry{':packages'}) {
9072: $metaentry{':packages'}.=','.$package.$keyroot;
9073: } else {
9074: $metaentry{':packages'}=$package.$keyroot;
9075: }
9076: foreach my $pack_entry (keys(%packagetab)) {
9077: my $part=$keyroot;
9078: $part=~s/^\_//;
9079: if ($pack_entry=~/^\Q$package\E\&/ ||
9080: $pack_entry=~/^\Q$package\E_0\&/) {
9081: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9082: # ignore package.tab specified default values
9083: # here &package_tab_default() will fetch those
9084: if ($subp eq 'default') { next; }
9085: my $value=$packagetab{$pack_entry};
9086: my $unikey;
9087: if ($pack =~ /_0$/) {
9088: $unikey='parameter_0_'.$name;
9089: $part=0;
9090: } else {
9091: $unikey='parameter'.$keyroot.'_'.$name;
9092: }
9093: if ($subp eq 'display') {
9094: $value.=' [Part: '.$part.']';
9095: }
9096: $metaentry{':'.$unikey.'.part'}=$part;
9097: $metathesekeys{$unikey}=1;
9098: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9099: $metaentry{':'.$unikey.'.'.$subp}=$value;
9100: }
9101: if (defined($metaentry{':'.$unikey.'.default'})) {
9102: $metaentry{':'.$unikey}=
9103: $metaentry{':'.$unikey.'.default'};
9104: }
9105: }
9106: }
9107: } else {
9108: #
9109: # This is not a package - some other kind of start tag
9110: #
9111: my $entry=$token->[1];
9112: my $unikey='';
9113:
9114: if ($entry eq 'import') {
9115: #
9116: # Importing a library here
9117: #
9118: my $location=$parser->get_text('/import');
9119: my $dir=$filename;
9120: $dir=~s|[^/]*$||;
9121: $location=&filelocation($dir,$location);
9122:
9123: my $importmode=$token->[2]->{'importmode'};
9124: if ($importmode eq 'problem') {
9125: # Import as problem/response
9126: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9127: } elsif ($importmode eq 'part') {
9128: # Import as part(s)
9129: $importedparts=1;
9130: # We need to get the original file and the imported file to get the part order correct
9131: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9132: # Load and inspect original file
9133: if ($#origfileimportpartids<0) {
9134: undef(%importedpartids);
9135: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9136: my $origfile=&getfile($origfilelocation);
9137: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9138: }
9139:
9140: # Load and inspect imported file
9141: my $impfile=&getfile($location);
9142: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9143: if ($#impfilepartids>=0) {
9144: # This problem had parts
9145: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9146: } else {
9147: # Importing by turning a single problem into a problem part
9148: # It gets the import-tags ID as part-ID
9149: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9150: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9151: }
9152: } else {
9153: # Normal import
9154: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9155: if (defined($token->[2]->{'id'})) {
9156: $unikey.='_'.$token->[2]->{'id'};
9157: }
9158: }
9159:
9160: if ($depthcount<20) {
9161: my $metadata =
9162: &metadata($uri,'keys', $location,$unikey,
9163: $depthcount+1);
9164: foreach my $meta (split(',',$metadata)) {
9165: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9166: $metathesekeys{$meta}=1;
9167: }
9168:
9169: }
9170: } else {
9171: #
9172: # Not importing, some other kind of non-package, non-library start tag
9173: #
9174: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9175: if (defined($token->[2]->{'id'})) {
9176: $unikey.='_'.$token->[2]->{'id'};
9177: }
9178: if (defined($token->[2]->{'name'})) {
9179: $unikey.='_'.$token->[2]->{'name'};
9180: }
9181: $metathesekeys{$unikey}=1;
9182: foreach my $param (@{$token->[3]}) {
9183: $metaentry{':'.$unikey.'.'.$param} =
9184: $token->[2]->{$param};
9185: }
9186: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9187: my $default=$metaentry{':'.$unikey.'.default'};
9188: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9189: # only ws inside the tag, and not in default, so use default
9190: # as value
9191: $metaentry{':'.$unikey}=$default;
9192: } elsif ( $internaltext =~ /\S/ ) {
9193: # something interesting inside the tag
9194: $metaentry{':'.$unikey}=$internaltext;
9195: } else {
9196: # no interesting values, don't set a default
9197: }
9198: # end of not-a-package not-a-library import
9199: }
9200: # end of not-a-package start tag
9201: }
9202: # the next is the end of "start tag"
9203: }
9204: }
9205: my ($extension) = ($uri =~ /\.(\w+)$/);
9206: $extension = lc($extension);
9207: if ($extension eq 'htm') { $extension='html'; }
9208:
9209: foreach my $key (keys(%packagetab)) {
9210: #no specific packages #how's our extension
9211: if ($key!~/^extension_\Q$extension\E&/) { next; }
9212: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9213: \%metathesekeys);
9214: }
9215:
9216: if (!exists($metaentry{':packages'})
9217: || $packagetab{"import_defaults&extension_$extension"}) {
9218: foreach my $key (keys(%packagetab)) {
9219: #no specific packages well let's get default then
9220: if ($key!~/^default&/) { next; }
9221: &metadata_create_package_def($uri,$key,'default',
9222: \%metathesekeys);
9223: }
9224: }
9225: # are there custom rights to evaluate
9226: if ($metaentry{':copyright'} eq 'custom') {
9227:
9228: #
9229: # Importing a rights file here
9230: #
9231: unless ($depthcount) {
9232: my $location=$metaentry{':customdistributionfile'};
9233: my $dir=$filename;
9234: $dir=~s|[^/]*$||;
9235: $location=&filelocation($dir,$location);
9236: my $rights_metadata =
9237: &metadata($uri,'keys',$location,'_rights',
9238: $depthcount+1);
9239: foreach my $rights (split(',',$rights_metadata)) {
9240: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9241: $metathesekeys{$rights}=1;
9242: }
9243: }
9244: }
9245: # uniqifiy package listing
9246: my %seen;
9247: my @uniq_packages =
9248: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9249: $metaentry{':packages'} = join(',',@uniq_packages);
9250:
9251: if ($importedparts) {
9252: # We had imported parts and need to rebuild partorder
9253: $metaentry{':partorder'}='';
9254: $metathesekeys{'partorder'}=1;
9255: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9256: if ($origfileimportpartids[$index] eq 'part') {
9257: # original part, part of the problem
9258: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9259: } else {
9260: # we have imported parts at this position
9261: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9262: }
9263: }
9264: $metaentry{':partorder'}=~s/^\,//;
9265: }
9266:
9267: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9268: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9269: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9270: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9271: # this is the end of "was not already recently cached
9272: }
9273: return $metaentry{':'.$what};
9274: }
9275:
9276: sub metadata_create_package_def {
9277: my ($uri,$key,$package,$metathesekeys)=@_;
9278: my ($pack,$name,$subp)=split(/\&/,$key);
9279: if ($subp eq 'default') { next; }
9280:
9281: if (defined($metaentry{':packages'})) {
9282: $metaentry{':packages'}.=','.$package;
9283: } else {
9284: $metaentry{':packages'}=$package;
9285: }
9286: my $value=$packagetab{$key};
9287: my $unikey;
9288: $unikey='parameter_0_'.$name;
9289: $metaentry{':'.$unikey.'.part'}=0;
9290: $$metathesekeys{$unikey}=1;
9291: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9292: $metaentry{':'.$unikey.'.'.$subp}=$value;
9293: }
9294: if (defined($metaentry{':'.$unikey.'.default'})) {
9295: $metaentry{':'.$unikey}=
9296: $metaentry{':'.$unikey.'.default'};
9297: }
9298: }
9299:
9300: sub metadata_generate_part0 {
9301: my ($metadata,$metacache,$uri) = @_;
9302: my %allnames;
9303: foreach my $metakey (keys(%$metadata)) {
9304: if ($metakey=~/^parameter\_(.*)/) {
9305: my $part=$$metacache{':'.$metakey.'.part'};
9306: my $name=$$metacache{':'.$metakey.'.name'};
9307: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9308: $allnames{$name}=$part;
9309: }
9310: }
9311: }
9312: foreach my $name (keys(%allnames)) {
9313: $$metadata{"parameter_0_$name"}=1;
9314: my $key=":parameter_0_$name";
9315: $$metacache{"$key.part"}='0';
9316: $$metacache{"$key.name"}=$name;
9317: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9318: $allnames{$name}.'_'.$name.
9319: '.type'};
9320: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9321: '.display'};
9322: my $expr='[Part: '.$allnames{$name}.']';
9323: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9324: $$metacache{"$key.display"}=$olddis;
9325: }
9326: }
9327:
9328: # ------------------------------------------------------ Devalidate title cache
9329:
9330: sub devalidate_title_cache {
9331: my ($url)=@_;
9332: if (!$env{'request.course.id'}) { return; }
9333: my $symb=&symbread($url);
9334: if (!$symb) { return; }
9335: my $key=$env{'request.course.id'}."\0".$symb;
9336: &devalidate_cache_new('title',$key);
9337: }
9338:
9339: # ------------------------------------------------- Get the title of a course
9340:
9341: sub current_course_title {
9342: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9343: }
9344: # ------------------------------------------------- Get the title of a resource
9345:
9346: sub gettitle {
9347: my $urlsymb=shift;
9348: my $symb=&symbread($urlsymb);
9349: if ($symb) {
9350: my $key=$env{'request.course.id'}."\0".$symb;
9351: my ($result,$cached)=&is_cached_new('title',$key);
9352: if (defined($cached)) {
9353: return $result;
9354: }
9355: my ($map,$resid,$url)=&decode_symb($symb);
9356: my $title='';
9357: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9358: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9359: } else {
9360: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9361: &GDBM_READER(),0640)) {
9362: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9363: $title=$bighash{'title_'.$mapid.'.'.$resid};
9364: untie(%bighash);
9365: }
9366: }
9367: $title=~s/\&colon\;/\:/gs;
9368: if ($title) {
9369: return &do_cache_new('title',$key,$title,600);
9370: }
9371: $urlsymb=$url;
9372: }
9373: my $title=&metadata($urlsymb,'title');
9374: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9375: return $title;
9376: }
9377:
9378: sub get_slot {
9379: my ($which,$cnum,$cdom)=@_;
9380: if (!$cnum || !$cdom) {
9381: (undef,my $courseid)=&whichuser();
9382: $cdom=$env{'course.'.$courseid.'.domain'};
9383: $cnum=$env{'course.'.$courseid.'.num'};
9384: }
9385: my $key=join("\0",'slots',$cdom,$cnum,$which);
9386: my %slotinfo;
9387: if (exists($remembered{$key})) {
9388: $slotinfo{$which} = $remembered{$key};
9389: } else {
9390: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9391: &Apache::lonhomework::showhash(%slotinfo);
9392: my ($tmp)=keys(%slotinfo);
9393: if ($tmp=~/^error:/) { return (); }
9394: $remembered{$key} = $slotinfo{$which};
9395: }
9396: if (ref($slotinfo{$which}) eq 'HASH') {
9397: return %{$slotinfo{$which}};
9398: }
9399: return $slotinfo{$which};
9400: }
9401: # ------------------------------------------------- Update symbolic store links
9402:
9403: sub symblist {
9404: my ($mapname,%newhash)=@_;
9405: $mapname=&deversion(&declutter($mapname));
9406: my %hash;
9407: if (($env{'request.course.fn'}) && (%newhash)) {
9408: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9409: &GDBM_WRCREAT(),0640)) {
9410: foreach my $url (keys(%newhash)) {
9411: next if ($url eq 'last_known'
9412: && $env{'form.no_update_last_known'});
9413: $hash{declutter($url)}=&encode_symb($mapname,
9414: $newhash{$url}->[1],
9415: $newhash{$url}->[0]);
9416: }
9417: if (untie(%hash)) {
9418: return 'ok';
9419: }
9420: }
9421: }
9422: return 'error';
9423: }
9424:
9425: # --------------------------------------------------------------- Verify a symb
9426:
9427: sub symbverify {
9428: my ($symb,$thisurl)=@_;
9429: my $thisfn=$thisurl;
9430: $thisfn=&declutter($thisfn);
9431: # direct jump to resource in page or to a sequence - will construct own symbs
9432: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9433: # check URL part
9434: my ($map,$resid,$url)=&decode_symb($symb);
9435:
9436: unless ($url eq $thisfn) { return 0; }
9437:
9438: $symb=&symbclean($symb);
9439: $thisurl=&deversion($thisurl);
9440: $thisfn=&deversion($thisfn);
9441:
9442: my %bighash;
9443: my $okay=0;
9444:
9445: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9446: &GDBM_READER(),0640)) {
9447: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9448: $thisurl =~ s/\?.+$//;
9449: }
9450: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9451: unless ($ids) {
9452: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9453: $ids=$bighash{$idkey};
9454: }
9455: if ($ids) {
9456: # ------------------------------------------------------------------- Has ID(s)
9457: foreach my $id (split(/\,/,$ids)) {
9458: my ($mapid,$resid)=split(/\./,$id);
9459: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9460: $symb =~ s/\?.+$//;
9461: }
9462: if (
9463: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9464: eq $symb) {
9465: if (($env{'request.role.adv'}) ||
9466: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9467: ($thisurl eq '/adm/navmaps')) {
9468: $okay=1;
9469: }
9470: }
9471: }
9472: }
9473: untie(%bighash);
9474: }
9475: return $okay;
9476: }
9477:
9478: # --------------------------------------------------------------- Clean-up symb
9479:
9480: sub symbclean {
9481: my $symb=shift;
9482: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9483: # remove version from map
9484: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9485:
9486: # remove version from URL
9487: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9488:
9489: # remove wrapper
9490:
9491: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9492: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9493: return $symb;
9494: }
9495:
9496: # ---------------------------------------------- Split symb to find map and url
9497:
9498: sub encode_symb {
9499: my ($map,$resid,$url)=@_;
9500: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9501: }
9502:
9503: sub decode_symb {
9504: my $symb=shift;
9505: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9506: my ($map,$resid,$url)=split(/___/,$symb);
9507: return (&fixversion($map),$resid,&fixversion($url));
9508: }
9509:
9510: sub fixversion {
9511: my $fn=shift;
9512: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9513: my %bighash;
9514: my $uri=&clutter($fn);
9515: my $key=$env{'request.course.id'}.'_'.$uri;
9516: # is this cached?
9517: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9518: if (defined($cached)) { return $result; }
9519: # unfortunately not cached, or expired
9520: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9521: &GDBM_READER(),0640)) {
9522: if ($bighash{'version_'.$uri}) {
9523: my $version=$bighash{'version_'.$uri};
9524: unless (($version eq 'mostrecent') ||
9525: ($version==&getversion($uri))) {
9526: $uri=~s/\.(\w+)$/\.$version\.$1/;
9527: }
9528: }
9529: untie %bighash;
9530: }
9531: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9532: }
9533:
9534: sub deversion {
9535: my $url=shift;
9536: $url=~s/\.\d+\.(\w+)$/\.$1/;
9537: return $url;
9538: }
9539:
9540: # ------------------------------------------------------ Return symb list entry
9541:
9542: sub symbread {
9543: my ($thisfn,$donotrecurse)=@_;
9544: my $cache_str='request.symbread.cached.'.$thisfn;
9545: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9546: # no filename provided? try from environment
9547: unless ($thisfn) {
9548: if ($env{'request.symb'}) {
9549: return $env{$cache_str}=&symbclean($env{'request.symb'});
9550: }
9551: $thisfn=$env{'request.filename'};
9552: }
9553: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9554: # is that filename actually a symb? Verify, clean, and return
9555: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9556: if (&symbverify($thisfn,$1)) {
9557: return $env{$cache_str}=&symbclean($thisfn);
9558: }
9559: }
9560: $thisfn=declutter($thisfn);
9561: my %hash;
9562: my %bighash;
9563: my $syval='';
9564: if (($env{'request.course.fn'}) && ($thisfn)) {
9565: my $targetfn = $thisfn;
9566: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9567: $targetfn = 'adm/wrapper/'.$thisfn;
9568: }
9569: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9570: $targetfn=$1;
9571: }
9572: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9573: &GDBM_READER(),0640)) {
9574: $syval=$hash{$targetfn};
9575: untie(%hash);
9576: }
9577: # ---------------------------------------------------------- There was an entry
9578: if ($syval) {
9579: #unless ($syval=~/\_\d+$/) {
9580: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9581: #&appenv({'request.ambiguous' => $thisfn});
9582: #return $env{$cache_str}='';
9583: #}
9584: #$syval.=$1;
9585: #}
9586: } else {
9587: # ------------------------------------------------------- Was not in symb table
9588: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9589: &GDBM_READER(),0640)) {
9590: # ---------------------------------------------- Get ID(s) for current resource
9591: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9592: unless ($ids) {
9593: $ids=$bighash{'ids_/'.$thisfn};
9594: }
9595: unless ($ids) {
9596: # alias?
9597: $ids=$bighash{'mapalias_'.$thisfn};
9598: }
9599: if ($ids) {
9600: # ------------------------------------------------------------------- Has ID(s)
9601: my @possibilities=split(/\,/,$ids);
9602: if ($#possibilities==0) {
9603: # ----------------------------------------------- There is only one possibility
9604: my ($mapid,$resid)=split(/\./,$ids);
9605: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9606: $resid,$thisfn);
9607: } elsif (!$donotrecurse) {
9608: # ------------------------------------------ There is more than one possibility
9609: my $realpossible=0;
9610: foreach my $id (@possibilities) {
9611: my $file=$bighash{'src_'.$id};
9612: if (&allowed('bre',$file)) {
9613: my ($mapid,$resid)=split(/\./,$id);
9614: if ($bighash{'map_type_'.$mapid} ne 'page') {
9615: $realpossible++;
9616: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9617: $resid,$thisfn);
9618: }
9619: }
9620: }
9621: if ($realpossible!=1) { $syval=''; }
9622: } else {
9623: $syval='';
9624: }
9625: }
9626: untie(%bighash)
9627: }
9628: }
9629: if ($syval) {
9630: return $env{$cache_str}=$syval;
9631: }
9632: }
9633: &appenv({'request.ambiguous' => $thisfn});
9634: return $env{$cache_str}='';
9635: }
9636:
9637: # ---------------------------------------------------------- Return random seed
9638:
9639: sub numval {
9640: my $txt=shift;
9641: $txt=~tr/A-J/0-9/;
9642: $txt=~tr/a-j/0-9/;
9643: $txt=~tr/K-T/0-9/;
9644: $txt=~tr/k-t/0-9/;
9645: $txt=~tr/U-Z/0-5/;
9646: $txt=~tr/u-z/0-5/;
9647: $txt=~s/\D//g;
9648: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9649: return int($txt);
9650: }
9651:
9652: sub numval2 {
9653: my $txt=shift;
9654: $txt=~tr/A-J/0-9/;
9655: $txt=~tr/a-j/0-9/;
9656: $txt=~tr/K-T/0-9/;
9657: $txt=~tr/k-t/0-9/;
9658: $txt=~tr/U-Z/0-5/;
9659: $txt=~tr/u-z/0-5/;
9660: $txt=~s/\D//g;
9661: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9662: my $total;
9663: foreach my $val (@txts) { $total+=$val; }
9664: if ($_64bit) { if ($total > 2**32) { return -1; } }
9665: return int($total);
9666: }
9667:
9668: sub numval3 {
9669: use integer;
9670: my $txt=shift;
9671: $txt=~tr/A-J/0-9/;
9672: $txt=~tr/a-j/0-9/;
9673: $txt=~tr/K-T/0-9/;
9674: $txt=~tr/k-t/0-9/;
9675: $txt=~tr/U-Z/0-5/;
9676: $txt=~tr/u-z/0-5/;
9677: $txt=~s/\D//g;
9678: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9679: my $total;
9680: foreach my $val (@txts) { $total+=$val; }
9681: if ($_64bit) { $total=(($total<<32)>>32); }
9682: return $total;
9683: }
9684:
9685: sub digest {
9686: my ($data)=@_;
9687: my $digest=&Digest::MD5::md5($data);
9688: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9689: my ($e,$f);
9690: {
9691: use integer;
9692: $e=($a+$b);
9693: $f=($c+$d);
9694: if ($_64bit) {
9695: $e=(($e<<32)>>32);
9696: $f=(($f<<32)>>32);
9697: }
9698: }
9699: if (wantarray) {
9700: return ($e,$f);
9701: } else {
9702: my $g;
9703: {
9704: use integer;
9705: $g=($e+$f);
9706: if ($_64bit) {
9707: $g=(($g<<32)>>32);
9708: }
9709: }
9710: return $g;
9711: }
9712: }
9713:
9714: sub latest_rnd_algorithm_id {
9715: return '64bit5';
9716: }
9717:
9718: sub get_rand_alg {
9719: my ($courseid)=@_;
9720: if (!$courseid) { $courseid=(&whichuser())[1]; }
9721: if ($courseid) {
9722: return $env{"course.$courseid.rndseed"};
9723: }
9724: return &latest_rnd_algorithm_id();
9725: }
9726:
9727: sub validCODE {
9728: my ($CODE)=@_;
9729: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9730: return 0;
9731: }
9732:
9733: sub getCODE {
9734: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
9735: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9736: defined($Apache::lonhomework::parsing_a_task) ) &&
9737: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
9738: return $Apache::lonhomework::history{'resource.CODE'};
9739: }
9740: return undef;
9741: }
9742: #
9743: # Determines the random seed for a specific context:
9744: #
9745: # parameters:
9746: # symb - in course context the symb for the seed.
9747: # course_id - The course id of the form domain_coursenum.
9748: # domain - Domain for the user.
9749: # course - Course for the user.
9750: # cenv - environment of the course.
9751: #
9752: # NOTE:
9753: # All parameters are picked out of the environment if missing
9754: # or not defined.
9755: # If a symb cannot be determined the current time is used instead.
9756: #
9757: # For a given well defined symb, courside, domain, username,
9758: # and course environment, the seed is reproducible.
9759: #
9760: sub rndseed {
9761: my ($symb,$courseid,$domain,$username, $cenv)=@_;
9762: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
9763: if (!defined($symb)) {
9764: unless ($symb=$wsymb) { return time; }
9765: }
9766: if (!defined $courseid) {
9767: $courseid=$wcourseid;
9768: }
9769: if (!defined $domain) { $domain=$wdomain; }
9770: if (!defined $username) { $username=$wusername }
9771:
9772: my $which;
9773: if (defined($cenv->{'rndseed'})) {
9774: $which = $cenv->{'rndseed'};
9775: } else {
9776: $which =&get_rand_alg($courseid);
9777: }
9778: if (defined(&getCODE())) {
9779:
9780: if ($which eq '64bit5') {
9781: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9782: } elsif ($which eq '64bit4') {
9783: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9784: } else {
9785: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9786: }
9787: } elsif ($which eq '64bit5') {
9788: return &rndseed_64bit5($symb,$courseid,$domain,$username);
9789: } elsif ($which eq '64bit4') {
9790: return &rndseed_64bit4($symb,$courseid,$domain,$username);
9791: } elsif ($which eq '64bit3') {
9792: return &rndseed_64bit3($symb,$courseid,$domain,$username);
9793: } elsif ($which eq '64bit2') {
9794: return &rndseed_64bit2($symb,$courseid,$domain,$username);
9795: } elsif ($which eq '64bit') {
9796: return &rndseed_64bit($symb,$courseid,$domain,$username);
9797: }
9798: return &rndseed_32bit($symb,$courseid,$domain,$username);
9799: }
9800:
9801: sub rndseed_32bit {
9802: my ($symb,$courseid,$domain,$username)=@_;
9803: {
9804: use integer;
9805: my $symbchck=unpack("%32C*",$symb) << 27;
9806: my $symbseed=numval($symb) << 22;
9807: my $namechck=unpack("%32C*",$username) << 17;
9808: my $nameseed=numval($username) << 12;
9809: my $domainseed=unpack("%32C*",$domain) << 7;
9810: my $courseseed=unpack("%32C*",$courseid);
9811: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
9812: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9813: #&logthis("rndseed :$num:$symb");
9814: if ($_64bit) { $num=(($num<<32)>>32); }
9815: return $num;
9816: }
9817: }
9818:
9819: sub rndseed_64bit {
9820: my ($symb,$courseid,$domain,$username)=@_;
9821: {
9822: use integer;
9823: my $symbchck=unpack("%32S*",$symb) << 21;
9824: my $symbseed=numval($symb) << 10;
9825: my $namechck=unpack("%32S*",$username);
9826:
9827: my $nameseed=numval($username) << 21;
9828: my $domainseed=unpack("%32S*",$domain) << 10;
9829: my $courseseed=unpack("%32S*",$courseid);
9830:
9831: my $num1=$symbchck+$symbseed+$namechck;
9832: my $num2=$nameseed+$domainseed+$courseseed;
9833: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9834: #&logthis("rndseed :$num:$symb");
9835: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9836: return "$num1,$num2";
9837: }
9838: }
9839:
9840: sub rndseed_64bit2 {
9841: my ($symb,$courseid,$domain,$username)=@_;
9842: {
9843: use integer;
9844: # strings need to be an even # of cahracters long, it it is odd the
9845: # last characters gets thrown away
9846: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9847: my $symbseed=numval($symb) << 10;
9848: my $namechck=unpack("%32S*",$username.' ');
9849:
9850: my $nameseed=numval($username) << 21;
9851: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9852: my $courseseed=unpack("%32S*",$courseid.' ');
9853:
9854: my $num1=$symbchck+$symbseed+$namechck;
9855: my $num2=$nameseed+$domainseed+$courseseed;
9856: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9857: #&logthis("rndseed :$num:$symb");
9858: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9859: return "$num1,$num2";
9860: }
9861: }
9862:
9863: sub rndseed_64bit3 {
9864: my ($symb,$courseid,$domain,$username)=@_;
9865: {
9866: use integer;
9867: # strings need to be an even # of cahracters long, it it is odd the
9868: # last characters gets thrown away
9869: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9870: my $symbseed=numval2($symb) << 10;
9871: my $namechck=unpack("%32S*",$username.' ');
9872:
9873: my $nameseed=numval2($username) << 21;
9874: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9875: my $courseseed=unpack("%32S*",$courseid.' ');
9876:
9877: my $num1=$symbchck+$symbseed+$namechck;
9878: my $num2=$nameseed+$domainseed+$courseseed;
9879: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9880: #&logthis("rndseed :$num1:$num2:$_64bit");
9881: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9882:
9883: return "$num1:$num2";
9884: }
9885: }
9886:
9887: sub rndseed_64bit4 {
9888: my ($symb,$courseid,$domain,$username)=@_;
9889: {
9890: use integer;
9891: # strings need to be an even # of cahracters long, it it is odd the
9892: # last characters gets thrown away
9893: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9894: my $symbseed=numval3($symb) << 10;
9895: my $namechck=unpack("%32S*",$username.' ');
9896:
9897: my $nameseed=numval3($username) << 21;
9898: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9899: my $courseseed=unpack("%32S*",$courseid.' ');
9900:
9901: my $num1=$symbchck+$symbseed+$namechck;
9902: my $num2=$nameseed+$domainseed+$courseseed;
9903: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9904: #&logthis("rndseed :$num1:$num2:$_64bit");
9905: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9906:
9907: return "$num1:$num2";
9908: }
9909: }
9910:
9911: sub rndseed_64bit5 {
9912: my ($symb,$courseid,$domain,$username)=@_;
9913: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9914: return "$num1:$num2";
9915: }
9916:
9917: sub rndseed_CODE_64bit {
9918: my ($symb,$courseid,$domain,$username)=@_;
9919: {
9920: use integer;
9921: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9922: my $symbseed=numval2($symb);
9923: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9924: my $CODEseed=numval(&getCODE());
9925: my $courseseed=unpack("%32S*",$courseid.' ');
9926: my $num1=$symbseed+$CODEchck;
9927: my $num2=$CODEseed+$courseseed+$symbchck;
9928: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9929: #&logthis("rndseed :$num1:$num2:$symb");
9930: if ($_64bit) { $num1=(($num1<<32)>>32); }
9931: if ($_64bit) { $num2=(($num2<<32)>>32); }
9932: return "$num1:$num2";
9933: }
9934: }
9935:
9936: sub rndseed_CODE_64bit4 {
9937: my ($symb,$courseid,$domain,$username)=@_;
9938: {
9939: use integer;
9940: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9941: my $symbseed=numval3($symb);
9942: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9943: my $CODEseed=numval3(&getCODE());
9944: my $courseseed=unpack("%32S*",$courseid.' ');
9945: my $num1=$symbseed+$CODEchck;
9946: my $num2=$CODEseed+$courseseed+$symbchck;
9947: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9948: #&logthis("rndseed :$num1:$num2:$symb");
9949: if ($_64bit) { $num1=(($num1<<32)>>32); }
9950: if ($_64bit) { $num2=(($num2<<32)>>32); }
9951: return "$num1:$num2";
9952: }
9953: }
9954:
9955: sub rndseed_CODE_64bit5 {
9956: my ($symb,$courseid,$domain,$username)=@_;
9957: my $code = &getCODE();
9958: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9959: return "$num1:$num2";
9960: }
9961:
9962: sub setup_random_from_rndseed {
9963: my ($rndseed)=@_;
9964: if ($rndseed =~/([,:])/) {
9965: my ($num1,$num2)=split(/[,:]/,$rndseed);
9966: &Math::Random::random_set_seed(abs($num1),abs($num2));
9967: } else {
9968: &Math::Random::random_set_seed_from_phrase($rndseed);
9969: }
9970: }
9971:
9972: sub latest_receipt_algorithm_id {
9973: return 'receipt3';
9974: }
9975:
9976: sub recunique {
9977: my $fucourseid=shift;
9978: my $unique;
9979: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9980: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9981: $unique=$env{"course.$fucourseid.internal.encseed"};
9982: } else {
9983: $unique=$perlvar{'lonReceipt'};
9984: }
9985: return unpack("%32C*",$unique);
9986: }
9987:
9988: sub recprefix {
9989: my $fucourseid=shift;
9990: my $prefix;
9991: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9992: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9993: $prefix=$env{"course.$fucourseid.internal.encpref"};
9994: } else {
9995: $prefix=$perlvar{'lonHostID'};
9996: }
9997: return unpack("%32C*",$prefix);
9998: }
9999:
10000: sub ireceipt {
10001: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10002:
10003: my $return =&recprefix($fucourseid).'-';
10004:
10005: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10006: $env{'request.state'} eq 'construct') {
10007: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10008: return $return;
10009: }
10010:
10011: my $cuname=unpack("%32C*",$funame);
10012: my $cudom=unpack("%32C*",$fudom);
10013: my $cucourseid=unpack("%32C*",$fucourseid);
10014: my $cusymb=unpack("%32C*",$fusymb);
10015: my $cunique=&recunique($fucourseid);
10016: my $cpart=unpack("%32S*",$part);
10017: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10018:
10019: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10020:
10021: $return.= ($cunique%$cuname+
10022: $cunique%$cudom+
10023: $cusymb%$cuname+
10024: $cusymb%$cudom+
10025: $cucourseid%$cuname+
10026: $cucourseid%$cudom+
10027: $cpart%$cuname+
10028: $cpart%$cudom);
10029: } else {
10030: $return.= ($cunique%$cuname+
10031: $cunique%$cudom+
10032: $cusymb%$cuname+
10033: $cusymb%$cudom+
10034: $cucourseid%$cuname+
10035: $cucourseid%$cudom);
10036: }
10037: return $return;
10038: }
10039:
10040: sub receipt {
10041: my ($part)=@_;
10042: my ($symb,$courseid,$domain,$name) = &whichuser();
10043: return &ireceipt($name,$domain,$courseid,$symb,$part);
10044: }
10045:
10046: sub whichuser {
10047: my ($passedsymb)=@_;
10048: my ($symb,$courseid,$domain,$name,$publicuser);
10049: if (defined($env{'form.grade_symb'})) {
10050: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10051: my $allowed=&allowed('vgr',$tmp_courseid);
10052: if (!$allowed &&
10053: exists($env{'request.course.sec'}) &&
10054: $env{'request.course.sec'} !~ /^\s*$/) {
10055: $allowed=&allowed('vgr',$tmp_courseid.
10056: '/'.$env{'request.course.sec'});
10057: }
10058: if ($allowed) {
10059: ($symb)=&get_env_multiple('form.grade_symb');
10060: $courseid=$tmp_courseid;
10061: ($domain)=&get_env_multiple('form.grade_domain');
10062: ($name)=&get_env_multiple('form.grade_username');
10063: return ($symb,$courseid,$domain,$name,$publicuser);
10064: }
10065: }
10066: if (!$passedsymb) {
10067: $symb=&symbread();
10068: } else {
10069: $symb=$passedsymb;
10070: }
10071: $courseid=$env{'request.course.id'};
10072: $domain=$env{'user.domain'};
10073: $name=$env{'user.name'};
10074: if ($name eq 'public' && $domain eq 'public') {
10075: if (!defined($env{'form.username'})) {
10076: $env{'form.username'}.=time.rand(10000000);
10077: }
10078: $name.=$env{'form.username'};
10079: }
10080: return ($symb,$courseid,$domain,$name,$publicuser);
10081:
10082: }
10083:
10084: # ------------------------------------------------------------ Serves up a file
10085: # returns either the contents of the file or
10086: # -1 if the file doesn't exist
10087: #
10088: # if the target is a file that was uploaded via DOCS,
10089: # a check will be made to see if a current copy exists on the local server,
10090: # if it does this will be served, otherwise a copy will be retrieved from
10091: # the home server for the course and stored in /home/httpd/html/userfiles on
10092: # the local server.
10093:
10094: sub getfile {
10095: my ($file) = @_;
10096: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10097: &repcopy($file);
10098: return &readfile($file);
10099: }
10100:
10101: sub repcopy_userfile {
10102: my ($file)=@_;
10103: my $londocroot = $perlvar{'lonDocRoot'};
10104: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10105: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10106: my ($cdom,$cnum,$filename) =
10107: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10108: my $uri="/uploaded/$cdom/$cnum/$filename";
10109: if (-e "$file") {
10110: # we already have a local copy, check it out
10111: my @fileinfo = stat($file);
10112: my $rtncode;
10113: my $info;
10114: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10115: if ($lwpresp ne 'ok') {
10116: # there is no such file anymore, even though we had a local copy
10117: if ($rtncode eq '404') {
10118: unlink($file);
10119: }
10120: return -1;
10121: }
10122: if ($info < $fileinfo[9]) {
10123: # nice, the file we have is up-to-date, just say okay
10124: return 'ok';
10125: } else {
10126: # the file is outdated, get rid of it
10127: unlink($file);
10128: }
10129: }
10130: # one way or the other, at this point, we don't have the file
10131: # construct the correct path for the file
10132: my @parts = ($cdom,$cnum);
10133: if ($filename =~ m|^(.+)/[^/]+$|) {
10134: push @parts, split(/\//,$1);
10135: }
10136: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10137: foreach my $part (@parts) {
10138: $path .= '/'.$part;
10139: if (!-e $path) {
10140: mkdir($path,0770);
10141: }
10142: }
10143: # now the path exists for sure
10144: # get a user agent
10145: my $ua=new LWP::UserAgent;
10146: my $transferfile=$file.'.in.transfer';
10147: # FIXME: this should flock
10148: if (-e $transferfile) { return 'ok'; }
10149: my $request;
10150: $uri=~s/^\///;
10151: my $homeserver = &homeserver($cnum,$cdom);
10152: my $protocol = $protocol{$homeserver};
10153: $protocol = 'http' if ($protocol ne 'https');
10154: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10155: my $response=$ua->request($request,$transferfile);
10156: # did it work?
10157: if ($response->is_error()) {
10158: unlink($transferfile);
10159: &logthis("Userfile repcopy failed for $uri");
10160: return -1;
10161: }
10162: # worked, rename the transfer file
10163: rename($transferfile,$file);
10164: return 'ok';
10165: }
10166:
10167: sub tokenwrapper {
10168: my $uri=shift;
10169: $uri=~s|^https?\://([^/]+)||;
10170: $uri=~s|^/||;
10171: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10172: my $token=$1;
10173: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10174: if ($udom && $uname && $file) {
10175: $file=~s|(\?\.*)*$||;
10176: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10177: my $homeserver = &homeserver($uname,$udom);
10178: my $protocol = $protocol{$homeserver};
10179: $protocol = 'http' if ($protocol ne 'https');
10180: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10181: (($uri=~/\?/)?'&':'?').'token='.$token.
10182: '&tokenissued='.$perlvar{'lonHostID'};
10183: } else {
10184: return '/adm/notfound.html';
10185: }
10186: }
10187:
10188: # call with reqtype HEAD: get last modification time
10189: # call with reqtype GET: get the file contents
10190: # Do not call this with reqtype GET for large files! It loads everything into memory
10191: #
10192: sub getuploaded {
10193: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10194: $uri=~s/^\///;
10195: my $homeserver = &homeserver($cnum,$cdom);
10196: my $protocol = $protocol{$homeserver};
10197: $protocol = 'http' if ($protocol ne 'https');
10198: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10199: my $ua=new LWP::UserAgent;
10200: my $request=new HTTP::Request($reqtype,$uri);
10201: my $response=$ua->request($request);
10202: $$rtncode = $response->code;
10203: if (! $response->is_success()) {
10204: return 'failed';
10205: }
10206: if ($reqtype eq 'HEAD') {
10207: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10208: } elsif ($reqtype eq 'GET') {
10209: $$info = $response->content;
10210: }
10211: return 'ok';
10212: }
10213:
10214: sub readfile {
10215: my $file = shift;
10216: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10217: my $fh;
10218: open($fh,"<$file");
10219: my $a='';
10220: while (my $line = <$fh>) { $a .= $line; }
10221: return $a;
10222: }
10223:
10224: sub filelocation {
10225: my ($dir,$file) = @_;
10226: my $location;
10227: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10228:
10229: if ($file =~ m-^/adm/-) {
10230: $file=~s-^/adm/wrapper/-/-;
10231: $file=~s-^/adm/coursedocs/showdoc/-/-;
10232: }
10233:
10234: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10235: $location = $file;
10236: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10237: my ($udom,$uname,$filename)=
10238: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10239: my $home=&homeserver($uname,$udom);
10240: my $is_me=0;
10241: my @ids=¤t_machine_ids();
10242: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10243: if ($is_me) {
10244: $location=propath($udom,$uname).'/userfiles/'.$filename;
10245: } else {
10246: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10247: $udom.'/'.$uname.'/'.$filename;
10248: }
10249: } elsif ($file =~ m-^/adm/-) {
10250: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10251: } else {
10252: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10253: $file=~s:^/(res|priv)/:/:;
10254: my $space=$1;
10255: if ( !( $file =~ m:^/:) ) {
10256: $location = $dir. '/'.$file;
10257: } else {
10258: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10259: }
10260: }
10261: $location=~s://+:/:g; # remove duplicate /
10262: while ($location=~m{/\.\./}) {
10263: if ($location =~ m{/[^/]+/\.\./}) {
10264: $location=~ s{/[^/]+/\.\./}{/}g;
10265: } else {
10266: $location=~ s{/\.\./}{/}g;
10267: }
10268: } #remove dir/..
10269: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10270: return $location;
10271: }
10272:
10273: sub hreflocation {
10274: my ($dir,$file)=@_;
10275: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10276: $file=filelocation($dir,$file);
10277: } elsif ($file=~m-^/adm/-) {
10278: $file=~s-^/adm/wrapper/-/-;
10279: $file=~s-^/adm/coursedocs/showdoc/-/-;
10280: }
10281: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10282: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10283: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10284: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10285: {/uploaded/$1/$2/}x;
10286: }
10287: if ($file=~ m{^/userfiles/}) {
10288: $file =~ s{^/userfiles/}{/uploaded/};
10289: }
10290: return $file;
10291: }
10292:
10293:
10294:
10295:
10296:
10297: sub current_machine_domains {
10298: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10299: }
10300:
10301: sub machine_domains {
10302: my ($hostname) = @_;
10303: my @domains;
10304: my %hostname = &all_hostnames();
10305: while( my($id, $name) = each(%hostname)) {
10306: # &logthis("-$id-$name-$hostname-");
10307: if ($hostname eq $name) {
10308: push(@domains,&host_domain($id));
10309: }
10310: }
10311: return @domains;
10312: }
10313:
10314: sub current_machine_ids {
10315: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10316: }
10317:
10318: sub machine_ids {
10319: my ($hostname) = @_;
10320: $hostname ||= &hostname($perlvar{'lonHostID'});
10321: my @ids;
10322: my %name_to_host = &all_names();
10323: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10324: return @{ $name_to_host{$hostname} };
10325: }
10326: return;
10327: }
10328:
10329: sub additional_machine_domains {
10330: my @domains;
10331: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10332: while( my $line = <$fh>) {
10333: $line =~ s/\s//g;
10334: push(@domains,$line);
10335: }
10336: return @domains;
10337: }
10338:
10339: sub default_login_domain {
10340: my $domain = $perlvar{'lonDefDomain'};
10341: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10342: foreach my $posdom (¤t_machine_domains(),
10343: &additional_machine_domains()) {
10344: if (lc($posdom) eq lc($testdomain)) {
10345: $domain=$posdom;
10346: last;
10347: }
10348: }
10349: return $domain;
10350: }
10351:
10352: # ------------------------------------------------------------- Declutters URLs
10353:
10354: sub declutter {
10355: my $thisfn=shift;
10356: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10357: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10358: $thisfn=~s/^\///;
10359: $thisfn=~s|^adm/wrapper/||;
10360: $thisfn=~s|^adm/coursedocs/showdoc/||;
10361: $thisfn=~s/^res\///;
10362: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10363: $thisfn=~s/\?.+$//;
10364: }
10365: return $thisfn;
10366: }
10367:
10368: # ------------------------------------------------------------- Clutter up URLs
10369:
10370: sub clutter {
10371: my $thisfn='/'.&declutter(shift);
10372: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10373: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10374: $thisfn='/res'.$thisfn;
10375: }
10376: if ($thisfn !~m|^/adm|) {
10377: if ($thisfn =~ m|^/ext/|) {
10378: $thisfn='/adm/wrapper'.$thisfn;
10379: } else {
10380: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10381: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10382: if ($embstyle eq 'ssi'
10383: || ($embstyle eq 'hdn')
10384: || ($embstyle eq 'rat')
10385: || ($embstyle eq 'prv')
10386: || ($embstyle eq 'ign')) {
10387: #do nothing with these
10388: } elsif (($embstyle eq 'img')
10389: || ($embstyle eq 'emb')
10390: || ($embstyle eq 'wrp')) {
10391: $thisfn='/adm/wrapper'.$thisfn;
10392: } elsif ($embstyle eq 'unk'
10393: && $thisfn!~/\.(sequence|page)$/) {
10394: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10395: } else {
10396: # &logthis("Got a blank emb style");
10397: }
10398: }
10399: }
10400: return $thisfn;
10401: }
10402:
10403: sub clutter_with_no_wrapper {
10404: my $uri = &clutter(shift);
10405: if ($uri =~ m-^/adm/-) {
10406: $uri =~ s-^/adm/wrapper/-/-;
10407: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10408: }
10409: return $uri;
10410: }
10411:
10412: sub freeze_escape {
10413: my ($value)=@_;
10414: if (ref($value)) {
10415: $value=&nfreeze($value);
10416: return '__FROZEN__'.&escape($value);
10417: }
10418: return &escape($value);
10419: }
10420:
10421:
10422: sub thaw_unescape {
10423: my ($value)=@_;
10424: if ($value =~ /^__FROZEN__/) {
10425: substr($value,0,10,undef);
10426: $value=&unescape($value);
10427: return &thaw($value);
10428: }
10429: return &unescape($value);
10430: }
10431:
10432: sub correct_line_ends {
10433: my ($result)=@_;
10434: $$result =~s/\r\n/\n/mg;
10435: $$result =~s/\r/\n/mg;
10436: }
10437: # ================================================================ Main Program
10438:
10439: sub goodbye {
10440: &logthis("Starting Shut down");
10441: #not converted to using infrastruture and probably shouldn't be
10442: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10443: #converted
10444: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10445: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10446: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10447: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10448: #1.1 only
10449: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10450: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10451: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10452: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10453: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10454: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10455: &logthis(sprintf("%-20s is %s",'hits',$hits));
10456: &flushcourselogs();
10457: &logthis("Shutting down");
10458: }
10459:
10460: sub get_dns {
10461: my ($url,$func,$ignore_cache) = @_;
10462: if (!$ignore_cache) {
10463: my ($content,$cached)=
10464: &Apache::lonnet::is_cached_new('dns',$url);
10465: if ($cached) {
10466: &$func($content);
10467: return;
10468: }
10469: }
10470:
10471: my %alldns;
10472: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10473: foreach my $dns (<$config>) {
10474: next if ($dns !~ /^\^(\S*)/x);
10475: my $line = $1;
10476: my ($host,$protocol) = split(/:/,$line);
10477: if ($protocol ne 'https') {
10478: $protocol = 'http';
10479: }
10480: $alldns{$host} = $protocol;
10481: }
10482: while (%alldns) {
10483: my ($dns) = keys(%alldns);
10484: my $ua=new LWP::UserAgent;
10485: $ua->timeout(30);
10486: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10487: my $response=$ua->request($request);
10488: delete($alldns{$dns});
10489: next if ($response->is_error());
10490: my @content = split("\n",$response->content);
10491: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10492: &$func(\@content);
10493: return;
10494: }
10495: close($config);
10496: my $which = (split('/',$url))[3];
10497: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10498: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10499: my @content = <$config>;
10500: &$func(\@content);
10501: return;
10502: }
10503: # ------------------------------------------------------------ Read domain file
10504: {
10505: my $loaded;
10506: my %domain;
10507:
10508: sub parse_domain_tab {
10509: my ($lines) = @_;
10510: foreach my $line (@$lines) {
10511: next if ($line =~ /^(\#|\s*$ )/x);
10512:
10513: chomp($line);
10514: my ($name,@elements) = split(/:/,$line,9);
10515: my %this_domain;
10516: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10517: 'lang_def', 'city', 'longi', 'lati',
10518: 'primary') {
10519: $this_domain{$field} = shift(@elements);
10520: }
10521: $domain{$name} = \%this_domain;
10522: }
10523: }
10524:
10525: sub reset_domain_info {
10526: undef($loaded);
10527: undef(%domain);
10528: }
10529:
10530: sub load_domain_tab {
10531: my ($ignore_cache) = @_;
10532: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10533: my $fh;
10534: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10535: my @lines = <$fh>;
10536: &parse_domain_tab(\@lines);
10537: }
10538: close($fh);
10539: $loaded = 1;
10540: }
10541:
10542: sub domain {
10543: &load_domain_tab() if (!$loaded);
10544:
10545: my ($name,$what) = @_;
10546: return if ( !exists($domain{$name}) );
10547:
10548: if (!$what) {
10549: return $domain{$name}{'description'};
10550: }
10551: return $domain{$name}{$what};
10552: }
10553:
10554: sub domain_info {
10555: &load_domain_tab() if (!$loaded);
10556: return %domain;
10557: }
10558:
10559: }
10560:
10561:
10562: # ------------------------------------------------------------- Read hosts file
10563: {
10564: my %hostname;
10565: my %hostdom;
10566: my %libserv;
10567: my $loaded;
10568: my %name_to_host;
10569: my %internetdom;
10570: my %LC_dns_serv;
10571:
10572: sub parse_hosts_tab {
10573: my ($file) = @_;
10574: foreach my $configline (@$file) {
10575: next if ($configline =~ /^(\#|\s*$ )/x);
10576: chomp($configline);
10577: if ($configline =~ /^\^/) {
10578: if ($configline =~ /^\^([\w.\-]+)/) {
10579: $LC_dns_serv{$1} = 1;
10580: }
10581: next;
10582: }
10583: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10584: $name=~s/\s//g;
10585: if ($id && $domain && $role && $name) {
10586: $hostname{$id}=$name;
10587: push(@{$name_to_host{$name}}, $id);
10588: $hostdom{$id}=$domain;
10589: if ($role eq 'library') { $libserv{$id}=$name; }
10590: if (defined($protocol)) {
10591: if ($protocol eq 'https') {
10592: $protocol{$id} = $protocol;
10593: } else {
10594: $protocol{$id} = 'http';
10595: }
10596: } else {
10597: $protocol{$id} = 'http';
10598: }
10599: if (defined($intdom)) {
10600: $internetdom{$id} = $intdom;
10601: }
10602: }
10603: }
10604: }
10605:
10606: sub reset_hosts_info {
10607: &purge_remembered();
10608: &reset_domain_info();
10609: &reset_hosts_ip_info();
10610: undef(%name_to_host);
10611: undef(%hostname);
10612: undef(%hostdom);
10613: undef(%libserv);
10614: undef($loaded);
10615: }
10616:
10617: sub load_hosts_tab {
10618: my ($ignore_cache) = @_;
10619: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10620: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10621: my @config = <$config>;
10622: &parse_hosts_tab(\@config);
10623: close($config);
10624: $loaded=1;
10625: }
10626:
10627: sub hostname {
10628: &load_hosts_tab() if (!$loaded);
10629:
10630: my ($lonid) = @_;
10631: return $hostname{$lonid};
10632: }
10633:
10634: sub all_hostnames {
10635: &load_hosts_tab() if (!$loaded);
10636:
10637: return %hostname;
10638: }
10639:
10640: sub all_names {
10641: &load_hosts_tab() if (!$loaded);
10642:
10643: return %name_to_host;
10644: }
10645:
10646: sub all_host_domain {
10647: &load_hosts_tab() if (!$loaded);
10648: return %hostdom;
10649: }
10650:
10651: sub is_library {
10652: &load_hosts_tab() if (!$loaded);
10653:
10654: return exists($libserv{$_[0]});
10655: }
10656:
10657: sub all_library {
10658: &load_hosts_tab() if (!$loaded);
10659:
10660: return %libserv;
10661: }
10662:
10663: sub unique_library {
10664: #2x reverse removes all hostnames that appear more than once
10665: my %unique = reverse &all_library();
10666: return reverse %unique;
10667: }
10668:
10669: sub get_servers {
10670: &load_hosts_tab() if (!$loaded);
10671:
10672: my ($domain,$type) = @_;
10673: my %possible_hosts = ($type eq 'library') ? %libserv
10674: : %hostname;
10675: my %result;
10676: if (ref($domain) eq 'ARRAY') {
10677: while ( my ($host,$hostname) = each(%possible_hosts)) {
10678: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10679: $result{$host} = $hostname;
10680: }
10681: }
10682: } else {
10683: while ( my ($host,$hostname) = each(%possible_hosts)) {
10684: if ($hostdom{$host} eq $domain) {
10685: $result{$host} = $hostname;
10686: }
10687: }
10688: }
10689: return %result;
10690: }
10691:
10692: sub get_unique_servers {
10693: my %unique = reverse &get_servers(@_);
10694: return reverse %unique;
10695: }
10696:
10697: sub host_domain {
10698: &load_hosts_tab() if (!$loaded);
10699:
10700: my ($lonid) = @_;
10701: return $hostdom{$lonid};
10702: }
10703:
10704: sub all_domains {
10705: &load_hosts_tab() if (!$loaded);
10706:
10707: my %seen;
10708: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10709: return @uniq;
10710: }
10711:
10712: sub internet_dom {
10713: &load_hosts_tab() if (!$loaded);
10714:
10715: my ($lonid) = @_;
10716: return $internetdom{$lonid};
10717: }
10718:
10719: sub is_LC_dns {
10720: &load_hosts_tab() if (!$loaded);
10721:
10722: my ($hostname) = @_;
10723: return exists($LC_dns_serv{$hostname});
10724: }
10725:
10726: }
10727:
10728: {
10729: my %iphost;
10730: my %name_to_ip;
10731: my %lonid_to_ip;
10732:
10733: sub get_hosts_from_ip {
10734: my ($ip) = @_;
10735: my %iphosts = &get_iphost();
10736: if (ref($iphosts{$ip})) {
10737: return @{$iphosts{$ip}};
10738: }
10739: return;
10740: }
10741:
10742: sub reset_hosts_ip_info {
10743: undef(%iphost);
10744: undef(%name_to_ip);
10745: undef(%lonid_to_ip);
10746: }
10747:
10748: sub get_host_ip {
10749: my ($lonid) = @_;
10750: if (exists($lonid_to_ip{$lonid})) {
10751: return $lonid_to_ip{$lonid};
10752: }
10753: my $name=&hostname($lonid);
10754: my $ip = gethostbyname($name);
10755: return if (!$ip || length($ip) ne 4);
10756: $ip=inet_ntoa($ip);
10757: $name_to_ip{$name} = $ip;
10758: $lonid_to_ip{$lonid} = $ip;
10759: return $ip;
10760: }
10761:
10762: sub get_iphost {
10763: my ($ignore_cache) = @_;
10764:
10765: if (!$ignore_cache) {
10766: if (%iphost) {
10767: return %iphost;
10768: }
10769: my ($ip_info,$cached)=
10770: &Apache::lonnet::is_cached_new('iphost','iphost');
10771: if ($cached) {
10772: %iphost = %{$ip_info->[0]};
10773: %name_to_ip = %{$ip_info->[1]};
10774: %lonid_to_ip = %{$ip_info->[2]};
10775: return %iphost;
10776: }
10777: }
10778:
10779: # get yesterday's info for fallback
10780: my %old_name_to_ip;
10781: my ($ip_info,$cached)=
10782: &Apache::lonnet::is_cached_new('iphost','iphost');
10783: if ($cached) {
10784: %old_name_to_ip = %{$ip_info->[1]};
10785: }
10786:
10787: my %name_to_host = &all_names();
10788: foreach my $name (keys(%name_to_host)) {
10789: my $ip;
10790: if (!exists($name_to_ip{$name})) {
10791: $ip = gethostbyname($name);
10792: if (!$ip || length($ip) ne 4) {
10793: if (defined($old_name_to_ip{$name})) {
10794: $ip = $old_name_to_ip{$name};
10795: &logthis("Can't find $name defaulting to old $ip");
10796: } else {
10797: &logthis("Name $name no IP found");
10798: next;
10799: }
10800: } else {
10801: $ip=inet_ntoa($ip);
10802: }
10803: $name_to_ip{$name} = $ip;
10804: } else {
10805: $ip = $name_to_ip{$name};
10806: }
10807: foreach my $id (@{ $name_to_host{$name} }) {
10808: $lonid_to_ip{$id} = $ip;
10809: }
10810: push(@{$iphost{$ip}},@{$name_to_host{$name}});
10811: }
10812: &Apache::lonnet::do_cache_new('iphost','iphost',
10813: [\%iphost,\%name_to_ip,\%lonid_to_ip],
10814: 48*60*60);
10815:
10816: return %iphost;
10817: }
10818:
10819: #
10820: # Given a DNS returns the loncapa host name for that DNS
10821: #
10822: sub host_from_dns {
10823: my ($dns) = @_;
10824: my @hosts;
10825: my $ip;
10826:
10827: if (exists($name_to_ip{$dns})) {
10828: $ip = $name_to_ip{$dns};
10829: }
10830: if (!$ip) {
10831: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10832: if (length($ip) == 4) {
10833: $ip = &IO::Socket::inet_ntoa($ip);
10834: }
10835: }
10836: if ($ip) {
10837: @hosts = get_hosts_from_ip($ip);
10838: return $hosts[0];
10839: }
10840: return undef;
10841: }
10842:
10843: sub get_internet_names {
10844: my ($lonid) = @_;
10845: return if ($lonid eq '');
10846: my ($idnref,$cached)=
10847: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10848: if ($cached) {
10849: return $idnref;
10850: }
10851: my $ip = &get_host_ip($lonid);
10852: my @hosts = &get_hosts_from_ip($ip);
10853: my %iphost = &get_iphost();
10854: my (@idns,%seen);
10855: foreach my $id (@hosts) {
10856: my $dom = &host_domain($id);
10857: my $prim_id = &domain($dom,'primary');
10858: my $prim_ip = &get_host_ip($prim_id);
10859: next if ($seen{$prim_ip});
10860: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10861: foreach my $id (@{$iphost{$prim_ip}}) {
10862: my $intdom = &internet_dom($id);
10863: unless (grep(/^\Q$intdom\E$/,@idns)) {
10864: push(@idns,$intdom);
10865: }
10866: }
10867: }
10868: $seen{$prim_ip} = 1;
10869: }
10870: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10871: }
10872:
10873: }
10874:
10875: sub all_loncaparevs {
10876: 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);
10877: }
10878:
10879: BEGIN {
10880:
10881: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10882: unless ($readit) {
10883: {
10884: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10885: %perlvar = (%perlvar,%{$configvars});
10886: }
10887:
10888:
10889: # ------------------------------------------------------ Read spare server file
10890: {
10891: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10892:
10893: while (my $configline=<$config>) {
10894: chomp($configline);
10895: if ($configline) {
10896: my ($host,$type) = split(':',$configline,2);
10897: if (!defined($type) || $type eq '') { $type = 'default' };
10898: push(@{ $spareid{$type} }, $host);
10899: }
10900: }
10901: close($config);
10902: }
10903: # ------------------------------------------------------------ Read permissions
10904: {
10905: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10906:
10907: while (my $configline=<$config>) {
10908: chomp($configline);
10909: if ($configline) {
10910: my ($role,$perm)=split(/ /,$configline);
10911: if ($perm ne '') { $pr{$role}=$perm; }
10912: }
10913: }
10914: close($config);
10915: }
10916:
10917: # -------------------------------------------- Read plain texts for permissions
10918: {
10919: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10920:
10921: while (my $configline=<$config>) {
10922: chomp($configline);
10923: if ($configline) {
10924: my ($short,@plain)=split(/:/,$configline);
10925: %{$prp{$short}} = ();
10926: if (@plain > 0) {
10927: $prp{$short}{'std'} = $plain[0];
10928: for (my $i=1; $i<@plain; $i++) {
10929: $prp{$short}{'alt'.$i} = $plain[$i];
10930: }
10931: }
10932: }
10933: }
10934: close($config);
10935: }
10936:
10937: # ---------------------------------------------------------- Read package table
10938: {
10939: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10940:
10941: while (my $configline=<$config>) {
10942: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10943: chomp($configline);
10944: my ($short,$plain)=split(/:/,$configline);
10945: my ($pack,$name)=split(/\&/,$short);
10946: if ($plain ne '') {
10947: $packagetab{$pack.'&'.$name.'&name'}=$name;
10948: $packagetab{$short}=$plain;
10949: }
10950: }
10951: close($config);
10952: }
10953:
10954: # ---------------------------------------------------------- Read loncaparev table
10955: {
10956: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10957: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10958: while (my $configline=<$config>) {
10959: chomp($configline);
10960: my ($hostid,$loncaparev)=split(/:/,$configline);
10961: $loncaparevs{$hostid}=$loncaparev;
10962: }
10963: close($config);
10964: }
10965: }
10966: }
10967:
10968: # ---------------------------------------------------------- Read serverhostID table
10969: {
10970: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10971: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10972: while (my $configline=<$config>) {
10973: chomp($configline);
10974: my ($name,$id)=split(/:/,$configline);
10975: $serverhomeIDs{$name}=$id;
10976: }
10977: close($config);
10978: }
10979: }
10980: }
10981:
10982: {
10983: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10984: if (-e $file) {
10985: my $parser = HTML::LCParser->new($file);
10986: while (my $token = $parser->get_token()) {
10987: if ($token->[0] eq 'S') {
10988: my $item = $token->[1];
10989: my $name = $token->[2]{'name'};
10990: my $value = $token->[2]{'value'};
10991: if ($item ne '' && $name ne '' && $value ne '') {
10992: my $release = $parser->get_text();
10993: $release =~ s/(^\s*|\s*$ )//gx;
10994: $needsrelease{$item.':'.$name.':'.$value} = $release;
10995: }
10996: }
10997: }
10998: }
10999: }
11000:
11001: # ---------------------------------------------------------- Read managers table
11002: {
11003: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11004: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11005: while (my $configline=<$config>) {
11006: chomp($configline);
11007: next if ($configline =~ /^\#/);
11008: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11009: $managerstab{$configline} = 1;
11010: }
11011: }
11012: close($config);
11013: }
11014: }
11015: }
11016:
11017: # ------------- set up temporary directory
11018: {
11019: $tmpdir = LONCAPA::tempdir();
11020:
11021: }
11022:
11023: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11024: 'compress_threshold'=> 20_000,
11025: });
11026:
11027: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11028: $dumpcount=0;
11029: $locknum=0;
11030:
11031: &logtouch();
11032: &logthis('<font color="yellow">INFO: Read configuration</font>');
11033: $readit=1;
11034: {
11035: use integer;
11036: my $test=(2**32)+1;
11037: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11038: &logthis(" Detected 64bit platform ($_64bit)");
11039: }
11040: }
11041: }
11042:
11043: 1;
11044: __END__
11045:
11046: =pod
11047:
11048: =head1 NAME
11049:
11050: Apache::lonnet - Subroutines to ask questions about things in the network.
11051:
11052: =head1 SYNOPSIS
11053:
11054: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11055:
11056: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11057:
11058: Common parameters:
11059:
11060: =over 4
11061:
11062: =item *
11063:
11064: $uname : an internal username (if $cname expecting a course Id specifically)
11065:
11066: =item *
11067:
11068: $udom : a domain (if $cdom expecting a course's domain specifically)
11069:
11070: =item *
11071:
11072: $symb : a resource instance identifier
11073:
11074: =item *
11075:
11076: $namespace : the name of a .db file that contains the data needed or
11077: being set.
11078:
11079: =back
11080:
11081: =head1 OVERVIEW
11082:
11083: lonnet provides subroutines which interact with the
11084: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11085: about classes, users, and resources.
11086:
11087: For many of these objects you can also use this to store data about
11088: them or modify them in various ways.
11089:
11090: =head2 Symbs
11091:
11092: To identify a specific instance of a resource, LON-CAPA uses symbols
11093: or "symbs"X<symb>. These identifiers are built from the URL of the
11094: map, the resource number of the resource in the map, and the URL of
11095: the resource itself. The latter is somewhat redundant, but might help
11096: if maps change.
11097:
11098: An example is
11099:
11100: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11101:
11102: The respective map entry is
11103:
11104: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11105: title="Problem 2">
11106: </resource>
11107:
11108: Symbs are used by the random number generator, as well as to store and
11109: restore data specific to a certain instance of for example a problem.
11110:
11111: =head2 Storing And Retrieving Data
11112:
11113: X<store()>X<cstore()>X<restore()>Three of the most important functions
11114: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11115: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11116: is is the non-critical message twin of cstore. These functions are for
11117: handlers to store a perl hash to a user's permanent data space in an
11118: easy manner, and to retrieve it again on another call. It is expected
11119: that a handler would use this once at the beginning to retrieve data,
11120: and then again once at the end to send only the new data back.
11121:
11122: The data is stored in the user's data directory on the user's
11123: homeserver under the ID of the course.
11124:
11125: The hash that is returned by restore will have all of the previous
11126: value for all of the elements of the hash.
11127:
11128: Example:
11129:
11130: #creating a hash
11131: my %hash;
11132: $hash{'foo'}='bar';
11133:
11134: #storing it
11135: &Apache::lonnet::cstore(\%hash);
11136:
11137: #changing a value
11138: $hash{'foo'}='notbar';
11139:
11140: #adding a new value
11141: $hash{'bar'}='foo';
11142: &Apache::lonnet::cstore(\%hash);
11143:
11144: #retrieving the hash
11145: my %history=&Apache::lonnet::restore();
11146:
11147: #print the hash
11148: foreach my $key (sort(keys(%history))) {
11149: print("\%history{$key} = $history{$key}");
11150: }
11151:
11152: Will print out:
11153:
11154: %history{1:foo} = bar
11155: %history{1:keys} = foo:timestamp
11156: %history{1:timestamp} = 990455579
11157: %history{2:bar} = foo
11158: %history{2:foo} = notbar
11159: %history{2:keys} = foo:bar:timestamp
11160: %history{2:timestamp} = 990455580
11161: %history{bar} = foo
11162: %history{foo} = notbar
11163: %history{timestamp} = 990455580
11164: %history{version} = 2
11165:
11166: Note that the special hash entries C<keys>, C<version> and
11167: C<timestamp> were added to the hash. C<version> will be equal to the
11168: total number of versions of the data that have been stored. The
11169: C<timestamp> attribute will be the UNIX time the hash was
11170: stored. C<keys> is available in every historical section to list which
11171: keys were added or changed at a specific historical revision of a
11172: hash.
11173:
11174: B<Warning>: do not store the hash that restore returns directly. This
11175: will cause a mess since it will restore the historical keys as if the
11176: were new keys. I.E. 1:foo will become 1:1:foo etc.
11177:
11178: Calling convention:
11179:
11180: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11181: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11182:
11183: For more detailed information, see lonnet specific documentation.
11184:
11185: =head1 RETURN MESSAGES
11186:
11187: =over 4
11188:
11189: =item * B<con_lost>: unable to contact remote host
11190:
11191: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11192: when the connection is brought back up
11193:
11194: =item * B<con_failed>: unable to contact remote host and unable to save message
11195: for later delivery
11196:
11197: =item * B<error:>: an error a occurred, a description of the error follows the :
11198:
11199: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11200: that was requested
11201:
11202: =back
11203:
11204: =head1 PUBLIC SUBROUTINES
11205:
11206: =head2 Session Environment Functions
11207:
11208: =over 4
11209:
11210: =item *
11211: X<appenv()>
11212: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11213: the user envirnoment file, and will be restored for each access this
11214: user makes during this session, also modifies the %env for the current
11215: process. Optional rolesarrayref - if defined contains a reference to an array
11216: of roles which are exempt from the restriction on modifying user.role entries
11217: in the user's environment.db and in %env.
11218:
11219: =item *
11220: X<delenv()>
11221: B<delenv($delthis,$regexp)>: removes all items from the session
11222: environment file that begin with $delthis. If the
11223: optional second arg - $regexp - is true, $delthis is treated as a
11224: regular expression, otherwise \Q$delthis\E is used.
11225: The values are also deleted from the current processes %env.
11226:
11227: =item * get_env_multiple($name)
11228:
11229: gets $name from the %env hash, it seemlessly handles the cases where multiple
11230: values may be defined and end up as an array ref.
11231:
11232: returns an array of values
11233:
11234: =back
11235:
11236: =head2 User Information
11237:
11238: =over 4
11239:
11240: =item *
11241: X<queryauthenticate()>
11242: B<queryauthenticate($uname,$udom)>: try to determine user's current
11243: authentication scheme
11244:
11245: =item *
11246: X<authenticate()>
11247: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11248: authenticate user from domain's lib servers (first use the current
11249: one). C<$upass> should be the users password.
11250: $checkdefauth is optional (value is 1 if a check should be made to
11251: authenticate user using default authentication method, and allow
11252: account creation if username does not have account in the domain).
11253: $clientcancheckhost is optional (value is 1 if checking whether the
11254: server can host will occur on the client side in lonauth.pm).
11255:
11256: =item *
11257: X<homeserver()>
11258: B<homeserver($uname,$udom)>: find the server which has
11259: the user's directory and files (there must be only one), this caches
11260: the answer, and also caches if there is a borken connection.
11261:
11262: =item *
11263: X<idget()>
11264: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11265: (IDs are a unique resource in a domain, there must be only 1 ID per
11266: username, and only 1 username per ID in a specific domain) (returns
11267: hash: id=>name,id=>name)
11268:
11269: =item *
11270: X<idrget()>
11271: B<idrget($udom,@unames)>: find the IDs behind a list of
11272: usernames (returns hash: name=>id,name=>id)
11273:
11274: =item *
11275: X<idput()>
11276: B<idput($udom,%ids)>: store away a list of names and associated IDs
11277:
11278: =item *
11279: X<rolesinit()>
11280: B<rolesinit($udom,$username,$authhost)>: get user privileges
11281:
11282: =item *
11283: X<getsection()>
11284: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11285: course $cname, return section name/number or '' for "not in course"
11286: and '-1' for "no section"
11287:
11288: =item *
11289: X<userenvironment()>
11290: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11291: passed in @what from the requested user's environment, returns a hash
11292:
11293: =item *
11294: X<userlog_query()>
11295: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11296: activity.log file. %filters defines filters applied when parsing the
11297: log file. These can be start or end timestamps, or the type of action
11298: - log to look for Login or Logout events, check for Checkin or
11299: Checkout, role for role selection. The response is in the form
11300: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11301: escaped strings of the action recorded in the activity.log file.
11302:
11303: =back
11304:
11305: =head2 User Roles
11306:
11307: =over 4
11308:
11309: =item *
11310:
11311: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11312: F: full access
11313: U,I,K: authentication modes (cxx only)
11314: '': forbidden
11315: 1: user needs to choose course
11316: 2: browse allowed
11317: A: passphrase authentication needed
11318:
11319: =item *
11320:
11321: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11322: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11323: and course level
11324:
11325: =item *
11326:
11327: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11328: (rolesplain.tab); plain text explanation of a user role term.
11329: $type is Course (default) or Community.
11330: If $forcedefault evaluates to true, text returned will be default
11331: text for $type. Otherwise, if this is a course, the text returned
11332: will be a custom name for the role (if defined in the course's
11333: environment). If no custom name is defined the default is returned.
11334:
11335: =item *
11336:
11337: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11338: All arguments are optional. Returns a hash of a roles, either for
11339: co-author/assistant author roles for a user's Construction Space
11340: (default), or if $context is 'userroles', roles for the user himself,
11341: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11342: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11343: For each key, value is set to colon-separated start and end times for
11344: the role. If no username and domain are specified, will default to
11345: current user/domain. Types, roles, and roledoms are references to arrays
11346: of role statuses (active, future or previous), roles
11347: (e.g., cc,in, st etc.) and domains of the roles which can be used
11348: to restrict the list of roles reported. If no array ref is
11349: provided for types, will default to return only active roles.
11350:
11351: =back
11352:
11353: =head2 User Modification
11354:
11355: =over 4
11356:
11357: =item *
11358:
11359: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11360: user for the level given by URL. Optional start and end dates (leave empty
11361: string or zero for "no date")
11362:
11363: =item *
11364:
11365: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11366: change a users, password, possible return values are: ok,
11367: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11368: refused
11369:
11370: =item *
11371:
11372: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11373:
11374: =item *
11375:
11376: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11377: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11378:
11379: will update user information (firstname,middlename,lastname,generation,
11380: permanentemail), and if forceid is true, student/employee ID also.
11381: A user's institutional affiliation(s) can also be updated.
11382: User information fields will not be overwritten with empty entries
11383: unless the field is included in the $candelete array reference.
11384: This array is included when a single user is modified via "Manage Users",
11385: or when Autoupdate.pl is run by cron in a domain.
11386:
11387: =item *
11388:
11389: modifystudent
11390:
11391: modify a student's enrollment and identification information.
11392: The course id is resolved based on the current users environment.
11393: This means the envoking user must be a course coordinator or otherwise
11394: associated with a course.
11395:
11396: This call is essentially a wrapper for lonnet::modifyuser and
11397: lonnet::modify_student_enrollment
11398:
11399: Inputs:
11400:
11401: =over 4
11402:
11403: =item B<$udom> Student's loncapa domain
11404:
11405: =item B<$uname> Student's loncapa login name
11406:
11407: =item B<$uid> Student/Employee ID
11408:
11409: =item B<$umode> Student's authentication mode
11410:
11411: =item B<$upass> Student's password
11412:
11413: =item B<$first> Student's first name
11414:
11415: =item B<$middle> Student's middle name
11416:
11417: =item B<$last> Student's last name
11418:
11419: =item B<$gene> Student's generation
11420:
11421: =item B<$usec> Student's section in course
11422:
11423: =item B<$end> Unix time of the roles expiration
11424:
11425: =item B<$start> Unix time of the roles start date
11426:
11427: =item B<$forceid> If defined, allow $uid to be changed
11428:
11429: =item B<$desiredhome> server to use as home server for student
11430:
11431: =item B<$email> Student's permanent e-mail address
11432:
11433: =item B<$type> Type of enrollment (auto or manual)
11434:
11435: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11436:
11437: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11438:
11439: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11440:
11441: =item B<$context> role change context (shown in User Management Logs display in a course)
11442:
11443: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11444:
11445: =back
11446:
11447: =item *
11448:
11449: modify_student_enrollment
11450:
11451: Change a students enrollment status in a class. The environment variable
11452: 'role.request.course' must be defined for this function to proceed.
11453:
11454: Inputs:
11455:
11456: =over 4
11457:
11458: =item $udom, students domain
11459:
11460: =item $uname, students name
11461:
11462: =item $uid, students user id
11463:
11464: =item $first, students first name
11465:
11466: =item $middle
11467:
11468: =item $last
11469:
11470: =item $gene
11471:
11472: =item $usec
11473:
11474: =item $end
11475:
11476: =item $start
11477:
11478: =item $type
11479:
11480: =item $locktype
11481:
11482: =item $cid
11483:
11484: =item $selfenroll
11485:
11486: =item $context
11487:
11488: =back
11489:
11490:
11491: =item *
11492:
11493: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11494: custom role; give a custom role to a user for the level given by URL. Specify
11495: name and domain of role author, and role name
11496:
11497: =item *
11498:
11499: revokerole($udom,$uname,$url,$role) : revoke a role for url
11500:
11501: =item *
11502:
11503: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11504:
11505: =back
11506:
11507: =head2 Course Infomation
11508:
11509: =over 4
11510:
11511: =item *
11512:
11513: coursedescription($courseid,$options) : returns a hash of information about the
11514: specified course id, including all environment settings for the
11515: course, the description of the course will be in the hash under the
11516: key 'description'
11517:
11518: $options is an optional parameter that if supplied is a hash reference that controls
11519: what how this function works. It has the following key/values:
11520:
11521: =over 4
11522:
11523: =item freshen_cache
11524:
11525: If defined, and the environment cache for the course is valid, it is
11526: returned in the returned hash.
11527:
11528: =item one_time
11529:
11530: If defined, the last cache time is set to _now_
11531:
11532: =item user
11533:
11534: If defined, the supplied username is used instead of the current user.
11535:
11536:
11537: =back
11538:
11539: =item *
11540:
11541: resdata($name,$domain,$type,@which) : request for current parameter
11542: setting for a specific $type, where $type is either 'course' or 'user',
11543: @what should be a list of parameters to ask about. This routine caches
11544: answers for 5 minutes.
11545:
11546: =item *
11547:
11548: get_courseresdata($courseid, $domain) : dump the entire course resource
11549: data base, returning a hash that is keyed by the resource name and has
11550: values that are the resource value. I believe that the timestamps and
11551: versions are also returned.
11552:
11553:
11554: =back
11555:
11556: =head2 Course Modification
11557:
11558: =over 4
11559:
11560: =item *
11561:
11562: writecoursepref($courseid,%prefs) : write preferences (environment
11563: database) for a course
11564:
11565: =item *
11566:
11567: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11568:
11569: =item *
11570:
11571: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11572:
11573: =back
11574:
11575: =head2 Resource Subroutines
11576:
11577: =over 4
11578:
11579: =item *
11580:
11581: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11582:
11583: =item *
11584:
11585: repcopy($filename) : subscribes to the requested file, and attempts to
11586: replicate from the owning library server, Might return
11587: 'unavailable', 'not_found', 'forbidden', 'ok', or
11588: 'bad_request', also attempts to grab the metadata for the
11589: resource. Expects the local filesystem pathname
11590: (/home/httpd/html/res/....)
11591:
11592: =back
11593:
11594: =head2 Resource Information
11595:
11596: =over 4
11597:
11598: =item *
11599:
11600: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11601: a vairety of different possible values, $varname should be a request
11602: string, and the other parameters can be used to specify who and what
11603: one is asking about.
11604:
11605: Possible values for $varname are environment.lastname (or other item
11606: from the envirnment hash), user.name (or someother aspect about the
11607: user), resource.0.maxtries (or some other part and parameter of a
11608: resource)
11609:
11610: =item *
11611:
11612: directcondval($number) : get current value of a condition; reads from a state
11613: string
11614:
11615: =item *
11616:
11617: condval($condidx) : value of condition index based on state
11618:
11619: =item *
11620:
11621: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11622: resource's metadata, $what should be either a specific key, or either
11623: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11624: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11625:
11626: this function automatically caches all requests
11627:
11628: =item *
11629:
11630: metadata_query($query,$custom,$customshow) : make a metadata query against the
11631: network of library servers; returns file handle of where SQL and regex results
11632: will be stored for query
11633:
11634: =item *
11635:
11636: symbread($filename) : return symbolic list entry (filename argument optional);
11637: returns the data handle
11638:
11639: =item *
11640:
11641: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11642: a possible symb for the URL in $thisfn, and if is an encryypted
11643: resource that the user accessed using /enc/ returns a 1 on success, 0
11644: on failure, user must be in a course, as it assumes the existance of
11645: the course initial hash, and uses $env('request.course.id'}
11646:
11647:
11648: =item *
11649:
11650: symbclean($symb) : removes versions numbers from a symb, returns the
11651: cleaned symb
11652:
11653: =item *
11654:
11655: is_on_map($uri) : checks if the $uri is somewhere on the current
11656: course map, user must be in a course for it to work.
11657:
11658: =item *
11659:
11660: numval($salt) : return random seed value (addend for rndseed)
11661:
11662: =item *
11663:
11664: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11665: a random seed, all arguments are optional, if they aren't sent it uses the
11666: environment to derive them. Note: if symb isn't sent and it can't get one
11667: from &symbread it will use the current time as its return value
11668:
11669: =item *
11670:
11671: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11672: unfakeable, receipt
11673:
11674: =item *
11675:
11676: receipt() : API to ireceipt working off of env values; given out to users
11677:
11678: =item *
11679:
11680: countacc($url) : count the number of accesses to a given URL
11681:
11682: =item *
11683:
11684: 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
11685:
11686: =item *
11687:
11688: 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)
11689:
11690: =item *
11691:
11692: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11693:
11694: =item *
11695:
11696: devalidate($symb) : devalidate temporary spreadsheet calculations,
11697: forcing spreadsheet to reevaluate the resource scores next time.
11698:
11699: =back
11700:
11701: =head2 Storing/Retreiving Data
11702:
11703: =over 4
11704:
11705: =item *
11706:
11707: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11708: for this url; hashref needs to be given and should be a \%hashname; the
11709: remaining args aren't required and if they aren't passed or are '' they will
11710: be derived from the env
11711:
11712: =item *
11713:
11714: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11715: uses critical subroutine
11716:
11717: =item *
11718:
11719: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11720: all args are optional
11721:
11722: =item *
11723:
11724: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11725: dumps the complete (or key matching regexp) namespace into a hash
11726: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11727: normally &store()ed into
11728:
11729: $range should be either an integer '100' (give me the first 100
11730: matching records)
11731: or be two integers sperated by a - with no spaces
11732: '30-50' (give me the 30th through the 50th matching
11733: records)
11734:
11735:
11736: =item *
11737:
11738: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11739: replaces a &store() version of data with a replacement set of data
11740: for a particular resource in a namespace passed in the $storehash hash
11741: reference
11742:
11743: =item *
11744:
11745: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11746: works very similar to store/cstore, but all data is stored in a
11747: temporary location and can be reset using tmpreset, $storehash should
11748: be a hash reference, returns nothing on success
11749:
11750: =item *
11751:
11752: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11753: similar to restore, but all data is stored in a temporary location and
11754: can be reset using tmpreset. Returns a hash of values on success,
11755: error string otherwise.
11756:
11757: =item *
11758:
11759: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11760: deltes all keys for $symb form the temporary storage hash.
11761:
11762: =item *
11763:
11764: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11765: reference filled in from namesp ($udom and $uname are optional)
11766:
11767: =item *
11768:
11769: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11770: namesp ($udom and $uname are optional)
11771:
11772: =item *
11773:
11774: dump($namespace,$udom,$uname,$regexp,$range) :
11775: dumps the complete (or key matching regexp) namespace into a hash
11776: ($udom, $uname, $regexp, $range are optional)
11777:
11778: $range should be either an integer '100' (give me the first 100
11779: matching records)
11780: or be two integers sperated by a - with no spaces
11781: '30-50' (give me the 30th through the 50th matching
11782: records)
11783: =item *
11784:
11785: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11786: $store can be a scalar, an array reference, or if the amount to be
11787: incremented is > 1, a hash reference.
11788:
11789: ($udom and $uname are optional)
11790:
11791: =item *
11792:
11793: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11794: ($udom and $uname are optional)
11795:
11796: =item *
11797:
11798: cput($namespace,$storehash,$udom,$uname) : critical put
11799: ($udom and $uname are optional)
11800:
11801: =item *
11802:
11803: newput($namespace,$storehash,$udom,$uname) :
11804:
11805: Attempts to store the items in the $storehash, but only if they don't
11806: currently exist, if this succeeds you can be certain that you have
11807: successfully created a new key value pair in the $namespace db.
11808:
11809:
11810: Args:
11811: $namespace: name of database to store values to
11812: $storehash: hashref to store to the db
11813: $udom: (optional) domain of user containing the db
11814: $uname: (optional) name of user caontaining the db
11815:
11816: Returns:
11817: 'ok' -> succeeded in storing all keys of $storehash
11818: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11819: least <key> already existed in the db (other
11820: requested keys may also already exist)
11821: 'error: <msg>' -> unable to tie the DB or other error occurred
11822: 'con_lost' -> unable to contact request server
11823: 'refused' -> action was not allowed by remote machine
11824:
11825:
11826: =item *
11827:
11828: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11829: reference filled in from namesp (encrypts the return communication)
11830: ($udom and $uname are optional)
11831:
11832: =item *
11833:
11834: log($udom,$name,$home,$message) : write to permanent log for user; use
11835: critical subroutine
11836:
11837: =item *
11838:
11839: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11840: array reference filled in from namespace found in domain level on either
11841: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11842:
11843: =item *
11844:
11845: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11846: domain level either on specified domain server ($uhome) or primary domain
11847: server ($udom and $uhome are optional)
11848:
11849: =item *
11850:
11851: get_domain_defaults($target_domain) : returns hash with defaults for
11852: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11853: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11854: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11855: Values are retrieved from cache (if current), or from domain's configuration.db
11856: (if available), or lastly from values in lonTabs/dns_domain,tab,
11857: or lonTabs/domain.tab.
11858:
11859: %domdefaults = &get_auth_defaults($target_domain);
11860:
11861: =back
11862:
11863: =head2 Network Status Functions
11864:
11865: =over 4
11866:
11867: =item *
11868:
11869: dirlist() : return directory list based on URI (first arg).
11870:
11871: Inputs: 1 required, 5 optional.
11872:
11873: =over
11874:
11875: =item
11876: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11877:
11878: =item
11879: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
11880:
11881: =item
11882: $username - username of user/course to be listed. Extracted from $uri if absent.
11883:
11884: =item
11885: $getpropath - boolean: 1 if prepend path using &propath().
11886:
11887: =item
11888: $getuserdir - boolean: 1 if prepend path for "userfiles".
11889:
11890: =item
11891: $alternateRoot - path to prepend in place of path from $uri.
11892:
11893: =back
11894:
11895: Returns: Array of up to two items.
11896:
11897: =over
11898:
11899: a reference to an array of files/subdirectories
11900:
11901: =over
11902:
11903: Each element in the array of files/subdirectories is a & separated list of
11904: item name and the result of running stat on the item. If dirlist was requested
11905: for a file instead of a directory, the item name will be ''. For a directory
11906: listing, if the item is a metadata file, the element will end &N&M
11907: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11908: default copyright set (1).
11909:
11910: =back
11911:
11912: a scalar containing error condition (if encountered).
11913:
11914: =over
11915:
11916: =item
11917: no_host (no homeserver identified for $username:$domain).
11918:
11919: =item
11920: no_such_host (server contacted for listing not identified as valid host).
11921:
11922: =item
11923: con_lost (connection to remote server failed).
11924:
11925: =item
11926: refused (invalid $username:$domain received on lond side).
11927:
11928: =item
11929: no_such_dir (directory at specified path on lond side does not exist).
11930:
11931: =item
11932: empty (directory at specified path on lond side is empty).
11933:
11934: =over
11935:
11936: This is currently not encountered because the &ls3, &ls2,
11937: &ls (_handler) routines on the lond side do not filter out
11938: . and .. from a directory listing.
11939:
11940: =back
11941:
11942: =back
11943:
11944: =back
11945:
11946: =item *
11947:
11948: spareserver() : find server with least workload from spare.tab
11949:
11950:
11951: =item *
11952:
11953: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11954: if there is no corresponding loncapa host.
11955:
11956: =back
11957:
11958:
11959: =head2 Apache Request
11960:
11961: =over 4
11962:
11963: =item *
11964:
11965: ssi($url,%hash) : server side include, does a complete request cycle on url to
11966: localhost, posts hash
11967:
11968: =back
11969:
11970: =head2 Data to String to Data
11971:
11972: =over 4
11973:
11974: =item *
11975:
11976: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11977: and '&' separators, supports elements that are arrayrefs and hashrefs
11978:
11979: =item *
11980:
11981: hashref2str($hashref) : convert a hashref into a string complete with
11982: escaping and '=' and '&' separators, supports elements that are
11983: arrayrefs and hashrefs
11984:
11985: =item *
11986:
11987: arrayref2str($arrayref) : convert an arrayref into a string complete
11988: with escaping and '&' separators, supports elements that are arrayrefs
11989: and hashrefs
11990:
11991: =item *
11992:
11993: str2hash($string) : convert string to hash using unescaping and
11994: splitting on '=' and '&', supports elements that are arrayrefs and
11995: hashrefs
11996:
11997: =item *
11998:
11999: str2array($string) : convert string to hash using unescaping and
12000: splitting on '&', supports elements that are arrayrefs and hashrefs
12001:
12002: =back
12003:
12004: =head2 Logging Routines
12005:
12006:
12007: These routines allow one to make log messages in the lonnet.log and
12008: lonnet.perm logfiles.
12009:
12010: =over 4
12011:
12012: =item *
12013:
12014: logtouch() : make sure the logfile, lonnet.log, exists
12015:
12016: =item *
12017:
12018: logthis() : append message to the normal lonnet.log file, it gets
12019: preiodically rolled over and deleted.
12020:
12021: =item *
12022:
12023: logperm() : append a permanent message to lonnet.perm.log, this log
12024: file never gets deleted by any automated portion of the system, only
12025: messages of critical importance should go in here.
12026:
12027:
12028: =back
12029:
12030: =head2 General File Helper Routines
12031:
12032: =over 4
12033:
12034: =item *
12035:
12036: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12037: (a) files in /uploaded
12038: (i) If a local copy of the file exists -
12039: compares modification date of local copy with last-modified date for
12040: definitive version stored on home server for course. If local copy is
12041: stale, requests a new version from the home server and stores it.
12042: If the original has been removed from the home server, then local copy
12043: is unlinked.
12044: (ii) If local copy does not exist -
12045: requests the file from the home server and stores it.
12046:
12047: If $caller is 'uploadrep':
12048: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12049: for request for files originally uploaded via DOCS.
12050: - returns 'ok' if fresh local copy now available, -1 otherwise.
12051:
12052: Otherwise:
12053: This indicates a call from the content generation phase of the request.
12054: - returns the entire contents of the file or -1.
12055:
12056: (b) files in /res
12057: - returns the entire contents of a file or -1;
12058: it properly subscribes to and replicates the file if neccessary.
12059:
12060:
12061: =item *
12062:
12063: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12064: reference
12065:
12066: returns either a stat() list of data about the file or an empty list
12067: if the file doesn't exist or couldn't find out about it (connection
12068: problems or user unknown)
12069:
12070: =item *
12071:
12072: filelocation($dir,$file) : returns file system location of a file
12073: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12074: directory that relative $file lookups are to looked in ($dir of /a/dir
12075: and a file of ../bob will become /a/bob)
12076:
12077: =item *
12078:
12079: hreflocation($dir,$file) : returns file system location or a URL; same as
12080: filelocation except for hrefs
12081:
12082: =item *
12083:
12084: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12085:
12086: =back
12087:
12088: =head2 Usererfile file routines (/uploaded*)
12089:
12090: =over 4
12091:
12092: =item *
12093:
12094: userfileupload(): main rotine for putting a file in a user or course's
12095: filespace, arguments are,
12096:
12097: formname - required - this is the name of the element in $env where the
12098: filename, and the contents of the file to create/modifed exist
12099: the filename is in $env{'form.'.$formname.'.filename'} and the
12100: contents of the file is located in $env{'form.'.$formname}
12101: context - if coursedoc, store the file in the course of the active role
12102: of the current user;
12103: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12104: if 'canceloverwrite': delete file in tmp/overwrites directory
12105: subdir - required - subdirectory to put the file in under ../userfiles/
12106: if undefined, it will be placed in "unknown"
12107:
12108: (This routine calls clean_filename() to remove any dangerous
12109: characters from the filename, and then calls finuserfileupload() to
12110: complete the transaction)
12111:
12112: returns either the url of the uploaded file (/uploaded/....) if successful
12113: and /adm/notfound.html if unsuccessful
12114:
12115: =item *
12116:
12117: clean_filename(): routine for cleaing a filename up for storage in
12118: userfile space, argument is:
12119:
12120: filename - proposed filename
12121:
12122: returns: the new clean filename
12123:
12124: =item *
12125:
12126: finishuserfileupload(): routine that creates and sends the file to
12127: userspace, probably shouldn't be called directly
12128:
12129: docuname: username or courseid of destination for the file
12130: docudom: domain of user/course of destination for the file
12131: formname: same as for userfileupload()
12132: fname: filename (including subdirectories) for the file
12133: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12134: allfiles: reference to hash used to store objects found by parser
12135: codebase: reference to hash used for codebases of java objects found by parser
12136: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12137: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12138: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12139: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12140: context: if 'overwrite', will move the uploaded file from its temporary location to
12141: userfiles to facilitate overwriting a previously uploaded file with same name.
12142: mimetype: reference to scalar to accommodate mime type determined
12143: from File::MMagic if $parser = parse.
12144:
12145: returns either the url of the uploaded file (/uploaded/....) if successful
12146: and /adm/notfound.html if unsuccessful (or an error message if context
12147: was 'overwrite').
12148:
12149:
12150: =item *
12151:
12152: renameuserfile(): renames an existing userfile to a new name
12153:
12154: Args:
12155: docuname: username or courseid of destination for the file
12156: docudom: domain of user/course of destination for the file
12157: old: current file name (including any subdirs under userfiles)
12158: new: desired file name (including any subdirs under userfiles)
12159:
12160: =item *
12161:
12162: mkdiruserfile(): creates a directory is a userfiles dir
12163:
12164: Args:
12165: docuname: username or courseid of destination for the file
12166: docudom: domain of user/course of destination for the file
12167: dir: dir to create (including any subdirs under userfiles)
12168:
12169: =item *
12170:
12171: removeuserfile(): removes a file that exists in userfiles
12172:
12173: Args:
12174: docuname: username or courseid of destination for the file
12175: docudom: domain of user/course of destination for the file
12176: fname: filname to delete (including any subdirs under userfiles)
12177:
12178: =item *
12179:
12180: removeuploadedurl(): convience function for removeuserfile()
12181:
12182: Args:
12183: url: a full /uploaded/... url to delete
12184:
12185: =item *
12186:
12187: get_portfile_permissions():
12188: Args:
12189: domain: domain of user or course contain the portfolio files
12190: user: name of user or num of course contain the portfolio files
12191: Returns:
12192: hashref of a dump of the proper file_permissions.db
12193:
12194:
12195: =item *
12196:
12197: get_access_controls():
12198:
12199: Args:
12200: current_permissions: the hash ref returned from get_portfile_permissions()
12201: group: (optional) the group you want the files associated with
12202: file: (optional) the file you want access info on
12203:
12204: Returns:
12205: a hash (keys are file names) of hashes containing
12206: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12207: values are XML containing access control settings (see below)
12208:
12209: Internal notes:
12210:
12211: access controls are stored in file_permissions.db as key=value pairs.
12212: key -> path to file/file_name\0uniqueID:scope_end_start
12213: where scope -> public,guest,course,group,domains or users.
12214: end -> UNIX time for end of access (0 -> no end date)
12215: start -> UNIX time for start of access
12216:
12217: value -> XML description of access control
12218: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12219: <start></start>
12220: <end></end>
12221:
12222: <password></password> for scope type = guest
12223:
12224: <domain></domain> for scope type = course or group
12225: <number></number>
12226: <roles id="">
12227: <role></role>
12228: <access></access>
12229: <section></section>
12230: <group></group>
12231: </roles>
12232:
12233: <dom></dom> for scope type = domains
12234:
12235: <users> for scope type = users
12236: <user>
12237: <uname></uname>
12238: <udom></udom>
12239: </user>
12240: </users>
12241: </scope>
12242:
12243: Access data is also aggregated for each file in an additional key=value pair:
12244: key -> path to file/file_name\0accesscontrol
12245: value -> reference to hash
12246: hash contains key = value pairs
12247: where key = uniqueID:scope_end_start
12248: value = UNIX time record was last updated
12249:
12250: Used to improve speed of look-ups of access controls for each file.
12251:
12252: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12253:
12254: modify_access_controls():
12255:
12256: Modifies access controls for a portfolio file
12257: Args
12258: 1. file name
12259: 2. reference to hash of required changes,
12260: 3. domain
12261: 4. username
12262: where domain,username are the domain of the portfolio owner
12263: (either a user or a course)
12264:
12265: Returns:
12266: 1. result of additions or updates ('ok' or 'error', with error message).
12267: 2. result of deletions ('ok' or 'error', with error message).
12268: 3. reference to hash of any new or updated access controls.
12269: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12270: key = integer (inbound ID)
12271: value = uniqueID
12272:
12273: =back
12274:
12275: =head2 HTTP Helper Routines
12276:
12277: =over 4
12278:
12279: =item *
12280:
12281: escape() : unpack non-word characters into CGI-compatible hex codes
12282:
12283: =item *
12284:
12285: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12286:
12287: =back
12288:
12289: =head1 PRIVATE SUBROUTINES
12290:
12291: =head2 Underlying communication routines (Shouldn't call)
12292:
12293: =over 4
12294:
12295: =item *
12296:
12297: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12298:
12299: =item *
12300:
12301: reply() : uses subreply to send a message to remote machine, logs all failures
12302:
12303: =item *
12304:
12305: critical() : passes a critical message to another server; if cannot
12306: get through then place message in connection buffer directory and
12307: returns con_delayed, if incapable of saving message, returns
12308: con_failed
12309:
12310: =item *
12311:
12312: reconlonc() : tries to reconnect lonc client processes.
12313:
12314: =back
12315:
12316: =head2 Resource Access Logging
12317:
12318: =over 4
12319:
12320: =item *
12321:
12322: flushcourselogs() : flush (save) buffer logs and access logs
12323:
12324: =item *
12325:
12326: courselog($what) : save message for course in hash
12327:
12328: =item *
12329:
12330: courseacclog($what) : save message for course using &courselog(). Perform
12331: special processing for specific resource types (problems, exams, quizzes, etc).
12332:
12333: =item *
12334:
12335: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12336: as a PerlChildExitHandler
12337:
12338: =back
12339:
12340: =head2 Other
12341:
12342: =over 4
12343:
12344: =item *
12345:
12346: symblist($mapname,%newhash) : update symbolic storage links
12347:
12348: =back
12349:
12350: =cut
12351:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>