1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1144 2011/11/07 20:05:59 www 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: } else {
1924: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1925: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1926: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1927: }
1928: if (ref($domconfig{'quotas'}) eq 'HASH') {
1929: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1930: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1931: } else {
1932: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1933: }
1934: my @usertools = ('aboutme','blog','portfolio');
1935: foreach my $item (@usertools) {
1936: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1937: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1938: }
1939: }
1940: }
1941: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1942: foreach my $item ('official','unofficial','community') {
1943: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1944: }
1945: }
1946: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1947: foreach my $item ('inststatustypes','inststatusorder') {
1948: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1949: }
1950: }
1951: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1952: foreach my $item ('canuse_pdfforms') {
1953: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1954: }
1955: }
1956: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1957: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1958: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1959: }
1960: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1961: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1962: }
1963: }
1964: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1965: $cachetime);
1966: return %domdefaults;
1967: }
1968:
1969: # --------------------------------------------------- Assign a key to a student
1970:
1971: sub assign_access_key {
1972: #
1973: # a valid key looks like uname:udom#comments
1974: # comments are being appended
1975: #
1976: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1977: $kdom=
1978: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1979: $knum=
1980: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1981: $cdom=
1982: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1983: $cnum=
1984: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1985: $udom=$env{'user.name'} unless (defined($udom));
1986: $uname=$env{'user.domain'} unless (defined($uname));
1987: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1988: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1989: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1990: # assigned to this person
1991: # - this should not happen,
1992: # unless something went wrong
1993: # the first time around
1994: # ready to assign
1995: $logentry=$1.'; '.$logentry;
1996: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1997: $kdom,$knum) eq 'ok') {
1998: # key now belongs to user
1999: my $envkey='key.'.$cdom.'_'.$cnum;
2000: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2001: &appenv({'environment.'.$envkey => $ckey});
2002: return 'ok';
2003: } else {
2004: return
2005: 'error: Count not permanently assign key, will need to be re-entered later.';
2006: }
2007: } else {
2008: return 'error: Could not assign key, try again later.';
2009: }
2010: } elsif (!$existing{$ckey}) {
2011: # the key does not exist
2012: return 'error: The key does not exist';
2013: } else {
2014: # the key is somebody else's
2015: return 'error: The key is already in use';
2016: }
2017: }
2018:
2019: # ------------------------------------------ put an additional comment on a key
2020:
2021: sub comment_access_key {
2022: #
2023: # a valid key looks like uname:udom#comments
2024: # comments are being appended
2025: #
2026: my ($ckey,$cdom,$cnum,$logentry)=@_;
2027: $cdom=
2028: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2029: $cnum=
2030: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2031: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2032: if ($existing{$ckey}) {
2033: $existing{$ckey}.='; '.$logentry;
2034: # ready to assign
2035: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2036: $cdom,$cnum) eq 'ok') {
2037: return 'ok';
2038: } else {
2039: return 'error: Count not store comment.';
2040: }
2041: } else {
2042: # the key does not exist
2043: return 'error: The key does not exist';
2044: }
2045: }
2046:
2047: # ------------------------------------------------------ Generate a set of keys
2048:
2049: sub generate_access_keys {
2050: my ($number,$cdom,$cnum,$logentry)=@_;
2051: $cdom=
2052: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2053: $cnum=
2054: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2055: unless (&allowed('mky',$cdom)) { return 0; }
2056: unless (($cdom) && ($cnum)) { return 0; }
2057: if ($number>10000) { return 0; }
2058: sleep(2); # make sure don't get same seed twice
2059: srand(time()^($$+($$<<15))); # from "Programming Perl"
2060: my $total=0;
2061: for (my $i=1;$i<=$number;$i++) {
2062: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2063: sprintf("%lx",int(100000*rand)).'-'.
2064: sprintf("%lx",int(100000*rand));
2065: $newkey=~s/1/g/g; # folks mix up 1 and l
2066: $newkey=~s/0/h/g; # and also 0 and O
2067: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2068: if ($existing{$newkey}) {
2069: $i--;
2070: } else {
2071: if (&put('accesskeys',
2072: { $newkey => '# generated '.localtime().
2073: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2074: '; '.$logentry },
2075: $cdom,$cnum) eq 'ok') {
2076: $total++;
2077: }
2078: }
2079: }
2080: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2081: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2082: return $total;
2083: }
2084:
2085: # ------------------------------------------------------- Validate an accesskey
2086:
2087: sub validate_access_key {
2088: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2089: $cdom=
2090: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2091: $cnum=
2092: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2093: $udom=$env{'user.domain'} unless (defined($udom));
2094: $uname=$env{'user.name'} unless (defined($uname));
2095: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2096: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2097: }
2098:
2099: # ------------------------------------- Find the section of student in a course
2100: sub devalidate_getsection_cache {
2101: my ($udom,$unam,$courseid)=@_;
2102: my $hashid="$udom:$unam:$courseid";
2103: &devalidate_cache_new('getsection',$hashid);
2104: }
2105:
2106: sub courseid_to_courseurl {
2107: my ($courseid) = @_;
2108: #already url style courseid
2109: return $courseid if ($courseid =~ m{^/});
2110:
2111: if (exists($env{'course.'.$courseid.'.num'})) {
2112: my $cnum = $env{'course.'.$courseid.'.num'};
2113: my $cdom = $env{'course.'.$courseid.'.domain'};
2114: return "/$cdom/$cnum";
2115: }
2116:
2117: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2118: if (exists($courseinfo{'num'})) {
2119: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2120: }
2121:
2122: return undef;
2123: }
2124:
2125: sub getsection {
2126: my ($udom,$unam,$courseid)=@_;
2127: my $cachetime=1800;
2128:
2129: my $hashid="$udom:$unam:$courseid";
2130: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2131: if (defined($cached)) { return $result; }
2132:
2133: my %Pending;
2134: my %Expired;
2135: #
2136: # Each role can either have not started yet (pending), be active,
2137: # or have expired.
2138: #
2139: # If there is an active role, we are done.
2140: #
2141: # If there is more than one role which has not started yet,
2142: # choose the one which will start sooner
2143: # If there is one role which has not started yet, return it.
2144: #
2145: # If there is more than one expired role, choose the one which ended last.
2146: # If there is a role which has expired, return it.
2147: #
2148: $courseid = &courseid_to_courseurl($courseid);
2149: my $extra = &freeze_escape({'skipcheck' => 1});
2150: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
2151: foreach my $key (keys(%roleshash)) {
2152: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2153: my $section=$1;
2154: if ($key eq $courseid.'_st') { $section=''; }
2155: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2156: my $now=time;
2157: if (defined($end) && $end && ($now > $end)) {
2158: $Expired{$end}=$section;
2159: next;
2160: }
2161: if (defined($start) && $start && ($now < $start)) {
2162: $Pending{$start}=$section;
2163: next;
2164: }
2165: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2166: }
2167: #
2168: # Presumedly there will be few matching roles from the above
2169: # loop and the sorting time will be negligible.
2170: if (scalar(keys(%Pending))) {
2171: my ($time) = sort {$a <=> $b} keys(%Pending);
2172: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2173: }
2174: if (scalar(keys(%Expired))) {
2175: my @sorted = sort {$a <=> $b} keys(%Expired);
2176: my $time = pop(@sorted);
2177: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2178: }
2179: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2180: }
2181:
2182: sub save_cache {
2183: &purge_remembered();
2184: #&Apache::loncommon::validate_page();
2185: undef(%env);
2186: undef($env_loaded);
2187: }
2188:
2189: my $to_remember=-1;
2190: my %remembered;
2191: my %accessed;
2192: my $kicks=0;
2193: my $hits=0;
2194: sub make_key {
2195: my ($name,$id) = @_;
2196: if (length($id) > 65
2197: && length(&escape($id)) > 200) {
2198: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2199: }
2200: return &escape($name.':'.$id);
2201: }
2202:
2203: sub devalidate_cache_new {
2204: my ($name,$id,$debug) = @_;
2205: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2206: $id=&make_key($name,$id);
2207: $memcache->delete($id);
2208: delete($remembered{$id});
2209: delete($accessed{$id});
2210: }
2211:
2212: sub is_cached_new {
2213: my ($name,$id,$debug) = @_;
2214: $id=&make_key($name,$id);
2215: if (exists($remembered{$id})) {
2216: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2217: $accessed{$id}=[&gettimeofday()];
2218: $hits++;
2219: return ($remembered{$id},1);
2220: }
2221: my $value = $memcache->get($id);
2222: if (!(defined($value))) {
2223: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2224: return (undef,undef);
2225: }
2226: if ($value eq '__undef__') {
2227: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2228: $value=undef;
2229: }
2230: &make_room($id,$value,$debug);
2231: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2232: return ($value,1);
2233: }
2234:
2235: sub do_cache_new {
2236: my ($name,$id,$value,$time,$debug) = @_;
2237: $id=&make_key($name,$id);
2238: my $setvalue=$value;
2239: if (!defined($setvalue)) {
2240: $setvalue='__undef__';
2241: }
2242: if (!defined($time) ) {
2243: $time=600;
2244: }
2245: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2246: my $result = $memcache->set($id,$setvalue,$time);
2247: if (! $result) {
2248: &logthis("caching of id -> $id failed");
2249: $memcache->disconnect_all();
2250: }
2251: # need to make a copy of $value
2252: &make_room($id,$value,$debug);
2253: return $value;
2254: }
2255:
2256: sub make_room {
2257: my ($id,$value,$debug)=@_;
2258:
2259: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2260: : $value;
2261: if ($to_remember<0) { return; }
2262: $accessed{$id}=[&gettimeofday()];
2263: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2264: my $to_kick;
2265: my $max_time=0;
2266: foreach my $other (keys(%accessed)) {
2267: if (&tv_interval($accessed{$other}) > $max_time) {
2268: $to_kick=$other;
2269: $max_time=&tv_interval($accessed{$other});
2270: }
2271: }
2272: delete($remembered{$to_kick});
2273: delete($accessed{$to_kick});
2274: $kicks++;
2275: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2276: return;
2277: }
2278:
2279: sub purge_remembered {
2280: #&logthis("Tossing ".scalar(keys(%remembered)));
2281: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2282: undef(%remembered);
2283: undef(%accessed);
2284: }
2285: # ------------------------------------- Read an entry from a user's environment
2286:
2287: sub userenvironment {
2288: my ($udom,$unam,@what)=@_;
2289: my $items;
2290: foreach my $item (@what) {
2291: $items.=&escape($item).'&';
2292: }
2293: $items=~s/\&$//;
2294: my %returnhash=();
2295: my $uhome = &homeserver($unam,$udom);
2296: unless ($uhome eq 'no_host') {
2297: my @answer=split(/\&/,
2298: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2299: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2300: return %returnhash;
2301: }
2302: my $i;
2303: for ($i=0;$i<=$#what;$i++) {
2304: $returnhash{$what[$i]}=&unescape($answer[$i]);
2305: }
2306: }
2307: return %returnhash;
2308: }
2309:
2310: # ---------------------------------------------------------- Get a studentphoto
2311: sub studentphoto {
2312: my ($udom,$unam,$ext) = @_;
2313: my $home=&Apache::lonnet::homeserver($unam,$udom);
2314: if (defined($env{'request.course.id'})) {
2315: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2316: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2317: return(&retrievestudentphoto($udom,$unam,$ext));
2318: } else {
2319: my ($result,$perm_reqd)=
2320: &Apache::lonnet::auto_photo_permission($unam,$udom);
2321: if ($result eq 'ok') {
2322: if (!($perm_reqd eq 'yes')) {
2323: return(&retrievestudentphoto($udom,$unam,$ext));
2324: }
2325: }
2326: }
2327: }
2328: } else {
2329: my ($result,$perm_reqd) =
2330: &Apache::lonnet::auto_photo_permission($unam,$udom);
2331: if ($result eq 'ok') {
2332: if (!($perm_reqd eq 'yes')) {
2333: return(&retrievestudentphoto($udom,$unam,$ext));
2334: }
2335: }
2336: }
2337: return '/adm/lonKaputt/lonlogo_broken.gif';
2338: }
2339:
2340: sub retrievestudentphoto {
2341: my ($udom,$unam,$ext,$type) = @_;
2342: my $home=&Apache::lonnet::homeserver($unam,$udom);
2343: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2344: if ($ret eq 'ok') {
2345: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2346: if ($type eq 'thumbnail') {
2347: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2348: }
2349: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2350: return $tokenurl;
2351: } else {
2352: if ($type eq 'thumbnail') {
2353: return '/adm/lonKaputt/genericstudent_tn.gif';
2354: } else {
2355: return '/adm/lonKaputt/lonlogo_broken.gif';
2356: }
2357: }
2358: }
2359:
2360: # -------------------------------------------------------------------- New chat
2361:
2362: sub chatsend {
2363: my ($newentry,$anon,$group)=@_;
2364: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2365: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2366: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2367: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2368: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2369: &escape($newentry)).':'.$group,$chome);
2370: }
2371:
2372: # ------------------------------------------ Find current version of a resource
2373:
2374: sub getversion {
2375: my $fname=&clutter(shift);
2376: unless ($fname=~/^\/res\//) { return -1; }
2377: return ¤tversion(&filelocation('',$fname));
2378: }
2379:
2380: sub currentversion {
2381: my $fname=shift;
2382: my $author=$fname;
2383: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2384: my ($udom,$uname)=split(/\//,$author);
2385: my $home=&homeserver($uname,$udom);
2386: if ($home eq 'no_host') {
2387: return -1;
2388: }
2389: my $answer=&reply("currentversion:$fname",$home);
2390: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2391: return -1;
2392: }
2393: return $answer;
2394: }
2395:
2396: #
2397: # Return special version number of resource if set by override, empty otherwise
2398: #
2399: sub usedversion {
2400: my $fname=shift;
2401: unless ($fname) { $fname=$env{'request.uri'}; }
2402: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2403: if ($urlversion) { return $urlversion; }
2404: return '';
2405: }
2406:
2407: # ----------------------------- Subscribe to a resource, return URL if possible
2408:
2409: sub subscribe {
2410: my $fname=shift;
2411: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2412: $fname=~s/[\n\r]//g;
2413: my $author=$fname;
2414: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2415: my ($udom,$uname)=split(/\//,$author);
2416: my $home=homeserver($uname,$udom);
2417: if ($home eq 'no_host') {
2418: return 'not_found';
2419: }
2420: my $answer=reply("sub:$fname",$home);
2421: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2422: $answer.=' by '.$home;
2423: }
2424: return $answer;
2425: }
2426:
2427: # -------------------------------------------------------------- Replicate file
2428:
2429: sub repcopy {
2430: my $filename=shift;
2431: $filename=~s/\/+/\//g;
2432: my $londocroot = $perlvar{'lonDocRoot'};
2433: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2434: if ($filename=~m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
2435: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2436: $filename=~m{^/*(uploaded|editupload)/}) {
2437: return &repcopy_userfile($filename);
2438: }
2439: $filename=~s/[\n\r]//g;
2440: my $transname="$filename.in.transfer";
2441: # FIXME: this should flock
2442: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2443: my $remoteurl=subscribe($filename);
2444: if ($remoteurl =~ /^con_lost by/) {
2445: &logthis("Subscribe returned $remoteurl: $filename");
2446: return 'unavailable';
2447: } elsif ($remoteurl eq 'not_found') {
2448: #&logthis("Subscribe returned not_found: $filename");
2449: return 'not_found';
2450: } elsif ($remoteurl =~ /^rejected by/) {
2451: &logthis("Subscribe returned $remoteurl: $filename");
2452: return 'forbidden';
2453: } elsif ($remoteurl eq 'directory') {
2454: return 'ok';
2455: } else {
2456: my $author=$filename;
2457: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2458: my ($udom,$uname)=split(/\//,$author);
2459: my $home=homeserver($uname,$udom);
2460: unless ($home eq $perlvar{'lonHostID'}) {
2461: my @parts=split(/\//,$filename);
2462: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2463: if ($path ne "$londocroot/res") {
2464: &logthis("Malconfiguration for replication: $filename");
2465: return 'bad_request';
2466: }
2467: my $count;
2468: for ($count=5;$count<$#parts;$count++) {
2469: $path.="/$parts[$count]";
2470: if ((-e $path)!=1) {
2471: mkdir($path,0777);
2472: }
2473: }
2474: my $ua=new LWP::UserAgent;
2475: my $request=new HTTP::Request('GET',"$remoteurl");
2476: my $response=$ua->request($request,$transname);
2477: if ($response->is_error()) {
2478: unlink($transname);
2479: my $message=$response->status_line;
2480: &logthis("<font color=\"blue\">WARNING:"
2481: ." LWP get: $message: $filename</font>");
2482: return 'unavailable';
2483: } else {
2484: if ($remoteurl!~/\.meta$/) {
2485: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2486: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2487: if ($mresponse->is_error()) {
2488: unlink($filename.'.meta');
2489: &logthis(
2490: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2491: }
2492: }
2493: rename($transname,$filename);
2494: return 'ok';
2495: }
2496: }
2497: }
2498: }
2499:
2500: # ------------------------------------------------ Get server side include body
2501: sub ssi_body {
2502: my ($filelink,%form)=@_;
2503: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2504: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2505: }
2506: my $output='';
2507: my $response;
2508: if ($filelink=~/^https?\:/) {
2509: ($output,$response)=&externalssi($filelink);
2510: } else {
2511: $filelink .= $filelink=~/\?/ ? '&' : '?';
2512: $filelink .= 'inhibitmenu=yes';
2513: ($output,$response)=&ssi($filelink,%form);
2514: }
2515: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2516: $output=~s/^.*?\<body[^\>]*\>//si;
2517: $output=~s/\<\/body\s*\>.*?$//si;
2518: if (wantarray) {
2519: return ($output, $response);
2520: } else {
2521: return $output;
2522: }
2523: }
2524:
2525: # --------------------------------------------------------- Server Side Include
2526:
2527: sub absolute_url {
2528: my ($host_name) = @_;
2529: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2530: if ($host_name eq '') {
2531: $host_name = $ENV{'SERVER_NAME'};
2532: }
2533: return $protocol.$host_name;
2534: }
2535:
2536: #
2537: # Server side include.
2538: # Parameters:
2539: # fn Possibly encrypted resource name/id.
2540: # form Hash that describes how the rendering should be done
2541: # and other things.
2542: # Returns:
2543: # Scalar context: The content of the response.
2544: # Array context: 2 element list of the content and the full response object.
2545: #
2546: sub ssi {
2547:
2548: my ($fn,%form)=@_;
2549: my $ua=new LWP::UserAgent;
2550: my $request;
2551:
2552: $form{'no_update_last_known'}=1;
2553: &Apache::lonenc::check_encrypt(\$fn);
2554: if (%form) {
2555: $request=new HTTP::Request('POST',&absolute_url().$fn);
2556: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2557: } else {
2558: $request=new HTTP::Request('GET',&absolute_url().$fn);
2559: }
2560:
2561: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2562: my $response=$ua->request($request);
2563:
2564: if (wantarray) {
2565: return ($response->content, $response);
2566: } else {
2567: return $response->content;
2568: }
2569: }
2570:
2571: sub externalssi {
2572: my ($url)=@_;
2573: my $ua=new LWP::UserAgent;
2574: my $request=new HTTP::Request('GET',$url);
2575: my $response=$ua->request($request);
2576: if (wantarray) {
2577: return ($response->content, $response);
2578: } else {
2579: return $response->content;
2580: }
2581: }
2582:
2583: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2584:
2585: sub allowuploaded {
2586: my ($srcurl,$url)=@_;
2587: $url=&clutter(&declutter($url));
2588: my $dir=$url;
2589: $dir=~s/\/[^\/]+$//;
2590: my %httpref=();
2591: my $httpurl=&hreflocation('',$url);
2592: $httpref{'httpref.'.$httpurl}=$srcurl;
2593: &Apache::lonnet::appenv(\%httpref);
2594: }
2595:
2596: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2597: # input: action, courseID, current domain, intended
2598: # path to file, source of file, instruction to parse file for objects,
2599: # ref to hash for embedded objects,
2600: # ref to hash for codebase of java objects.
2601: # reference to scalar to accommodate mime type determined
2602: # from File::MMagic if $parser = parse.
2603: #
2604: # output: url to file (if action was uploaddoc),
2605: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2606: #
2607: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2608: # course.
2609: #
2610: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2611: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2612: # course's home server.
2613: #
2614: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2615: # be copied from $source (current location) to
2616: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2617: # and will then be copied to
2618: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2619: # course's home server.
2620: #
2621: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2622: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2623: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2624: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2625: # in course's home server.
2626: #
2627:
2628: sub process_coursefile {
2629: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2630: $mimetype)=@_;
2631: my $fetchresult;
2632: my $home=&homeserver($docuname,$docudom);
2633: if ($action eq 'propagate') {
2634: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2635: $home);
2636: } else {
2637: my $fpath = '';
2638: my $fname = $file;
2639: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2640: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2641: my $filepath = &build_filepath($fpath);
2642: if ($action eq 'copy') {
2643: if ($source eq '') {
2644: $fetchresult = 'no source file';
2645: return $fetchresult;
2646: } else {
2647: my $destination = $filepath.'/'.$fname;
2648: rename($source,$destination);
2649: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2650: $home);
2651: }
2652: } elsif ($action eq 'uploaddoc') {
2653: open(my $fh,'>'.$filepath.'/'.$fname);
2654: print $fh $env{'form.'.$source};
2655: close($fh);
2656: if ($parser eq 'parse') {
2657: my $mm = new File::MMagic;
2658: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2659: if ($type eq 'text/html') {
2660: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2661: unless ($parse_result eq 'ok') {
2662: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2663: }
2664: }
2665: if (ref($mimetype)) {
2666: $$mimetype = $type;
2667: }
2668: }
2669: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2670: $home);
2671: if ($fetchresult eq 'ok') {
2672: return '/uploaded/'.$fpath.'/'.$fname;
2673: } else {
2674: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2675: ' to host '.$home.': '.$fetchresult);
2676: return '/adm/notfound.html';
2677: }
2678: }
2679: }
2680: unless ( $fetchresult eq 'ok') {
2681: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2682: ' to host '.$home.': '.$fetchresult);
2683: }
2684: return $fetchresult;
2685: }
2686:
2687: sub build_filepath {
2688: my ($fpath) = @_;
2689: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2690: unless ($fpath eq '') {
2691: my @parts=split('/',$fpath);
2692: foreach my $part (@parts) {
2693: $filepath.= '/'.$part;
2694: if ((-e $filepath)!=1) {
2695: mkdir($filepath,0777);
2696: }
2697: }
2698: }
2699: return $filepath;
2700: }
2701:
2702: sub store_edited_file {
2703: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2704: my $file = $primary_url;
2705: $file =~ s#^/uploaded/$docudom/$docuname/##;
2706: my $fpath = '';
2707: my $fname = $file;
2708: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2709: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2710: my $filepath = &build_filepath($fpath);
2711: open(my $fh,'>'.$filepath.'/'.$fname);
2712: print $fh $content;
2713: close($fh);
2714: my $home=&homeserver($docuname,$docudom);
2715: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2716: $home);
2717: if ($$fetchresult eq 'ok') {
2718: return '/uploaded/'.$fpath.'/'.$fname;
2719: } else {
2720: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2721: ' to host '.$home.': '.$$fetchresult);
2722: return '/adm/notfound.html';
2723: }
2724: }
2725:
2726: sub clean_filename {
2727: my ($fname,$args)=@_;
2728: # Replace Windows backslashes by forward slashes
2729: $fname=~s/\\/\//g;
2730: if (!$args->{'keep_path'}) {
2731: # Get rid of everything but the actual filename
2732: $fname=~s/^.*\/([^\/]+)$/$1/;
2733: }
2734: # Replace spaces by underscores
2735: $fname=~s/\s+/\_/g;
2736: # Replace all other weird characters by nothing
2737: $fname=~s{[^/\w\.\-]}{}g;
2738: # Replace all .\d. sequences with _\d. so they no longer look like version
2739: # numbers
2740: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2741: return $fname;
2742: }
2743: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2744: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2745: # image with the same aspect ratio as the original, but with dimensions which do
2746: # not exceed $resizewidth and $resizeheight.
2747:
2748: sub resizeImage {
2749: my ($img_path,$resizewidth,$resizeheight) = @_;
2750: my $ima = Image::Magick->new;
2751: my $resized;
2752: if (-e $img_path) {
2753: $ima->Read($img_path);
2754: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2755: my $width = $ima->Get('width');
2756: my $height = $ima->Get('height');
2757: if ($width > $resizewidth) {
2758: my $factor = $width/$resizewidth;
2759: my $newheight = $height/$factor;
2760: $ima->Scale(width=>$resizewidth,height=>$newheight);
2761: $resized = 1;
2762: }
2763: }
2764: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2765: my $width = $ima->Get('width');
2766: my $height = $ima->Get('height');
2767: if ($height > $resizeheight) {
2768: my $factor = $height/$resizeheight;
2769: my $newwidth = $width/$factor;
2770: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2771: $resized = 1;
2772: }
2773: }
2774: if ($resized) {
2775: $ima->Write($img_path);
2776: }
2777: }
2778: return;
2779: }
2780:
2781: # --------------- Take an uploaded file and put it into the userfiles directory
2782: # input: $formname - the contents of the file are in $env{"form.$formname"}
2783: # the desired filename is in $env{"form.$formname.filename"}
2784: # $context - possible values: coursedoc, existingfile, overwrite,
2785: # canceloverwrite, or ''.
2786: # if 'coursedoc': upload to the current course
2787: # if 'existingfile': write file to tmp/overwrites directory
2788: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2789: # $context is passed as argument to &finishuserfileupload
2790: # $subdir - directory in userfile to store the file into
2791: # $parser - instruction to parse file for objects ($parser = parse)
2792: # $allfiles - reference to hash for embedded objects
2793: # $codebase - reference to hash for codebase of java objects
2794: # $desuname - username for permanent storage of uploaded file
2795: # $dsetudom - domain for permanaent storage of uploaded file
2796: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2797: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2798: # $resizewidth - width (pixels) to which to resize uploaded image
2799: # $resizeheight - height (pixels) to which to resize uploaded image
2800: # $mimetype - reference to scalar to accommodate mime type determined
2801: # from File::MMagic if $parser = parse.
2802: #
2803: # output: url of file in userspace, or error: <message>
2804: # or /adm/notfound.html if failure to upload occurse
2805:
2806: sub userfileupload {
2807: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2808: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2809: if (!defined($subdir)) { $subdir='unknown'; }
2810: my $fname=$env{'form.'.$formname.'.filename'};
2811: $fname=&clean_filename($fname);
2812: # See if there is anything left
2813: unless ($fname) { return 'error: no uploaded file'; }
2814: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2815: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2816: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2817: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2818: my $now = time;
2819: my $filepath;
2820: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2821: $filepath = 'tmp/helprequests/'.$now;
2822: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2823: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2824: '_'.$env{'user.domain'}.'/pending';
2825: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2826: my ($docuname,$docudom);
2827: if ($destudom) {
2828: $docudom = $destudom;
2829: } else {
2830: $docudom = $env{'user.domain'};
2831: }
2832: if ($destuname) {
2833: $docuname = $destuname;
2834: } else {
2835: $docuname = $env{'user.name'};
2836: }
2837: if (exists($env{'form.group'})) {
2838: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2839: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2840: }
2841: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2842: if ($context eq 'canceloverwrite') {
2843: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2844: if (-e $tempfile) {
2845: my @info = stat($tempfile);
2846: if ($info[9] eq $env{'form.timestamp'}) {
2847: unlink($tempfile);
2848: }
2849: }
2850: return;
2851: }
2852: }
2853: # Create the directory if not present
2854: my @parts=split(/\//,$filepath);
2855: my $fullpath = $perlvar{'lonDaemons'};
2856: for (my $i=0;$i<@parts;$i++) {
2857: $fullpath .= '/'.$parts[$i];
2858: if ((-e $fullpath)!=1) {
2859: mkdir($fullpath,0777);
2860: }
2861: }
2862: open(my $fh,'>'.$fullpath.'/'.$fname);
2863: print $fh $env{'form.'.$formname};
2864: close($fh);
2865: if ($context eq 'existingfile') {
2866: my @info = stat($fullpath.'/'.$fname);
2867: return ($fullpath.'/'.$fname,$info[9]);
2868: } else {
2869: return $fullpath.'/'.$fname;
2870: }
2871: }
2872: if ($subdir eq 'scantron') {
2873: $fname = 'scantron_orig_'.$fname;
2874: } else {
2875: $fname="$subdir/$fname";
2876: }
2877: if ($context eq 'coursedoc') {
2878: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2879: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2880: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2881: return &finishuserfileupload($docuname,$docudom,
2882: $formname,$fname,$parser,$allfiles,
2883: $codebase,$thumbwidth,$thumbheight,
2884: $resizewidth,$resizeheight,$context,$mimetype);
2885: } else {
2886: $fname=$env{'form.folder'}.'/'.$fname;
2887: return &process_coursefile('uploaddoc',$docuname,$docudom,
2888: $fname,$formname,$parser,
2889: $allfiles,$codebase,$mimetype);
2890: }
2891: } elsif (defined($destuname)) {
2892: my $docuname=$destuname;
2893: my $docudom=$destudom;
2894: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2895: $parser,$allfiles,$codebase,
2896: $thumbwidth,$thumbheight,
2897: $resizewidth,$resizeheight,$context,$mimetype);
2898: } else {
2899: my $docuname=$env{'user.name'};
2900: my $docudom=$env{'user.domain'};
2901: if (exists($env{'form.group'})) {
2902: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2903: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2904: }
2905: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2906: $parser,$allfiles,$codebase,
2907: $thumbwidth,$thumbheight,
2908: $resizewidth,$resizeheight,$context,$mimetype);
2909: }
2910: }
2911:
2912: sub finishuserfileupload {
2913: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2914: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2915: my $path=$docudom.'/'.$docuname.'/';
2916: my $filepath=$perlvar{'lonDocRoot'};
2917:
2918: my ($fnamepath,$file,$fetchthumb);
2919: $file=$fname;
2920: if ($fname=~m|/|) {
2921: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2922: $path.=$fnamepath.'/';
2923: }
2924: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2925: my $count;
2926: for ($count=4;$count<=$#parts;$count++) {
2927: $filepath.="/$parts[$count]";
2928: if ((-e $filepath)!=1) {
2929: mkdir($filepath,0777);
2930: }
2931: }
2932:
2933: # Save the file
2934: {
2935: if (!open(FH,'>'.$filepath.'/'.$file)) {
2936: &logthis('Failed to create '.$filepath.'/'.$file);
2937: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2938: return '/adm/notfound.html';
2939: }
2940: if ($context eq 'overwrite') {
2941: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2942: my $target = $filepath.'/'.$file;
2943: if (-e $source) {
2944: my @info = stat($source);
2945: if ($info[9] eq $env{'form.timestamp'}) {
2946: unless (&File::Copy::move($source,$target)) {
2947: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2948: return "Moving from $source failed";
2949: }
2950: } else {
2951: return "Temporary file: $source had unexpected date/time for last modification";
2952: }
2953: } else {
2954: return "Temporary file: $source missing";
2955: }
2956: } elsif (!print FH ($env{'form.'.$formname})) {
2957: &logthis('Failed to write to '.$filepath.'/'.$file);
2958: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2959: return '/adm/notfound.html';
2960: }
2961: close(FH);
2962: if ($resizewidth && $resizeheight) {
2963: my $mm = new File::MMagic;
2964: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2965: if ($mime_type =~ m{^image/}) {
2966: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2967: }
2968: }
2969: }
2970: if ($parser eq 'parse') {
2971: my $mm = new File::MMagic;
2972: my $type = $mm->checktype_filename($filepath.'/'.$file);
2973: if ($type eq 'text/html') {
2974: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2975: $allfiles,$codebase);
2976: unless ($parse_result eq 'ok') {
2977: &logthis('Failed to parse '.$filepath.$file.
2978: ' for embedded media: '.$parse_result);
2979: }
2980: }
2981: if (ref($mimetype)) {
2982: $$mimetype = $type;
2983: }
2984: }
2985: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2986: my $input = $filepath.'/'.$file;
2987: my $output = $filepath.'/'.'tn-'.$file;
2988: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2989: system("convert -sample $thumbsize $input $output");
2990: if (-e $filepath.'/'.'tn-'.$file) {
2991: $fetchthumb = 1;
2992: }
2993: }
2994:
2995: # Notify homeserver to grep it
2996: #
2997: my $docuhome=&homeserver($docuname,$docudom);
2998: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2999: if ($fetchresult eq 'ok') {
3000: if ($fetchthumb) {
3001: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3002: if ($thumbresult ne 'ok') {
3003: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3004: $docuhome.': '.$thumbresult);
3005: }
3006: }
3007: #
3008: # Return the URL to it
3009: return '/uploaded/'.$path.$file;
3010: } else {
3011: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3012: ': '.$fetchresult);
3013: return '/adm/notfound.html';
3014: }
3015: }
3016:
3017: sub extract_embedded_items {
3018: my ($fullpath,$allfiles,$codebase,$content) = @_;
3019: my @state = ();
3020: my %javafiles = (
3021: codebase => '',
3022: code => '',
3023: archive => ''
3024: );
3025: my %mediafiles = (
3026: src => '',
3027: movie => '',
3028: );
3029: my $p;
3030: if ($content) {
3031: $p = HTML::LCParser->new($content);
3032: } else {
3033: $p = HTML::LCParser->new($fullpath);
3034: }
3035: while (my $t=$p->get_token()) {
3036: if ($t->[0] eq 'S') {
3037: my ($tagname, $attr) = ($t->[1],$t->[2]);
3038: push(@state, $tagname);
3039: if (lc($tagname) eq 'allow') {
3040: &add_filetype($allfiles,$attr->{'src'},'src');
3041: }
3042: if (lc($tagname) eq 'img') {
3043: &add_filetype($allfiles,$attr->{'src'},'src');
3044: }
3045: if (lc($tagname) eq 'a') {
3046: &add_filetype($allfiles,$attr->{'href'},'href');
3047: }
3048: if (lc($tagname) eq 'script') {
3049: if ($attr->{'archive'} =~ /\.jar$/i) {
3050: &add_filetype($allfiles,$attr->{'archive'},'archive');
3051: } else {
3052: &add_filetype($allfiles,$attr->{'src'},'src');
3053: }
3054: }
3055: if (lc($tagname) eq 'link') {
3056: if (lc($attr->{'rel'}) eq 'stylesheet') {
3057: &add_filetype($allfiles,$attr->{'href'},'href');
3058: }
3059: }
3060: if (lc($tagname) eq 'object' ||
3061: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3062: foreach my $item (keys(%javafiles)) {
3063: $javafiles{$item} = '';
3064: }
3065: }
3066: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3067: my $name = lc($attr->{'name'});
3068: foreach my $item (keys(%javafiles)) {
3069: if ($name eq $item) {
3070: $javafiles{$item} = $attr->{'value'};
3071: last;
3072: }
3073: }
3074: foreach my $item (keys(%mediafiles)) {
3075: if ($name eq $item) {
3076: &add_filetype($allfiles, $attr->{'value'}, 'value');
3077: last;
3078: }
3079: }
3080: }
3081: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3082: foreach my $item (keys(%javafiles)) {
3083: if ($attr->{$item}) {
3084: $javafiles{$item} = $attr->{$item};
3085: last;
3086: }
3087: }
3088: foreach my $item (keys(%mediafiles)) {
3089: if ($attr->{$item}) {
3090: &add_filetype($allfiles,$attr->{$item},$item);
3091: last;
3092: }
3093: }
3094: }
3095: } elsif ($t->[0] eq 'E') {
3096: my ($tagname) = ($t->[1]);
3097: if ($javafiles{'codebase'} ne '') {
3098: $javafiles{'codebase'} .= '/';
3099: }
3100: if (lc($tagname) eq 'applet' ||
3101: lc($tagname) eq 'object' ||
3102: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3103: ) {
3104: foreach my $item (keys(%javafiles)) {
3105: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3106: my $file=$javafiles{'codebase'}.$javafiles{$item};
3107: &add_filetype($allfiles,$file,$item);
3108: }
3109: }
3110: }
3111: pop @state;
3112: }
3113: }
3114: return 'ok';
3115: }
3116:
3117: sub add_filetype {
3118: my ($allfiles,$file,$type)=@_;
3119: if (exists($allfiles->{$file})) {
3120: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3121: push(@{$allfiles->{$file}}, &escape($type));
3122: }
3123: } else {
3124: @{$allfiles->{$file}} = (&escape($type));
3125: }
3126: }
3127:
3128: sub removeuploadedurl {
3129: my ($url)=@_;
3130: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3131: return &removeuserfile($uname,$udom,$fname);
3132: }
3133:
3134: sub removeuserfile {
3135: my ($docuname,$docudom,$fname)=@_;
3136: my $home=&homeserver($docuname,$docudom);
3137: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3138: if ($result eq 'ok') {
3139: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3140: my $metafile = $fname.'.meta';
3141: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3142: my $url = "/uploaded/$docudom/$docuname/$fname";
3143: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3144: my $sqlresult =
3145: &update_portfolio_table($docuname,$docudom,$file,
3146: 'portfolio_metadata',$group,
3147: 'delete');
3148: }
3149: }
3150: return $result;
3151: }
3152:
3153: sub mkdiruserfile {
3154: my ($docuname,$docudom,$dir)=@_;
3155: my $home=&homeserver($docuname,$docudom);
3156: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3157: }
3158:
3159: sub renameuserfile {
3160: my ($docuname,$docudom,$old,$new)=@_;
3161: my $home=&homeserver($docuname,$docudom);
3162: my $result = &reply("renameuserfile:$docudom:$docuname:".
3163: &escape("$old").':'.&escape("$new"),$home);
3164: if ($result eq 'ok') {
3165: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3166: my $oldmeta = $old.'.meta';
3167: my $newmeta = $new.'.meta';
3168: my $metaresult =
3169: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3170: my $url = "/uploaded/$docudom/$docuname/$old";
3171: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3172: my $sqlresult =
3173: &update_portfolio_table($docuname,$docudom,$file,
3174: 'portfolio_metadata',$group,
3175: 'delete');
3176: }
3177: }
3178: return $result;
3179: }
3180:
3181: # ------------------------------------------------------------------------- Log
3182:
3183: sub log {
3184: my ($dom,$nam,$hom,$what)=@_;
3185: return critical("log:$dom:$nam:$what",$hom);
3186: }
3187:
3188: # ------------------------------------------------------------------ Course Log
3189: #
3190: # This routine flushes several buffers of non-mission-critical nature
3191: #
3192:
3193: sub flushcourselogs {
3194: &logthis('Flushing log buffers');
3195: #
3196: # course logs
3197: # This is a log of all transactions in a course, which can be used
3198: # for data mining purposes
3199: #
3200: # It also collects the courseid database, which lists last transaction
3201: # times and course titles for all courseids
3202: #
3203: my %courseidbuffer=();
3204: foreach my $crsid (keys(%courselogs)) {
3205: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3206: &escape($courselogs{$crsid}),
3207: $coursehombuf{$crsid}) eq 'ok') {
3208: delete $courselogs{$crsid};
3209: } else {
3210: &logthis('Failed to flush log buffer for '.$crsid);
3211: if (length($courselogs{$crsid})>40000) {
3212: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3213: " exceeded maximum size, deleting.</font>");
3214: delete $courselogs{$crsid};
3215: }
3216: }
3217: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3218: 'description' => $coursedescrbuf{$crsid},
3219: 'inst_code' => $courseinstcodebuf{$crsid},
3220: 'type' => $coursetypebuf{$crsid},
3221: 'owner' => $courseownerbuf{$crsid},
3222: };
3223: }
3224: #
3225: # Write course id database (reverse lookup) to homeserver of courses
3226: # Is used in pickcourse
3227: #
3228: foreach my $crs_home (keys(%courseidbuffer)) {
3229: my $response = &courseidput(&host_domain($crs_home),
3230: $courseidbuffer{$crs_home},
3231: $crs_home,'timeonly');
3232: }
3233: #
3234: # File accesses
3235: # Writes to the dynamic metadata of resources to get hit counts, etc.
3236: #
3237: foreach my $entry (keys(%accesshash)) {
3238: if ($entry =~ /___count$/) {
3239: my ($dom,$name);
3240: ($dom,$name,undef)=
3241: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3242: if (! defined($dom) || $dom eq '' ||
3243: ! defined($name) || $name eq '') {
3244: my $cid = $env{'request.course.id'};
3245: $dom = $env{'request.'.$cid.'.domain'};
3246: $name = $env{'request.'.$cid.'.num'};
3247: }
3248: my $value = $accesshash{$entry};
3249: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3250: my %temphash=($url => $value);
3251: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3252: if ($result eq 'ok') {
3253: delete $accesshash{$entry};
3254: } elsif ($result eq 'unknown_cmd') {
3255: # Target server has old code running on it.
3256: my %temphash=($entry => $value);
3257: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3258: delete $accesshash{$entry};
3259: }
3260: }
3261: } else {
3262: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3263: my %temphash=($entry => $accesshash{$entry});
3264: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3265: delete $accesshash{$entry};
3266: }
3267: }
3268: }
3269: #
3270: # Roles
3271: # Reverse lookup of user roles for course faculty/staff and co-authorship
3272: #
3273: foreach my $entry (keys(%userrolehash)) {
3274: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3275: split(/\:/,$entry);
3276: if (&Apache::lonnet::put('nohist_userroles',
3277: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3278: $rudom,$runame) eq 'ok') {
3279: delete $userrolehash{$entry};
3280: }
3281: }
3282: #
3283: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3284: #
3285: my %domrolebuffer = ();
3286: foreach my $entry (keys(%domainrolehash)) {
3287: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3288: if ($domrolebuffer{$rudom}) {
3289: $domrolebuffer{$rudom}.='&'.&escape($entry).
3290: '='.&escape($domainrolehash{$entry});
3291: } else {
3292: $domrolebuffer{$rudom}.=&escape($entry).
3293: '='.&escape($domainrolehash{$entry});
3294: }
3295: delete $domainrolehash{$entry};
3296: }
3297: foreach my $dom (keys(%domrolebuffer)) {
3298: my %servers = &get_servers($dom,'library');
3299: foreach my $tryserver (keys(%servers)) {
3300: unless (&reply('domroleput:'.$dom.':'.
3301: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3302: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3303: }
3304: }
3305: }
3306: $dumpcount++;
3307: }
3308:
3309: sub courselog {
3310: my $what=shift;
3311: $what=time.':'.$what;
3312: unless ($env{'request.course.id'}) { return ''; }
3313: $coursedombuf{$env{'request.course.id'}}=
3314: $env{'course.'.$env{'request.course.id'}.'.domain'};
3315: $coursenumbuf{$env{'request.course.id'}}=
3316: $env{'course.'.$env{'request.course.id'}.'.num'};
3317: $coursehombuf{$env{'request.course.id'}}=
3318: $env{'course.'.$env{'request.course.id'}.'.home'};
3319: $coursedescrbuf{$env{'request.course.id'}}=
3320: $env{'course.'.$env{'request.course.id'}.'.description'};
3321: $courseinstcodebuf{$env{'request.course.id'}}=
3322: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3323: $courseownerbuf{$env{'request.course.id'}}=
3324: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3325: $coursetypebuf{$env{'request.course.id'}}=
3326: $env{'course.'.$env{'request.course.id'}.'.type'};
3327: if (defined $courselogs{$env{'request.course.id'}}) {
3328: $courselogs{$env{'request.course.id'}}.='&'.$what;
3329: } else {
3330: $courselogs{$env{'request.course.id'}}.=$what;
3331: }
3332: if (length($courselogs{$env{'request.course.id'}})>4048) {
3333: &flushcourselogs();
3334: }
3335: }
3336:
3337: sub courseacclog {
3338: my $fnsymb=shift;
3339: unless ($env{'request.course.id'}) { return ''; }
3340: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3341: if ($fnsymb=~/$LONCAPA::assess_re/) {
3342: $what.=':POST';
3343: # FIXME: Probably ought to escape things....
3344: foreach my $key (keys(%env)) {
3345: if ($key=~/^form\.(.*)/) {
3346: my $formitem = $1;
3347: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3348: $what.=':'.$formitem.'='.$env{$key};
3349: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3350: $what.=':'.$formitem.'='.$env{$key};
3351: }
3352: }
3353: }
3354: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3355: # FIXME: We should not be depending on a form parameter that someone
3356: # editing lonsearchcat.pm might change in the future.
3357: if ($env{'form.phase'} eq 'course_search') {
3358: $what.= ':POST';
3359: # FIXME: Probably ought to escape things....
3360: foreach my $element ('courseexp','crsfulltext','crsrelated',
3361: 'crsdiscuss') {
3362: $what.=':'.$element.'='.$env{'form.'.$element};
3363: }
3364: }
3365: }
3366: &courselog($what);
3367: }
3368:
3369: sub countacc {
3370: my $url=&declutter(shift);
3371: return if (! defined($url) || $url eq '');
3372: unless ($env{'request.course.id'}) { return ''; }
3373: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3374: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3375: $accesshash{$key}++;
3376: }
3377:
3378: sub linklog {
3379: my ($from,$to)=@_;
3380: $from=&declutter($from);
3381: $to=&declutter($to);
3382: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3383: $accesshash{$to.'___'.$from.'___goto'}=1;
3384: }
3385:
3386: sub userrolelog {
3387: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3388: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3389: ($trole=~/^in/) || ($trole=~/^cc/) ||
3390: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3391: ($trole=~/^ta/) || ($trole=~/^co/)) {
3392: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3393: $userrolehash
3394: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3395: =$tend.':'.$tstart;
3396: }
3397: if (($env{'request.role'} =~ /dc\./) &&
3398: (($trole=~/^au/) || ($trole=~/^in/) ||
3399: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3400: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3401: ($trole=~/^co/))) {
3402: $userrolehash
3403: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3404: =$tend.':'.$tstart;
3405: }
3406: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3407: ($trole=~/^li/) || ($trole=~/^li/) ||
3408: ($trole=~/^au/) || ($trole=~/^dg/) ||
3409: ($trole=~/^sc/)) {
3410: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3411: $domainrolehash
3412: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3413: = $tend.':'.$tstart;
3414: }
3415: }
3416:
3417: sub courserolelog {
3418: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3419: if (($trole eq 'cc') || ($trole eq 'in') ||
3420: ($trole eq 'ep') || ($trole eq 'ad') ||
3421: ($trole eq 'ta') || ($trole eq 'st') ||
3422: ($trole=~/^cr/) || ($trole eq 'gr') ||
3423: ($trole eq 'co')) {
3424: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3425: my $cdom = $1;
3426: my $cnum = $2;
3427: my $sec = $3;
3428: my $namespace = 'rolelog';
3429: my %storehash = (
3430: role => $trole,
3431: start => $tstart,
3432: end => $tend,
3433: selfenroll => $selfenroll,
3434: context => $context,
3435: );
3436: if ($trole eq 'gr') {
3437: $namespace = 'groupslog';
3438: $storehash{'group'} = $sec;
3439: } else {
3440: $storehash{'section'} = $sec;
3441: }
3442: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3443: if (($trole ne 'st') || ($sec ne '')) {
3444: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3445: }
3446: }
3447: }
3448: return;
3449: }
3450:
3451: sub get_course_adv_roles {
3452: my ($cid,$codes) = @_;
3453: $cid=$env{'request.course.id'} unless (defined($cid));
3454: my %coursehash=&coursedescription($cid);
3455: my $crstype = &Apache::loncommon::course_type($cid);
3456: my %nothide=();
3457: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3458: if ($user !~ /:/) {
3459: $nothide{join(':',split(/[\@]/,$user))}=1;
3460: } else {
3461: $nothide{$user}=1;
3462: }
3463: }
3464: my %returnhash=();
3465: my %dumphash=
3466: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3467: my $now=time;
3468: my %privileged;
3469: foreach my $entry (keys(%dumphash)) {
3470: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3471: if (($tstart) && ($tstart<0)) { next; }
3472: if (($tend) && ($tend<$now)) { next; }
3473: if (($tstart) && ($now<$tstart)) { next; }
3474: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3475: if ($username eq '' || $domain eq '') { next; }
3476: unless (ref($privileged{$domain}) eq 'HASH') {
3477: my %dompersonnel =
3478: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3479: $privileged{$domain} = {};
3480: foreach my $server (keys(%dompersonnel)) {
3481: if (ref($dompersonnel{$server}) eq 'HASH') {
3482: foreach my $user (keys(%{$dompersonnel{$server}})) {
3483: my ($trole,$uname,$udom) = split(/:/,$user);
3484: $privileged{$udom}{$uname} = 1;
3485: }
3486: }
3487: }
3488: }
3489: if ((exists($privileged{$domain}{$username})) &&
3490: (!$nothide{$username.':'.$domain})) { next; }
3491: if ($role eq 'cr') { next; }
3492: if ($codes) {
3493: if ($section) { $role .= ':'.$section; }
3494: if ($returnhash{$role}) {
3495: $returnhash{$role}.=','.$username.':'.$domain;
3496: } else {
3497: $returnhash{$role}=$username.':'.$domain;
3498: }
3499: } else {
3500: my $key=&plaintext($role,$crstype);
3501: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3502: if ($returnhash{$key}) {
3503: $returnhash{$key}.=','.$username.':'.$domain;
3504: } else {
3505: $returnhash{$key}=$username.':'.$domain;
3506: }
3507: }
3508: }
3509: return %returnhash;
3510: }
3511:
3512: sub get_my_roles {
3513: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3514: unless (defined($uname)) { $uname=$env{'user.name'}; }
3515: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3516: my (%dumphash,%nothide);
3517: if ($context eq 'userroles') {
3518: my $extra = &freeze_escape({'skipcheck' => 1});
3519: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3520: } else {
3521: %dumphash=
3522: &dump('nohist_userroles',$udom,$uname);
3523: if ($hidepriv) {
3524: my %coursehash=&coursedescription($udom.'_'.$uname);
3525: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3526: if ($user !~ /:/) {
3527: $nothide{join(':',split(/[\@]/,$user))} = 1;
3528: } else {
3529: $nothide{$user} = 1;
3530: }
3531: }
3532: }
3533: }
3534: my %returnhash=();
3535: my $now=time;
3536: my %privileged;
3537: foreach my $entry (keys(%dumphash)) {
3538: my ($role,$tend,$tstart);
3539: if ($context eq 'userroles') {
3540: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3541: } else {
3542: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3543: }
3544: if (($tstart) && ($tstart<0)) { next; }
3545: my $status = 'active';
3546: if (($tend) && ($tend<=$now)) {
3547: $status = 'previous';
3548: }
3549: if (($tstart) && ($now<$tstart)) {
3550: $status = 'future';
3551: }
3552: if (ref($types) eq 'ARRAY') {
3553: if (!grep(/^\Q$status\E$/,@{$types})) {
3554: next;
3555: }
3556: } else {
3557: if ($status ne 'active') {
3558: next;
3559: }
3560: }
3561: my ($rolecode,$username,$domain,$section,$area);
3562: if ($context eq 'userroles') {
3563: ($area,$rolecode) = split(/_/,$entry);
3564: (undef,$domain,$username,$section) = split(/\//,$area);
3565: } else {
3566: ($role,$username,$domain,$section) = split(/\:/,$entry);
3567: }
3568: if (ref($roledoms) eq 'ARRAY') {
3569: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3570: next;
3571: }
3572: }
3573: if (ref($roles) eq 'ARRAY') {
3574: if (!grep(/^\Q$role\E$/,@{$roles})) {
3575: if ($role =~ /^cr\//) {
3576: if (!grep(/^cr$/,@{$roles})) {
3577: next;
3578: }
3579: } elsif ($role =~ /^gr\//) {
3580: if (!grep(/^gr$/,@{$roles})) {
3581: next;
3582: }
3583: } else {
3584: next;
3585: }
3586: }
3587: }
3588: if ($hidepriv) {
3589: if ($context eq 'userroles') {
3590: if ((&privileged($username,$domain)) &&
3591: (!$nothide{$username.':'.$domain})) {
3592: next;
3593: }
3594: } else {
3595: unless (ref($privileged{$domain}) eq 'HASH') {
3596: my %dompersonnel =
3597: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3598: $privileged{$domain} = {};
3599: if (keys(%dompersonnel)) {
3600: foreach my $server (keys(%dompersonnel)) {
3601: if (ref($dompersonnel{$server}) eq 'HASH') {
3602: foreach my $user (keys(%{$dompersonnel{$server}})) {
3603: my ($trole,$uname,$udom) = split(/:/,$user);
3604: $privileged{$udom}{$uname} = $trole;
3605: }
3606: }
3607: }
3608: }
3609: }
3610: if (exists($privileged{$domain}{$username})) {
3611: if (!$nothide{$username.':'.$domain}) {
3612: next;
3613: }
3614: }
3615: }
3616: }
3617: if ($withsec) {
3618: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3619: $tstart.':'.$tend;
3620: } else {
3621: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3622: }
3623: }
3624: return %returnhash;
3625: }
3626:
3627: # ----------------------------------------------------- Frontpage Announcements
3628: #
3629: #
3630:
3631: sub postannounce {
3632: my ($server,$text)=@_;
3633: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3634: unless ($text=~/\w/) { $text=''; }
3635: return &reply('setannounce:'.&escape($text),$server);
3636: }
3637:
3638: sub getannounce {
3639:
3640: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3641: my $announcement='';
3642: while (my $line = <$fh>) { $announcement .= $line; }
3643: close($fh);
3644: if ($announcement=~/\w/) {
3645: return
3646: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3647: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3648: } else {
3649: return '';
3650: }
3651: } else {
3652: return '';
3653: }
3654: }
3655:
3656: # ---------------------------------------------------------- Course ID routines
3657: # Deal with domain's nohist_courseid.db files
3658: #
3659:
3660: sub courseidput {
3661: my ($domain,$storehash,$coursehome,$caller) = @_;
3662: return unless (ref($storehash) eq 'HASH');
3663: my $outcome;
3664: if ($caller eq 'timeonly') {
3665: my $cids = '';
3666: foreach my $item (keys(%$storehash)) {
3667: $cids.=&escape($item).'&';
3668: }
3669: $cids=~s/\&$//;
3670: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3671: $coursehome);
3672: } else {
3673: my $items = '';
3674: foreach my $item (keys(%$storehash)) {
3675: $items.= &escape($item).'='.
3676: &freeze_escape($$storehash{$item}).'&';
3677: }
3678: $items=~s/\&$//;
3679: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3680: $coursehome);
3681: }
3682: if ($outcome eq 'unknown_cmd') {
3683: my $what;
3684: foreach my $cid (keys(%$storehash)) {
3685: $what .= &escape($cid).'=';
3686: foreach my $item ('description','inst_code','owner','type') {
3687: $what .= &escape($storehash->{$cid}{$item}).':';
3688: }
3689: $what =~ s/\:$/&/;
3690: }
3691: $what =~ s/\&$//;
3692: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3693: } else {
3694: return $outcome;
3695: }
3696: }
3697:
3698: sub courseiddump {
3699: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3700: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3701: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3702: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3703: my $as_hash = 1;
3704: my %returnhash;
3705: if (!$domfilter) { $domfilter=''; }
3706: my %libserv = &all_library();
3707: foreach my $tryserver (keys(%libserv)) {
3708: if ( ( $hostidflag == 1
3709: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3710: || (!defined($hostidflag)) ) {
3711:
3712: if (($domfilter eq '') ||
3713: (&host_domain($tryserver) eq $domfilter)) {
3714: my $rep =
3715: &reply('courseiddump:'.&host_domain($tryserver).':'.
3716: $sincefilter.':'.&escape($descfilter).':'.
3717: &escape($instcodefilter).':'.&escape($ownerfilter).
3718: ':'.&escape($coursefilter).':'.&escape($typefilter).
3719: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3720: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3721: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3722: &escape($cc_clone).':'.$cloneonly.':'.
3723: &escape($createdbefore).':'.&escape($createdafter).':'.
3724: &escape($creationcontext).':'.$domcloner,
3725: $tryserver);
3726: my @pairs=split(/\&/,$rep);
3727: foreach my $item (@pairs) {
3728: my ($key,$value)=split(/\=/,$item,2);
3729: $key = &unescape($key);
3730: next if ($key =~ /^error: 2 /);
3731: my $result = &thaw_unescape($value);
3732: if (ref($result) eq 'HASH') {
3733: $returnhash{$key}=$result;
3734: } else {
3735: my @responses = split(/:/,$value);
3736: my @items = ('description','inst_code','owner','type');
3737: for (my $i=0; $i<@responses; $i++) {
3738: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3739: }
3740: }
3741: }
3742: }
3743: }
3744: }
3745: return %returnhash;
3746: }
3747:
3748: sub courselastaccess {
3749: my ($cdom,$cnum,$hostidref) = @_;
3750: my %returnhash;
3751: if ($cdom && $cnum) {
3752: my $chome = &homeserver($cnum,$cdom);
3753: if ($chome ne 'no_host') {
3754: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3755: &extract_lastaccess(\%returnhash,$rep);
3756: }
3757: } else {
3758: if (!$cdom) { $cdom=''; }
3759: my %libserv = &all_library();
3760: foreach my $tryserver (keys(%libserv)) {
3761: if (ref($hostidref) eq 'ARRAY') {
3762: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3763: }
3764: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3765: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3766: &extract_lastaccess(\%returnhash,$rep);
3767: }
3768: }
3769: }
3770: return %returnhash;
3771: }
3772:
3773: sub extract_lastaccess {
3774: my ($returnhash,$rep) = @_;
3775: if (ref($returnhash) eq 'HASH') {
3776: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3777: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3778: $rep eq '') {
3779: my @pairs=split(/\&/,$rep);
3780: foreach my $item (@pairs) {
3781: my ($key,$value)=split(/\=/,$item,2);
3782: $key = &unescape($key);
3783: next if ($key =~ /^error: 2 /);
3784: $returnhash->{$key} = &thaw_unescape($value);
3785: }
3786: }
3787: }
3788: return;
3789: }
3790:
3791: # ---------------------------------------------------------- DC e-mail
3792:
3793: sub dcmailput {
3794: my ($domain,$msgid,$message,$server)=@_;
3795: my $status = &Apache::lonnet::critical(
3796: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3797: &escape($message),$server);
3798: return $status;
3799: }
3800:
3801: sub dcmaildump {
3802: my ($dom,$startdate,$enddate,$senders) = @_;
3803: my %returnhash=();
3804:
3805: if (defined(&domain($dom,'primary'))) {
3806: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3807: &escape($enddate).':';
3808: my @esc_senders=map { &escape($_)} @$senders;
3809: $cmd.=&escape(join('&',@esc_senders));
3810: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3811: my ($key,$value) = split(/\=/,$line,2);
3812: if (($key) && ($value)) {
3813: $returnhash{&unescape($key)} = &unescape($value);
3814: }
3815: }
3816: }
3817: return %returnhash;
3818: }
3819: # ---------------------------------------------------------- Domain roles
3820:
3821: sub get_domain_roles {
3822: my ($dom,$roles,$startdate,$enddate)=@_;
3823: if ((!defined($startdate)) || ($startdate eq '')) {
3824: $startdate = '.';
3825: }
3826: if ((!defined($enddate)) || ($enddate eq '')) {
3827: $enddate = '.';
3828: }
3829: my $rolelist;
3830: if (ref($roles) eq 'ARRAY') {
3831: $rolelist = join(':',@{$roles});
3832: }
3833: my %personnel = ();
3834:
3835: my %servers = &get_servers($dom,'library');
3836: foreach my $tryserver (keys(%servers)) {
3837: %{$personnel{$tryserver}}=();
3838: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3839: &escape($startdate).':'.
3840: &escape($enddate).':'.
3841: &escape($rolelist), $tryserver))) {
3842: my ($key,$value) = split(/\=/,$line,2);
3843: if (($key) && ($value)) {
3844: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3845: }
3846: }
3847: }
3848: return %personnel;
3849: }
3850:
3851: # ----------------------------------------------------------- Interval timing
3852:
3853: sub get_first_access {
3854: my ($type,$argsymb)=@_;
3855: my ($symb,$courseid,$udom,$uname)=&whichuser();
3856: if ($argsymb) { $symb=$argsymb; }
3857: my ($map,$id,$res)=&decode_symb($symb);
3858: if ($type eq 'course') {
3859: $res='course';
3860: } elsif ($type eq 'map') {
3861: $res=&symbread($map);
3862: } else {
3863: $res=$symb;
3864: }
3865: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3866: return $times{"$courseid\0$res"};
3867: }
3868:
3869: sub set_first_access {
3870: my ($type)=@_;
3871: my ($symb,$courseid,$udom,$uname)=&whichuser();
3872: my ($map,$id,$res)=&decode_symb($symb);
3873: if ($type eq 'course') {
3874: $res='course';
3875: } elsif ($type eq 'map') {
3876: $res=&symbread($map);
3877: } else {
3878: $res=$symb;
3879: }
3880: my $firstaccess=&get_first_access($type,$symb);
3881: if (!$firstaccess) {
3882: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3883: }
3884: return 'already_set';
3885: }
3886:
3887: # --------------------------------------------- Set Expire Date for Spreadsheet
3888:
3889: sub expirespread {
3890: my ($uname,$udom,$stype,$usymb)=@_;
3891: my $cid=$env{'request.course.id'};
3892: if ($cid) {
3893: my $now=time;
3894: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3895: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3896: $env{'course.'.$cid.'.num'}.
3897: ':nohist_expirationdates:'.
3898: &escape($key).'='.$now,
3899: $env{'course.'.$cid.'.home'})
3900: }
3901: return 'ok';
3902: }
3903:
3904: # ----------------------------------------------------- Devalidate Spreadsheets
3905:
3906: sub devalidate {
3907: my ($symb,$uname,$udom)=@_;
3908: my $cid=$env{'request.course.id'};
3909: if ($cid) {
3910: # delete the stored spreadsheets for
3911: # - the student level sheet of this user in course's homespace
3912: # - the assessment level sheet for this resource
3913: # for this user in user's homespace
3914: # - current conditional state info
3915: my $key=$uname.':'.$udom.':';
3916: my $status=
3917: &del('nohist_calculatedsheets',
3918: [$key.'studentcalc:'],
3919: $env{'course.'.$cid.'.domain'},
3920: $env{'course.'.$cid.'.num'})
3921: .' '.
3922: &del('nohist_calculatedsheets_'.$cid,
3923: [$key.'assesscalc:'.$symb],$udom,$uname);
3924: unless ($status eq 'ok ok') {
3925: &logthis('Could not devalidate spreadsheet '.
3926: $uname.' at '.$udom.' for '.
3927: $symb.': '.$status);
3928: }
3929: &delenv('user.state.'.$cid);
3930: }
3931: }
3932:
3933: sub get_scalar {
3934: my ($string,$end) = @_;
3935: my $value;
3936: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3937: $value = $1;
3938: } elsif ($$string =~ s/^([^&]*?)&//) {
3939: $value = $1;
3940: }
3941: return &unescape($value);
3942: }
3943:
3944: sub array2str {
3945: my (@array) = @_;
3946: my $result=&arrayref2str(\@array);
3947: $result=~s/^__ARRAY_REF__//;
3948: $result=~s/__END_ARRAY_REF__$//;
3949: return $result;
3950: }
3951:
3952: sub arrayref2str {
3953: my ($arrayref) = @_;
3954: my $result='__ARRAY_REF__';
3955: foreach my $elem (@$arrayref) {
3956: if(ref($elem) eq 'ARRAY') {
3957: $result.=&arrayref2str($elem).'&';
3958: } elsif(ref($elem) eq 'HASH') {
3959: $result.=&hashref2str($elem).'&';
3960: } elsif(ref($elem)) {
3961: #print("Got a ref of ".(ref($elem))." skipping.");
3962: } else {
3963: $result.=&escape($elem).'&';
3964: }
3965: }
3966: $result=~s/\&$//;
3967: $result .= '__END_ARRAY_REF__';
3968: return $result;
3969: }
3970:
3971: sub hash2str {
3972: my (%hash) = @_;
3973: my $result=&hashref2str(\%hash);
3974: $result=~s/^__HASH_REF__//;
3975: $result=~s/__END_HASH_REF__$//;
3976: return $result;
3977: }
3978:
3979: sub hashref2str {
3980: my ($hashref)=@_;
3981: my $result='__HASH_REF__';
3982: foreach my $key (sort(keys(%$hashref))) {
3983: if (ref($key) eq 'ARRAY') {
3984: $result.=&arrayref2str($key).'=';
3985: } elsif (ref($key) eq 'HASH') {
3986: $result.=&hashref2str($key).'=';
3987: } elsif (ref($key)) {
3988: $result.='=';
3989: #print("Got a ref of ".(ref($key))." skipping.");
3990: } else {
3991: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
3992: }
3993:
3994: if(ref($hashref->{$key}) eq 'ARRAY') {
3995: $result.=&arrayref2str($hashref->{$key}).'&';
3996: } elsif(ref($hashref->{$key}) eq 'HASH') {
3997: $result.=&hashref2str($hashref->{$key}).'&';
3998: } elsif(ref($hashref->{$key})) {
3999: $result.='&';
4000: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4001: } else {
4002: $result.=&escape($hashref->{$key}).'&';
4003: }
4004: }
4005: $result=~s/\&$//;
4006: $result .= '__END_HASH_REF__';
4007: return $result;
4008: }
4009:
4010: sub str2hash {
4011: my ($string)=@_;
4012: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4013: return %$hash;
4014: }
4015:
4016: sub str2hashref {
4017: my ($string) = @_;
4018:
4019: my %hash;
4020:
4021: if($string !~ /^__HASH_REF__/) {
4022: if (! ($string eq '' || !defined($string))) {
4023: $hash{'error'}='Not hash reference';
4024: }
4025: return (\%hash, $string);
4026: }
4027:
4028: $string =~ s/^__HASH_REF__//;
4029:
4030: while($string !~ /^__END_HASH_REF__/) {
4031: #key
4032: my $key='';
4033: if($string =~ /^__HASH_REF__/) {
4034: ($key, $string)=&str2hashref($string);
4035: if(defined($key->{'error'})) {
4036: $hash{'error'}='Bad data';
4037: return (\%hash, $string);
4038: }
4039: } elsif($string =~ /^__ARRAY_REF__/) {
4040: ($key, $string)=&str2arrayref($string);
4041: if($key->[0] eq 'Array reference error') {
4042: $hash{'error'}='Bad data';
4043: return (\%hash, $string);
4044: }
4045: } else {
4046: $string =~ s/^(.*?)=//;
4047: $key=&unescape($1);
4048: }
4049: $string =~ s/^=//;
4050:
4051: #value
4052: my $value='';
4053: if($string =~ /^__HASH_REF__/) {
4054: ($value, $string)=&str2hashref($string);
4055: if(defined($value->{'error'})) {
4056: $hash{'error'}='Bad data';
4057: return (\%hash, $string);
4058: }
4059: } elsif($string =~ /^__ARRAY_REF__/) {
4060: ($value, $string)=&str2arrayref($string);
4061: if($value->[0] eq 'Array reference error') {
4062: $hash{'error'}='Bad data';
4063: return (\%hash, $string);
4064: }
4065: } else {
4066: $value=&get_scalar(\$string,'__END_HASH_REF__');
4067: }
4068: $string =~ s/^&//;
4069:
4070: $hash{$key}=$value;
4071: }
4072:
4073: $string =~ s/^__END_HASH_REF__//;
4074:
4075: return (\%hash, $string);
4076: }
4077:
4078: sub str2array {
4079: my ($string)=@_;
4080: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4081: return @$array;
4082: }
4083:
4084: sub str2arrayref {
4085: my ($string) = @_;
4086: my @array;
4087:
4088: if($string !~ /^__ARRAY_REF__/) {
4089: if (! ($string eq '' || !defined($string))) {
4090: $array[0]='Array reference error';
4091: }
4092: return (\@array, $string);
4093: }
4094:
4095: $string =~ s/^__ARRAY_REF__//;
4096:
4097: while($string !~ /^__END_ARRAY_REF__/) {
4098: my $value='';
4099: if($string =~ /^__HASH_REF__/) {
4100: ($value, $string)=&str2hashref($string);
4101: if(defined($value->{'error'})) {
4102: $array[0] ='Array reference error';
4103: return (\@array, $string);
4104: }
4105: } elsif($string =~ /^__ARRAY_REF__/) {
4106: ($value, $string)=&str2arrayref($string);
4107: if($value->[0] eq 'Array reference error') {
4108: $array[0] ='Array reference error';
4109: return (\@array, $string);
4110: }
4111: } else {
4112: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4113: }
4114: $string =~ s/^&//;
4115:
4116: push(@array, $value);
4117: }
4118:
4119: $string =~ s/^__END_ARRAY_REF__//;
4120:
4121: return (\@array, $string);
4122: }
4123:
4124: # -------------------------------------------------------------------Temp Store
4125:
4126: sub tmpreset {
4127: my ($symb,$namespace,$domain,$stuname) = @_;
4128: if (!$symb) {
4129: $symb=&symbread();
4130: if (!$symb) { $symb= $env{'request.url'}; }
4131: }
4132: $symb=escape($symb);
4133:
4134: if (!$namespace) { $namespace=$env{'request.state'}; }
4135: $namespace=~s/\//\_/g;
4136: $namespace=~s/\W//g;
4137:
4138: if (!$domain) { $domain=$env{'user.domain'}; }
4139: if (!$stuname) { $stuname=$env{'user.name'}; }
4140: if ($domain eq 'public' && $stuname eq 'public') {
4141: $stuname=$ENV{'REMOTE_ADDR'};
4142: }
4143: my $path=LONCAPA::tempdir();
4144: my %hash;
4145: if (tie(%hash,'GDBM_File',
4146: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4147: &GDBM_WRCREAT(),0640)) {
4148: foreach my $key (keys(%hash)) {
4149: if ($key=~ /:$symb/) {
4150: delete($hash{$key});
4151: }
4152: }
4153: }
4154: }
4155:
4156: sub tmpstore {
4157: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4158:
4159: if (!$symb) {
4160: $symb=&symbread();
4161: if (!$symb) { $symb= $env{'request.url'}; }
4162: }
4163: $symb=escape($symb);
4164:
4165: if (!$namespace) {
4166: # I don't think we would ever want to store this for a course.
4167: # it seems this will only be used if we don't have a course.
4168: #$namespace=$env{'request.course.id'};
4169: #if (!$namespace) {
4170: $namespace=$env{'request.state'};
4171: #}
4172: }
4173: $namespace=~s/\//\_/g;
4174: $namespace=~s/\W//g;
4175: if (!$domain) { $domain=$env{'user.domain'}; }
4176: if (!$stuname) { $stuname=$env{'user.name'}; }
4177: if ($domain eq 'public' && $stuname eq 'public') {
4178: $stuname=$ENV{'REMOTE_ADDR'};
4179: }
4180: my $now=time;
4181: my %hash;
4182: my $path=LONCAPA::tempdir();
4183: if (tie(%hash,'GDBM_File',
4184: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4185: &GDBM_WRCREAT(),0640)) {
4186: $hash{"version:$symb"}++;
4187: my $version=$hash{"version:$symb"};
4188: my $allkeys='';
4189: foreach my $key (keys(%$storehash)) {
4190: $allkeys.=$key.':';
4191: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4192: }
4193: $hash{"$version:$symb:timestamp"}=$now;
4194: $allkeys.='timestamp';
4195: $hash{"$version:keys:$symb"}=$allkeys;
4196: if (untie(%hash)) {
4197: return 'ok';
4198: } else {
4199: return "error:$!";
4200: }
4201: } else {
4202: return "error:$!";
4203: }
4204: }
4205:
4206: # -----------------------------------------------------------------Temp Restore
4207:
4208: sub tmprestore {
4209: my ($symb,$namespace,$domain,$stuname) = @_;
4210:
4211: if (!$symb) {
4212: $symb=&symbread();
4213: if (!$symb) { $symb= $env{'request.url'}; }
4214: }
4215: $symb=escape($symb);
4216:
4217: if (!$namespace) { $namespace=$env{'request.state'}; }
4218:
4219: if (!$domain) { $domain=$env{'user.domain'}; }
4220: if (!$stuname) { $stuname=$env{'user.name'}; }
4221: if ($domain eq 'public' && $stuname eq 'public') {
4222: $stuname=$ENV{'REMOTE_ADDR'};
4223: }
4224: my %returnhash;
4225: $namespace=~s/\//\_/g;
4226: $namespace=~s/\W//g;
4227: my %hash;
4228: my $path=LONCAPA::tempdir();
4229: if (tie(%hash,'GDBM_File',
4230: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4231: &GDBM_READER(),0640)) {
4232: my $version=$hash{"version:$symb"};
4233: $returnhash{'version'}=$version;
4234: my $scope;
4235: for ($scope=1;$scope<=$version;$scope++) {
4236: my $vkeys=$hash{"$scope:keys:$symb"};
4237: my @keys=split(/:/,$vkeys);
4238: my $key;
4239: $returnhash{"$scope:keys"}=$vkeys;
4240: foreach $key (@keys) {
4241: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4242: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4243: }
4244: }
4245: if (!(untie(%hash))) {
4246: return "error:$!";
4247: }
4248: } else {
4249: return "error:$!";
4250: }
4251: return %returnhash;
4252: }
4253:
4254: # ----------------------------------------------------------------------- Store
4255:
4256: sub store {
4257: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4258: my $home='';
4259:
4260: if ($stuname) { $home=&homeserver($stuname,$domain); }
4261:
4262: $symb=&symbclean($symb);
4263: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4264:
4265: if (!$domain) { $domain=$env{'user.domain'}; }
4266: if (!$stuname) { $stuname=$env{'user.name'}; }
4267:
4268: &devalidate($symb,$stuname,$domain);
4269:
4270: $symb=escape($symb);
4271: if (!$namespace) {
4272: unless ($namespace=$env{'request.course.id'}) {
4273: return '';
4274: }
4275: }
4276: if (!$home) { $home=$env{'user.home'}; }
4277:
4278: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4279: $$storehash{'host'}=$perlvar{'lonHostID'};
4280:
4281: my $namevalue='';
4282: foreach my $key (keys(%$storehash)) {
4283: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4284: }
4285: $namevalue=~s/\&$//;
4286: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4287: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4288: }
4289:
4290: # -------------------------------------------------------------- Critical Store
4291:
4292: sub cstore {
4293: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4294: my $home='';
4295:
4296: if ($stuname) { $home=&homeserver($stuname,$domain); }
4297:
4298: $symb=&symbclean($symb);
4299: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4300:
4301: if (!$domain) { $domain=$env{'user.domain'}; }
4302: if (!$stuname) { $stuname=$env{'user.name'}; }
4303:
4304: &devalidate($symb,$stuname,$domain);
4305:
4306: $symb=escape($symb);
4307: if (!$namespace) {
4308: unless ($namespace=$env{'request.course.id'}) {
4309: return '';
4310: }
4311: }
4312: if (!$home) { $home=$env{'user.home'}; }
4313:
4314: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4315: $$storehash{'host'}=$perlvar{'lonHostID'};
4316:
4317: my $namevalue='';
4318: foreach my $key (keys(%$storehash)) {
4319: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4320: }
4321: $namevalue=~s/\&$//;
4322: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4323: return critical
4324: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4325: }
4326:
4327: # --------------------------------------------------------------------- Restore
4328:
4329: sub restore {
4330: my ($symb,$namespace,$domain,$stuname) = @_;
4331: my $home='';
4332:
4333: if ($stuname) { $home=&homeserver($stuname,$domain); }
4334:
4335: if (!$symb) {
4336: unless ($symb=escape(&symbread())) { return ''; }
4337: } else {
4338: $symb=&escape(&symbclean($symb));
4339: }
4340: if (!$namespace) {
4341: unless ($namespace=$env{'request.course.id'}) {
4342: return '';
4343: }
4344: }
4345: if (!$domain) { $domain=$env{'user.domain'}; }
4346: if (!$stuname) { $stuname=$env{'user.name'}; }
4347: if (!$home) { $home=$env{'user.home'}; }
4348: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4349:
4350: my %returnhash=();
4351: foreach my $line (split(/\&/,$answer)) {
4352: my ($name,$value)=split(/\=/,$line);
4353: $returnhash{&unescape($name)}=&thaw_unescape($value);
4354: }
4355: my $version;
4356: for ($version=1;$version<=$returnhash{'version'};$version++) {
4357: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4358: $returnhash{$item}=$returnhash{$version.':'.$item};
4359: }
4360: }
4361: return %returnhash;
4362: }
4363:
4364: # ---------------------------------------------------------- Course Description
4365: #
4366: #
4367:
4368: sub coursedescription {
4369: my ($courseid,$args)=@_;
4370: $courseid=~s/^\///;
4371: $courseid=~s/\_/\//g;
4372: my ($cdomain,$cnum)=split(/\//,$courseid);
4373: my $chome=&homeserver($cnum,$cdomain);
4374: my $normalid=$cdomain.'_'.$cnum;
4375: # need to always cache even if we get errors otherwise we keep
4376: # trying and trying and trying to get the course description.
4377: my %envhash=();
4378: my %returnhash=();
4379:
4380: my $expiretime=600;
4381: if ($env{'request.course.id'} eq $normalid) {
4382: $expiretime=120;
4383: }
4384:
4385: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4386: if (!$args->{'freshen_cache'}
4387: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4388: foreach my $key (keys(%env)) {
4389: next if ($key !~ /^\Q$prefix\E(.*)/);
4390: my ($setting) = $1;
4391: $returnhash{$setting} = $env{$key};
4392: }
4393: return %returnhash;
4394: }
4395:
4396: # get the data again
4397:
4398: if (!$args->{'one_time'}) {
4399: $envhash{'course.'.$normalid.'.last_cache'}=time;
4400: }
4401:
4402: if ($chome ne 'no_host') {
4403: %returnhash=&dump('environment',$cdomain,$cnum);
4404: if (!exists($returnhash{'con_lost'})) {
4405: my $username = $env{'user.name'}; # Defult username
4406: if(defined $args->{'user'}) {
4407: $username = $args->{'user'};
4408: }
4409: $returnhash{'home'}= $chome;
4410: $returnhash{'domain'} = $cdomain;
4411: $returnhash{'num'} = $cnum;
4412: if (!defined($returnhash{'type'})) {
4413: $returnhash{'type'} = 'Course';
4414: }
4415: while (my ($name,$value) = each %returnhash) {
4416: $envhash{'course.'.$normalid.'.'.$name}=$value;
4417: }
4418: $returnhash{'url'}=&clutter($returnhash{'url'});
4419: $returnhash{'fn'}=LONCAPA::tempdir() .
4420: $username.'_'.$cdomain.'_'.$cnum;
4421: $envhash{'course.'.$normalid.'.home'}=$chome;
4422: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4423: $envhash{'course.'.$normalid.'.num'}=$cnum;
4424: }
4425: }
4426: if (!$args->{'one_time'}) {
4427: &appenv(\%envhash);
4428: }
4429: return %returnhash;
4430: }
4431:
4432: sub update_released_required {
4433: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4434: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4435: $cid = $env{'request.course.id'};
4436: $cdom = $env{'course.'.$cid.'.domain'};
4437: $cnum = $env{'course.'.$cid.'.num'};
4438: $chome = $env{'course.'.$cid.'.home'};
4439: }
4440: if ($needsrelease) {
4441: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4442: my $needsupdate;
4443: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4444: $needsupdate = 1;
4445: } else {
4446: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4447: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4448: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4449: $needsupdate = 1;
4450: }
4451: }
4452: if ($needsupdate) {
4453: my %needshash = (
4454: 'internal.releaserequired' => $needsrelease,
4455: );
4456: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4457: if ($putresult eq 'ok') {
4458: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4459: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4460: if (ref($crsinfo{$cid}) eq 'HASH') {
4461: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4462: &courseidput($cdom,\%crsinfo,$chome,'notime');
4463: }
4464: }
4465: }
4466: }
4467: return;
4468: }
4469:
4470: # -------------------------------------------------See if a user is privileged
4471:
4472: sub privileged {
4473: my ($username,$domain)=@_;
4474: my $rolesdump=&reply("dump:$domain:$username:roles",
4475: &homeserver($username,$domain));
4476: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4477: ($rolesdump =~ /^error:/)) {
4478: return 0;
4479: }
4480: my $now=time;
4481: if ($rolesdump ne '') {
4482: foreach my $entry (split(/&/,$rolesdump)) {
4483: if ($entry!~/^rolesdef_/) {
4484: my ($area,$role)=split(/=/,$entry);
4485: $area=~s/\_\w\w$//;
4486: my ($trole,$tend,$tstart)=split(/_/,$role);
4487: if (($trole eq 'dc') || ($trole eq 'su')) {
4488: my $active=1;
4489: if ($tend) {
4490: if ($tend<$now) { $active=0; }
4491: }
4492: if ($tstart) {
4493: if ($tstart>$now) { $active=0; }
4494: }
4495: if ($active) { return 1; }
4496: }
4497: }
4498: }
4499: }
4500: return 0;
4501: }
4502:
4503: # -------------------------------------------------------- Get user privileges
4504:
4505: sub rolesinit {
4506: my ($domain,$username,$authhost)=@_;
4507: my $now=time;
4508: my %userroles = ('user.login.time' => $now);
4509: my $extra = &freeze_escape({'skipcheck' => 1});
4510: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4511: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4512: ($rolesdump =~ /^error:/)) {
4513: return \%userroles;
4514: }
4515: my %allroles=();
4516: my %allgroups=();
4517:
4518: if ($rolesdump ne '') {
4519: foreach my $entry (split(/&/,$rolesdump)) {
4520: if ($entry!~/^rolesdef_/) {
4521: my ($area,$role)=split(/=/,$entry);
4522: $area=~s/\_\w\w$//;
4523: my ($trole,$tend,$tstart,$group_privs);
4524: if ($role=~/^cr/) {
4525: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4526: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4527: ($tend,$tstart)=split('_',$trest);
4528: } else {
4529: $trole=$role;
4530: }
4531: } elsif ($role =~ m|^gr/|) {
4532: ($trole,$tend,$tstart) = split(/_/,$role);
4533: next if ($tstart eq '-1');
4534: ($trole,$group_privs) = split(/\//,$trole);
4535: $group_privs = &unescape($group_privs);
4536: } else {
4537: ($trole,$tend,$tstart)=split(/_/,$role);
4538: }
4539: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4540: $username);
4541: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4542: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4543: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4544: if (($area ne '') && ($trole ne '')) {
4545: my $spec=$trole.'.'.$area;
4546: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4547: if ($trole =~ /^cr\//) {
4548: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4549: } elsif ($trole eq 'gr') {
4550: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4551: } else {
4552: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4553: }
4554: }
4555: }
4556: }
4557: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4558: $userroles{'user.adv'} = $adv;
4559: $userroles{'user.author'} = $author;
4560: $env{'user.adv'}=$adv;
4561: }
4562: return \%userroles;
4563: }
4564:
4565: sub set_arearole {
4566: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4567: # log the associated role with the area
4568: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4569: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4570: }
4571:
4572: sub custom_roleprivs {
4573: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4574: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4575: my $homsvr=homeserver($rauthor,$rdomain);
4576: if (&hostname($homsvr) ne '') {
4577: my ($rdummy,$roledef)=
4578: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4579: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4580: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4581: if (defined($syspriv)) {
4582: if ($trest =~ /^$match_community$/) {
4583: $syspriv =~ s/bre\&S//;
4584: }
4585: $$allroles{'cm./'}.=':'.$syspriv;
4586: $$allroles{$spec.'./'}.=':'.$syspriv;
4587: }
4588: if ($tdomain ne '') {
4589: if (defined($dompriv)) {
4590: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4591: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4592: }
4593: if (($trest ne '') && (defined($coursepriv))) {
4594: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4595: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4596: }
4597: }
4598: }
4599: }
4600: }
4601:
4602: sub group_roleprivs {
4603: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4604: my $access = 1;
4605: my $now = time;
4606: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4607: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4608: if ($access) {
4609: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4610: $$allgroups{$course}{$group} .=':'.$group_privs;
4611: }
4612: }
4613:
4614: sub standard_roleprivs {
4615: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4616: if (defined($pr{$trole.':s'})) {
4617: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4618: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4619: }
4620: if ($tdomain ne '') {
4621: if (defined($pr{$trole.':d'})) {
4622: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4623: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4624: }
4625: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4626: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4627: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4628: }
4629: }
4630: }
4631:
4632: sub set_userprivs {
4633: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4634: my $author=0;
4635: my $adv=0;
4636: my %grouproles = ();
4637: if (keys(%{$allgroups}) > 0) {
4638: my @groupkeys;
4639: foreach my $role (keys(%{$allroles})) {
4640: push(@groupkeys,$role);
4641: }
4642: if (ref($groups_roles) eq 'HASH') {
4643: foreach my $key (keys(%{$groups_roles})) {
4644: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4645: push(@groupkeys,$key);
4646: }
4647: }
4648: }
4649: if (@groupkeys > 0) {
4650: foreach my $role (@groupkeys) {
4651: my ($trole,$area,$sec,$extendedarea);
4652: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4653: $trole = $1;
4654: $area = $2;
4655: $sec = $3;
4656: $extendedarea = $area.$sec;
4657: if (exists($$allgroups{$area})) {
4658: foreach my $group (keys(%{$$allgroups{$area}})) {
4659: my $spec = $trole.'.'.$extendedarea;
4660: $grouproles{$spec.'.'.$area.'/'.$group} =
4661: $$allgroups{$area}{$group};
4662: }
4663: }
4664: }
4665: }
4666: }
4667: }
4668: foreach my $group (keys(%grouproles)) {
4669: $$allroles{$group} = $grouproles{$group};
4670: }
4671: foreach my $role (keys(%{$allroles})) {
4672: my %thesepriv;
4673: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4674: foreach my $item (split(/:/,$$allroles{$role})) {
4675: if ($item ne '') {
4676: my ($privilege,$restrictions)=split(/&/,$item);
4677: if ($restrictions eq '') {
4678: $thesepriv{$privilege}='F';
4679: } elsif ($thesepriv{$privilege} ne 'F') {
4680: $thesepriv{$privilege}.=$restrictions;
4681: }
4682: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4683: }
4684: }
4685: my $thesestr='';
4686: foreach my $priv (sort(keys(%thesepriv))) {
4687: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4688: }
4689: $userroles->{'user.priv.'.$role} = $thesestr;
4690: }
4691: return ($author,$adv);
4692: }
4693:
4694: sub role_status {
4695: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4696: my @pwhere = ();
4697: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4698: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4699: unless (!defined($$role) || $$role eq '') {
4700: $$where=join('.',@pwhere);
4701: $$trolecode=$$role.'.'.$$where;
4702: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4703: $$tstatus='is';
4704: if ($$tstart && $$tstart>$update) {
4705: $$tstatus='future';
4706: if ($$tstart<$now) {
4707: if ($$tstart && $$tstart>$refresh) {
4708: if (($$where ne '') && ($$role ne '')) {
4709: my (%allroles,%allgroups,$group_privs,
4710: %groups_roles,@rolecodes);
4711: my %userroles = (
4712: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4713: );
4714: @rolecodes = ('cm');
4715: my $spec=$$role.'.'.$$where;
4716: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4717: if ($$role =~ /^cr\//) {
4718: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4719: push(@rolecodes,'cr');
4720: } elsif ($$role eq 'gr') {
4721: push(@rolecodes,$$role);
4722: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4723: $env{'user.name'});
4724: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4725: (undef,my $group_privs) = split(/\//,$trole);
4726: $group_privs = &unescape($group_privs);
4727: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4728: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4729: &get_groups_roles($tdomain,$trest,
4730: \%course_roles,\@rolecodes,
4731: \%groups_roles);
4732: } else {
4733: push(@rolecodes,$$role);
4734: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4735: }
4736: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4737: &appenv(\%userroles,\@rolecodes);
4738: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4739: }
4740: }
4741: $$tstatus = 'is';
4742: }
4743: }
4744: if ($$tend) {
4745: if ($$tend<$update) {
4746: $$tstatus='expired';
4747: } elsif ($$tend<$now) {
4748: $$tstatus='will_not';
4749: }
4750: }
4751: }
4752: }
4753: }
4754:
4755: sub get_groups_roles {
4756: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4757: return unless((ref($cdom_courseroles) eq 'HASH') &&
4758: (ref($rolecodes) eq 'ARRAY') &&
4759: (ref($groups_roles) eq 'HASH'));
4760: if (keys(%{$cdom_courseroles}) > 0) {
4761: my ($cnum) = ($rest =~ /^($match_courseid)/);
4762: if ($cdom ne '' && $cnum ne '') {
4763: foreach my $key (keys(%{$cdom_courseroles})) {
4764: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4765: my $crsrole = $1;
4766: my $crssec = $2;
4767: if ($crsrole =~ /^cr/) {
4768: unless (grep(/^cr$/,@{$rolecodes})) {
4769: push(@{$rolecodes},'cr');
4770: }
4771: } else {
4772: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4773: push(@{$rolecodes},$crsrole);
4774: }
4775: }
4776: my $rolekey = "$crsrole./$cdom/$cnum";
4777: if ($crssec ne '') {
4778: $rolekey .= "/$crssec";
4779: }
4780: $rolekey .= './';
4781: $groups_roles->{$rolekey} = $rolecodes;
4782: }
4783: }
4784: }
4785: }
4786: return;
4787: }
4788:
4789: sub delete_env_groupprivs {
4790: my ($where,$courseroles,$possroles) = @_;
4791: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4792: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4793: unless (ref($courseroles->{$udom}) eq 'HASH') {
4794: %{$courseroles->{$udom}} =
4795: &get_my_roles('','','userroles',['active'],
4796: $possroles,[$udom],1);
4797: }
4798: if (ref($courseroles->{$udom}) eq 'HASH') {
4799: foreach my $item (keys(%{$courseroles->{$udom}})) {
4800: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4801: my $area = '/'.$cdom.'/'.$cnum;
4802: my $privkey = "user.priv.$crsrole.$area";
4803: if ($crssec ne '') {
4804: $privkey .= '/'.$crssec;
4805: }
4806: $privkey .= ".$area/$group";
4807: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4808: }
4809: }
4810: return;
4811: }
4812:
4813: sub check_adhoc_privs {
4814: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4815: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4816: if ($env{$cckey}) {
4817: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4818: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4819: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4820: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4821: }
4822: } else {
4823: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4824: }
4825: }
4826:
4827: sub set_adhoc_privileges {
4828: # role can be cc or ca
4829: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4830: my $area = '/'.$dcdom.'/'.$pickedcourse;
4831: my $spec = $role.'.'.$area;
4832: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4833: $env{'user.name'});
4834: my %ccrole = ();
4835: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4836: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4837: &appenv(\%userroles,[$role,'cm']);
4838: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4839: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4840: &appenv( {'request.role' => $spec,
4841: 'request.role.domain' => $dcdom,
4842: 'request.course.sec' => ''
4843: }
4844: );
4845: my $tadv=0;
4846: if (&allowed('adv') eq 'F') { $tadv=1; }
4847: &appenv({'request.role.adv' => $tadv});
4848: }
4849: }
4850:
4851: # --------------------------------------------------------------- get interface
4852:
4853: sub get {
4854: my ($namespace,$storearr,$udomain,$uname)=@_;
4855: my $items='';
4856: foreach my $item (@$storearr) {
4857: $items.=&escape($item).'&';
4858: }
4859: $items=~s/\&$//;
4860: if (!$udomain) { $udomain=$env{'user.domain'}; }
4861: if (!$uname) { $uname=$env{'user.name'}; }
4862: my $uhome=&homeserver($uname,$udomain);
4863:
4864: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4865: my @pairs=split(/\&/,$rep);
4866: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4867: return @pairs;
4868: }
4869: my %returnhash=();
4870: my $i=0;
4871: foreach my $item (@$storearr) {
4872: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4873: $i++;
4874: }
4875: return %returnhash;
4876: }
4877:
4878: # --------------------------------------------------------------- del interface
4879:
4880: sub del {
4881: my ($namespace,$storearr,$udomain,$uname)=@_;
4882: my $items='';
4883: foreach my $item (@$storearr) {
4884: $items.=&escape($item).'&';
4885: }
4886:
4887: $items=~s/\&$//;
4888: if (!$udomain) { $udomain=$env{'user.domain'}; }
4889: if (!$uname) { $uname=$env{'user.name'}; }
4890: my $uhome=&homeserver($uname,$udomain);
4891: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4892: }
4893:
4894: # -------------------------------------------------------------- dump interface
4895:
4896: sub dump {
4897: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
4898: if (!$udomain) { $udomain=$env{'user.domain'}; }
4899: if (!$uname) { $uname=$env{'user.name'}; }
4900: my $uhome=&homeserver($uname,$udomain);
4901: if ($regexp) {
4902: $regexp=&escape($regexp);
4903: } else {
4904: $regexp='.';
4905: }
4906: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
4907: my @pairs=split(/\&/,$rep);
4908: my %returnhash=();
4909: if (!($rep =~ /^error/ )) {
4910: foreach my $item (@pairs) {
4911: my ($key,$value)=split(/=/,$item,2);
4912: $key = &unescape($key);
4913: next if ($key =~ /^error: 2 /);
4914: $returnhash{$key}=&thaw_unescape($value);
4915: }
4916: }
4917: return %returnhash;
4918: }
4919:
4920:
4921: # --------------------------------------------------------- dumpstore interface
4922:
4923: sub dumpstore {
4924: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4925: if (!$udomain) { $udomain=$env{'user.domain'}; }
4926: if (!$uname) { $uname=$env{'user.name'}; }
4927: my $uhome=&homeserver($uname,$udomain);
4928: if ($regexp) {
4929: $regexp=&escape($regexp);
4930: } else {
4931: $regexp='.';
4932: }
4933: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4934: my @pairs=split(/\&/,$rep);
4935: my %returnhash=();
4936: foreach my $item (@pairs) {
4937: my ($key,$value)=split(/=/,$item,2);
4938: next if ($key =~ /^error: 2 /);
4939: $returnhash{$key}=&thaw_unescape($value);
4940: }
4941: return %returnhash;
4942: }
4943:
4944: # -------------------------------------------------------------- keys interface
4945:
4946: sub getkeys {
4947: my ($namespace,$udomain,$uname)=@_;
4948: if (!$udomain) { $udomain=$env{'user.domain'}; }
4949: if (!$uname) { $uname=$env{'user.name'}; }
4950: my $uhome=&homeserver($uname,$udomain);
4951: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4952: my @keyarray=();
4953: foreach my $key (split(/\&/,$rep)) {
4954: next if ($key =~ /^error: 2 /);
4955: push(@keyarray,&unescape($key));
4956: }
4957: return @keyarray;
4958: }
4959:
4960: # --------------------------------------------------------------- currentdump
4961: sub currentdump {
4962: my ($courseid,$sdom,$sname)=@_;
4963: $courseid = $env{'request.course.id'} if (! defined($courseid));
4964: $sdom = $env{'user.domain'} if (! defined($sdom));
4965: $sname = $env{'user.name'} if (! defined($sname));
4966: my $uhome = &homeserver($sname,$sdom);
4967: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4968: return if ($rep =~ /^(error:|no_such_host)/);
4969: #
4970: my %returnhash=();
4971: #
4972: if ($rep eq "unknown_cmd") {
4973: # an old lond will not know currentdump
4974: # Do a dump and make it look like a currentdump
4975: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4976: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4977: my %hash = @tmp;
4978: @tmp=();
4979: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4980: } else {
4981: my @pairs=split(/\&/,$rep);
4982: foreach my $pair (@pairs) {
4983: my ($key,$value)=split(/=/,$pair,2);
4984: my ($symb,$param) = split(/:/,$key);
4985: $returnhash{&unescape($symb)}->{&unescape($param)} =
4986: &thaw_unescape($value);
4987: }
4988: }
4989: return %returnhash;
4990: }
4991:
4992: sub convert_dump_to_currentdump{
4993: my %hash = %{shift()};
4994: my %returnhash;
4995: # Code ripped from lond, essentially. The only difference
4996: # here is the unescaping done by lonnet::dump(). Conceivably
4997: # we might run in to problems with parameter names =~ /^v\./
4998: while (my ($key,$value) = each(%hash)) {
4999: my ($v,$symb,$param) = split(/:/,$key);
5000: $symb = &unescape($symb);
5001: $param = &unescape($param);
5002: next if ($v eq 'version' || $symb eq 'keys');
5003: next if (exists($returnhash{$symb}) &&
5004: exists($returnhash{$symb}->{$param}) &&
5005: $returnhash{$symb}->{'v.'.$param} > $v);
5006: $returnhash{$symb}->{$param}=$value;
5007: $returnhash{$symb}->{'v.'.$param}=$v;
5008: }
5009: #
5010: # Remove all of the keys in the hashes which keep track of
5011: # the version of the parameter.
5012: while (my ($symb,$param_hash) = each(%returnhash)) {
5013: # use a foreach because we are going to delete from the hash.
5014: foreach my $key (keys(%$param_hash)) {
5015: delete($param_hash->{$key}) if ($key =~ /^v\./);
5016: }
5017: }
5018: return \%returnhash;
5019: }
5020:
5021: # ------------------------------------------------------ critical inc interface
5022:
5023: sub cinc {
5024: return &inc(@_,'critical');
5025: }
5026:
5027: # --------------------------------------------------------------- inc interface
5028:
5029: sub inc {
5030: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5031: if (!$udomain) { $udomain=$env{'user.domain'}; }
5032: if (!$uname) { $uname=$env{'user.name'}; }
5033: my $uhome=&homeserver($uname,$udomain);
5034: my $items='';
5035: if (! ref($store)) {
5036: # got a single value, so use that instead
5037: $items = &escape($store).'=&';
5038: } elsif (ref($store) eq 'SCALAR') {
5039: $items = &escape($$store).'=&';
5040: } elsif (ref($store) eq 'ARRAY') {
5041: $items = join('=&',map {&escape($_);} @{$store});
5042: } elsif (ref($store) eq 'HASH') {
5043: while (my($key,$value) = each(%{$store})) {
5044: $items.= &escape($key).'='.&escape($value).'&';
5045: }
5046: }
5047: $items=~s/\&$//;
5048: if ($critical) {
5049: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5050: } else {
5051: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5052: }
5053: }
5054:
5055: # --------------------------------------------------------------- put interface
5056:
5057: sub put {
5058: my ($namespace,$storehash,$udomain,$uname)=@_;
5059: if (!$udomain) { $udomain=$env{'user.domain'}; }
5060: if (!$uname) { $uname=$env{'user.name'}; }
5061: my $uhome=&homeserver($uname,$udomain);
5062: my $items='';
5063: foreach my $item (keys(%$storehash)) {
5064: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5065: }
5066: $items=~s/\&$//;
5067: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5068: }
5069:
5070: # ------------------------------------------------------------ newput interface
5071:
5072: sub newput {
5073: my ($namespace,$storehash,$udomain,$uname)=@_;
5074: if (!$udomain) { $udomain=$env{'user.domain'}; }
5075: if (!$uname) { $uname=$env{'user.name'}; }
5076: my $uhome=&homeserver($uname,$udomain);
5077: my $items='';
5078: foreach my $key (keys(%$storehash)) {
5079: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5080: }
5081: $items=~s/\&$//;
5082: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5083: }
5084:
5085: # --------------------------------------------------------- putstore interface
5086:
5087: sub putstore {
5088: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5089: if (!$udomain) { $udomain=$env{'user.domain'}; }
5090: if (!$uname) { $uname=$env{'user.name'}; }
5091: my $uhome=&homeserver($uname,$udomain);
5092: my $items='';
5093: foreach my $key (keys(%$storehash)) {
5094: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5095: }
5096: $items=~s/\&$//;
5097: my $esc_symb=&escape($symb);
5098: my $esc_v=&escape($version);
5099: my $reply =
5100: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5101: $uhome);
5102: if ($reply eq 'unknown_cmd') {
5103: # gfall back to way things use to be done
5104: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5105: $uname);
5106: }
5107: return $reply;
5108: }
5109:
5110: sub old_putstore {
5111: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5112: if (!$udomain) { $udomain=$env{'user.domain'}; }
5113: if (!$uname) { $uname=$env{'user.name'}; }
5114: my $uhome=&homeserver($uname,$udomain);
5115: my %newstorehash;
5116: foreach my $item (keys(%$storehash)) {
5117: my $key = $version.':'.&escape($symb).':'.$item;
5118: $newstorehash{$key} = $storehash->{$item};
5119: }
5120: my $items='';
5121: my %allitems = ();
5122: foreach my $item (keys(%newstorehash)) {
5123: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5124: my $key = $1.':keys:'.$2;
5125: $allitems{$key} .= $3.':';
5126: }
5127: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5128: }
5129: foreach my $item (keys(%allitems)) {
5130: $allitems{$item} =~ s/\:$//;
5131: $items.= $item.'='.$allitems{$item}.'&';
5132: }
5133: $items=~s/\&$//;
5134: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5135: }
5136:
5137: # ------------------------------------------------------ critical put interface
5138:
5139: sub cput {
5140: my ($namespace,$storehash,$udomain,$uname)=@_;
5141: if (!$udomain) { $udomain=$env{'user.domain'}; }
5142: if (!$uname) { $uname=$env{'user.name'}; }
5143: my $uhome=&homeserver($uname,$udomain);
5144: my $items='';
5145: foreach my $item (keys(%$storehash)) {
5146: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5147: }
5148: $items=~s/\&$//;
5149: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5150: }
5151:
5152: # -------------------------------------------------------------- eget interface
5153:
5154: sub eget {
5155: my ($namespace,$storearr,$udomain,$uname)=@_;
5156: my $items='';
5157: foreach my $item (@$storearr) {
5158: $items.=&escape($item).'&';
5159: }
5160: $items=~s/\&$//;
5161: if (!$udomain) { $udomain=$env{'user.domain'}; }
5162: if (!$uname) { $uname=$env{'user.name'}; }
5163: my $uhome=&homeserver($uname,$udomain);
5164: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5165: my @pairs=split(/\&/,$rep);
5166: my %returnhash=();
5167: my $i=0;
5168: foreach my $item (@$storearr) {
5169: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5170: $i++;
5171: }
5172: return %returnhash;
5173: }
5174:
5175: # ------------------------------------------------------------ tmpput interface
5176: sub tmpput {
5177: my ($storehash,$server,$context)=@_;
5178: my $items='';
5179: foreach my $item (keys(%$storehash)) {
5180: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5181: }
5182: $items=~s/\&$//;
5183: if (defined($context)) {
5184: $items .= ':'.&escape($context);
5185: }
5186: return &reply("tmpput:$items",$server);
5187: }
5188:
5189: # ------------------------------------------------------------ tmpget interface
5190: sub tmpget {
5191: my ($token,$server)=@_;
5192: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5193: my $rep=&reply("tmpget:$token",$server);
5194: my %returnhash;
5195: foreach my $item (split(/\&/,$rep)) {
5196: my ($key,$value)=split(/=/,$item);
5197: next if ($key =~ /^error: 2 /);
5198: $returnhash{&unescape($key)}=&thaw_unescape($value);
5199: }
5200: return %returnhash;
5201: }
5202:
5203: # ------------------------------------------------------------ tmpdel interface
5204: sub tmpdel {
5205: my ($token,$server)=@_;
5206: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5207: return &reply("tmpdel:$token",$server);
5208: }
5209:
5210: # -------------------------------------------------- portfolio access checking
5211:
5212: sub portfolio_access {
5213: my ($requrl) = @_;
5214: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5215: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5216: if ($result) {
5217: my %setters;
5218: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5219: my ($startblock,$endblock) =
5220: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5221: if ($startblock && $endblock) {
5222: return 'B';
5223: }
5224: } else {
5225: my ($startblock,$endblock) =
5226: &Apache::loncommon::blockcheck(\%setters,'port');
5227: if ($startblock && $endblock) {
5228: return 'B';
5229: }
5230: }
5231: }
5232: if ($result eq 'ok') {
5233: return 'F';
5234: } elsif ($result =~ /^[^:]+:guest_/) {
5235: return 'A';
5236: }
5237: return '';
5238: }
5239:
5240: sub get_portfolio_access {
5241: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5242:
5243: if (!ref($access_hash)) {
5244: my $current_perms = &get_portfile_permissions($udom,$unum);
5245: my %access_controls = &get_access_controls($current_perms,$group,
5246: $file_name);
5247: $access_hash = $access_controls{$file_name};
5248: }
5249:
5250: my ($public,$guest,@domains,@users,@courses,@groups);
5251: my $now = time;
5252: if (ref($access_hash) eq 'HASH') {
5253: foreach my $key (keys(%{$access_hash})) {
5254: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5255: if ($start > $now) {
5256: next;
5257: }
5258: if ($end && $end<$now) {
5259: next;
5260: }
5261: if ($scope eq 'public') {
5262: $public = $key;
5263: last;
5264: } elsif ($scope eq 'guest') {
5265: $guest = $key;
5266: } elsif ($scope eq 'domains') {
5267: push(@domains,$key);
5268: } elsif ($scope eq 'users') {
5269: push(@users,$key);
5270: } elsif ($scope eq 'course') {
5271: push(@courses,$key);
5272: } elsif ($scope eq 'group') {
5273: push(@groups,$key);
5274: }
5275: }
5276: if ($public) {
5277: return 'ok';
5278: }
5279: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5280: if ($guest) {
5281: return $guest;
5282: }
5283: } else {
5284: if (@domains > 0) {
5285: foreach my $domkey (@domains) {
5286: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5287: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5288: return 'ok';
5289: }
5290: }
5291: }
5292: }
5293: if (@users > 0) {
5294: foreach my $userkey (@users) {
5295: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5296: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5297: if (ref($item) eq 'HASH') {
5298: if (($item->{'uname'} eq $env{'user.name'}) &&
5299: ($item->{'udom'} eq $env{'user.domain'})) {
5300: return 'ok';
5301: }
5302: }
5303: }
5304: }
5305: }
5306: }
5307: my %roleshash;
5308: my @courses_and_groups = @courses;
5309: push(@courses_and_groups,@groups);
5310: if (@courses_and_groups > 0) {
5311: my (%allgroups,%allroles);
5312: my ($start,$end,$role,$sec,$group);
5313: foreach my $envkey (%env) {
5314: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5315: my $cid = $2.'_'.$3;
5316: if ($1 eq 'gr') {
5317: $group = $4;
5318: $allgroups{$cid}{$group} = $env{$envkey};
5319: } else {
5320: if ($4 eq '') {
5321: $sec = 'none';
5322: } else {
5323: $sec = $4;
5324: }
5325: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5326: }
5327: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5328: my $cid = $2.'_'.$3;
5329: if ($4 eq '') {
5330: $sec = 'none';
5331: } else {
5332: $sec = $4;
5333: }
5334: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5335: }
5336: }
5337: if (keys(%allroles) == 0) {
5338: return;
5339: }
5340: foreach my $key (@courses_and_groups) {
5341: my %content = %{$$access_hash{$key}};
5342: my $cnum = $content{'number'};
5343: my $cdom = $content{'domain'};
5344: my $cid = $cdom.'_'.$cnum;
5345: if (!exists($allroles{$cid})) {
5346: next;
5347: }
5348: foreach my $role_id (keys(%{$content{'roles'}})) {
5349: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5350: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5351: my @status = @{$content{'roles'}{$role_id}{'access'}};
5352: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5353: foreach my $role (keys(%{$allroles{$cid}})) {
5354: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5355: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5356: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5357: if (grep/^all$/,@sections) {
5358: return 'ok';
5359: } else {
5360: if (grep/^$sec$/,@sections) {
5361: return 'ok';
5362: }
5363: }
5364: }
5365: }
5366: if (keys(%{$allgroups{$cid}}) == 0) {
5367: if (grep/^none$/,@groups) {
5368: return 'ok';
5369: }
5370: } else {
5371: if (grep/^all$/,@groups) {
5372: return 'ok';
5373: }
5374: foreach my $group (keys(%{$allgroups{$cid}})) {
5375: if (grep/^$group$/,@groups) {
5376: return 'ok';
5377: }
5378: }
5379: }
5380: }
5381: }
5382: }
5383: }
5384: }
5385: if ($guest) {
5386: return $guest;
5387: }
5388: }
5389: }
5390: return;
5391: }
5392:
5393: sub course_group_datechecker {
5394: my ($dates,$now,$status) = @_;
5395: my ($start,$end) = split(/\./,$dates);
5396: if (!$start && !$end) {
5397: return 'ok';
5398: }
5399: if (grep/^active$/,@{$status}) {
5400: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5401: return 'ok';
5402: }
5403: }
5404: if (grep/^previous$/,@{$status}) {
5405: if ($end > $now ) {
5406: return 'ok';
5407: }
5408: }
5409: if (grep/^future$/,@{$status}) {
5410: if ($start > $now) {
5411: return 'ok';
5412: }
5413: }
5414: return;
5415: }
5416:
5417: sub parse_portfolio_url {
5418: my ($url) = @_;
5419:
5420: my ($type,$udom,$unum,$group,$file_name);
5421:
5422: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5423: $type = 1;
5424: $udom = $1;
5425: $unum = $2;
5426: $file_name = $3;
5427: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5428: $type = 2;
5429: $udom = $1;
5430: $unum = $2;
5431: $group = $3;
5432: $file_name = $3.'/'.$4;
5433: }
5434: if (wantarray) {
5435: return ($type,$udom,$unum,$file_name,$group);
5436: }
5437: return $type;
5438: }
5439:
5440: sub is_portfolio_url {
5441: my ($url) = @_;
5442: return scalar(&parse_portfolio_url($url));
5443: }
5444:
5445: sub is_portfolio_file {
5446: my ($file) = @_;
5447: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5448: return 1;
5449: }
5450: return;
5451: }
5452:
5453: sub usertools_access {
5454: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5455: my ($access,%tools);
5456: if ($context eq '') {
5457: $context = 'tools';
5458: }
5459: if ($context eq 'requestcourses') {
5460: %tools = (
5461: official => 1,
5462: unofficial => 1,
5463: community => 1,
5464: );
5465: } else {
5466: %tools = (
5467: aboutme => 1,
5468: blog => 1,
5469: portfolio => 1,
5470: );
5471: }
5472: return if (!defined($tools{$tool}));
5473:
5474: if ((!defined($udom)) || (!defined($uname))) {
5475: $udom = $env{'user.domain'};
5476: $uname = $env{'user.name'};
5477: }
5478:
5479: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5480: if ($action ne 'reload') {
5481: if ($context eq 'requestcourses') {
5482: return $env{'environment.canrequest.'.$tool};
5483: } else {
5484: return $env{'environment.availabletools.'.$tool};
5485: }
5486: }
5487: }
5488:
5489: my ($toolstatus,$inststatus);
5490:
5491: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5492: ($action ne 'reload')) {
5493: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5494: $inststatus = $env{'environment.inststatus'};
5495: } else {
5496: if (ref($userenvref) eq 'HASH') {
5497: $toolstatus = $userenvref->{$context.'.'.$tool};
5498: $inststatus = $userenvref->{'inststatus'};
5499: } else {
5500: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5501: $toolstatus = $userenv{$context.'.'.$tool};
5502: $inststatus = $userenv{'inststatus'};
5503: }
5504: }
5505:
5506: if ($toolstatus ne '') {
5507: if ($toolstatus) {
5508: $access = 1;
5509: } else {
5510: $access = 0;
5511: }
5512: return $access;
5513: }
5514:
5515: my ($is_adv,%domdef);
5516: if (ref($is_advref) eq 'HASH') {
5517: $is_adv = $is_advref->{'is_adv'};
5518: } else {
5519: $is_adv = &is_advanced_user($udom,$uname);
5520: }
5521: if (ref($domdefref) eq 'HASH') {
5522: %domdef = %{$domdefref};
5523: } else {
5524: %domdef = &get_domain_defaults($udom);
5525: }
5526: if (ref($domdef{$tool}) eq 'HASH') {
5527: if ($is_adv) {
5528: if ($domdef{$tool}{'_LC_adv'} ne '') {
5529: if ($domdef{$tool}{'_LC_adv'}) {
5530: $access = 1;
5531: } else {
5532: $access = 0;
5533: }
5534: return $access;
5535: }
5536: }
5537: if ($inststatus ne '') {
5538: my ($hasaccess,$hasnoaccess);
5539: foreach my $affiliation (split(/:/,$inststatus)) {
5540: if ($domdef{$tool}{$affiliation} ne '') {
5541: if ($domdef{$tool}{$affiliation}) {
5542: $hasaccess = 1;
5543: } else {
5544: $hasnoaccess = 1;
5545: }
5546: }
5547: }
5548: if ($hasaccess || $hasnoaccess) {
5549: if ($hasaccess) {
5550: $access = 1;
5551: } elsif ($hasnoaccess) {
5552: $access = 0;
5553: }
5554: return $access;
5555: }
5556: } else {
5557: if ($domdef{$tool}{'default'} ne '') {
5558: if ($domdef{$tool}{'default'}) {
5559: $access = 1;
5560: } elsif ($domdef{$tool}{'default'} == 0) {
5561: $access = 0;
5562: }
5563: return $access;
5564: }
5565: }
5566: } else {
5567: if ($context eq 'tools') {
5568: $access = 1;
5569: } else {
5570: $access = 0;
5571: }
5572: return $access;
5573: }
5574: }
5575:
5576: sub is_course_owner {
5577: my ($cdom,$cnum,$udom,$uname) = @_;
5578: if (($udom eq '') || ($uname eq '')) {
5579: $udom = $env{'user.domain'};
5580: $uname = $env{'user.name'};
5581: }
5582: unless (($udom eq '') || ($uname eq '')) {
5583: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5584: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5585: return 1;
5586: } else {
5587: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5588: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5589: return 1;
5590: }
5591: }
5592: }
5593: }
5594: return;
5595: }
5596:
5597: sub is_advanced_user {
5598: my ($udom,$uname) = @_;
5599: if ($udom ne '' && $uname ne '') {
5600: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5601: if (wantarray) {
5602: return ($env{'user.adv'},$env{'user.author'});
5603: } else {
5604: return $env{'user.adv'};
5605: }
5606: }
5607: }
5608: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5609: my %allroles;
5610: my ($is_adv,$is_author);
5611: foreach my $role (keys(%roleshash)) {
5612: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5613: my $area = '/'.$tdomain.'/'.$trest;
5614: if ($sec ne '') {
5615: $area .= '/'.$sec;
5616: }
5617: if (($area ne '') && ($trole ne '')) {
5618: my $spec=$trole.'.'.$area;
5619: if ($trole =~ /^cr\//) {
5620: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5621: } elsif ($trole ne 'gr') {
5622: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5623: }
5624: if ($trole eq 'au') {
5625: $is_author = 1;
5626: }
5627: }
5628: }
5629: foreach my $role (keys(%allroles)) {
5630: last if ($is_adv);
5631: foreach my $item (split(/:/,$allroles{$role})) {
5632: if ($item ne '') {
5633: my ($privilege,$restrictions)=split(/&/,$item);
5634: if ($privilege eq 'adv') {
5635: $is_adv = 1;
5636: last;
5637: }
5638: }
5639: }
5640: }
5641: if (wantarray) {
5642: return ($is_adv,$is_author);
5643: }
5644: return $is_adv;
5645: }
5646:
5647: sub check_can_request {
5648: my ($dom,$can_request,$request_domains) = @_;
5649: my $canreq = 0;
5650: my ($types,$typename) = &Apache::loncommon::course_types();
5651: my @options = ('approval','validate','autolimit');
5652: my $optregex = join('|',@options);
5653: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5654: foreach my $type (@{$types}) {
5655: if (&usertools_access($env{'user.name'},
5656: $env{'user.domain'},
5657: $type,undef,'requestcourses')) {
5658: $canreq ++;
5659: if (ref($request_domains) eq 'HASH') {
5660: push(@{$request_domains->{$type}},$env{'user.domain'});
5661: }
5662: if ($dom eq $env{'user.domain'}) {
5663: $can_request->{$type} = 1;
5664: }
5665: }
5666: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5667: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5668: if (@curr > 0) {
5669: foreach my $item (@curr) {
5670: if (ref($request_domains) eq 'HASH') {
5671: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5672: if ($otherdom ne '') {
5673: if (ref($request_domains->{$type}) eq 'ARRAY') {
5674: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5675: push(@{$request_domains->{$type}},$otherdom);
5676: }
5677: } else {
5678: push(@{$request_domains->{$type}},$otherdom);
5679: }
5680: }
5681: }
5682: }
5683: unless($dom eq $env{'user.domain'}) {
5684: $canreq ++;
5685: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5686: $can_request->{$type} = 1;
5687: }
5688: }
5689: }
5690: }
5691: }
5692: }
5693: return $canreq;
5694: }
5695:
5696: # ---------------------------------------------- Custom access rule evaluation
5697:
5698: sub customaccess {
5699: my ($priv,$uri)=@_;
5700: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5701: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5702: $udom = &LONCAPA::clean_domain($udom);
5703: $ucrs = &LONCAPA::clean_username($ucrs);
5704: my $access=0;
5705: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5706: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5707: if ($type eq 'user') {
5708: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5709: my ($tdom,$tuname)=split(m{/},$scope);
5710: if ($tdom) {
5711: if ($tdom ne $env{'user.domain'}) { next; }
5712: }
5713: if ($tuname) {
5714: if ($tuname ne $env{'user.name'}) { next; }
5715: }
5716: $access=($effect eq 'allow');
5717: last;
5718: }
5719: } else {
5720: if ($role) {
5721: if ($role ne $urole) { next; }
5722: }
5723: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5724: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5725: if ($tdom) {
5726: if ($tdom ne $udom) { next; }
5727: }
5728: if ($tcrs) {
5729: if ($tcrs ne $ucrs) { next; }
5730: }
5731: if ($tsec) {
5732: if ($tsec ne $usec) { next; }
5733: }
5734: $access=($effect eq 'allow');
5735: last;
5736: }
5737: if ($realm eq '' && $role eq '') {
5738: $access=($effect eq 'allow');
5739: }
5740: }
5741: }
5742: return $access;
5743: }
5744:
5745: # ------------------------------------------------- Check for a user privilege
5746:
5747: sub allowed {
5748: my ($priv,$uri,$symb,$role)=@_;
5749: my $ver_orguri=$uri;
5750: $uri=&deversion($uri);
5751: my $orguri=$uri;
5752: $uri=&declutter($uri);
5753:
5754: if ($priv eq 'evb') {
5755: # Evade communication block restrictions for specified role in a course
5756: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5757: return $1;
5758: } else {
5759: return;
5760: }
5761: }
5762:
5763: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5764: # Free bre access to adm and meta resources
5765: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5766: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5767: && ($priv eq 'bre')) {
5768: return 'F';
5769: }
5770:
5771: # Free bre access to user's own portfolio contents
5772: my ($space,$domain,$name,@dir)=split('/',$uri);
5773: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5774: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5775: my %setters;
5776: my ($startblock,$endblock) =
5777: &Apache::loncommon::blockcheck(\%setters,'port');
5778: if ($startblock && $endblock) {
5779: return 'B';
5780: } else {
5781: return 'F';
5782: }
5783: }
5784:
5785: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5786: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5787: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5788: if (exists($env{'request.course.id'})) {
5789: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5790: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5791: if (($domain eq $cdom) && ($name eq $cnum)) {
5792: my $courseprivid=$env{'request.course.id'};
5793: $courseprivid=~s/\_/\//;
5794: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5795: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5796: return $1;
5797: } else {
5798: if ($env{'request.course.sec'}) {
5799: $courseprivid.='/'.$env{'request.course.sec'};
5800: }
5801: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5802: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5803: return $2;
5804: }
5805: }
5806: }
5807: }
5808: }
5809:
5810: # Free bre to public access
5811:
5812: if ($priv eq 'bre') {
5813: my $copyright=&metadata($uri,'copyright');
5814: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5815: return 'F';
5816: }
5817: if ($copyright eq 'priv') {
5818: $uri=~/([^\/]+)\/([^\/]+)\//;
5819: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5820: return '';
5821: }
5822: }
5823: if ($copyright eq 'domain') {
5824: $uri=~/([^\/]+)\/([^\/]+)\//;
5825: unless (($env{'user.domain'} eq $1) ||
5826: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5827: return '';
5828: }
5829: }
5830: if ($env{'request.role'}=~ /li\.\//) {
5831: # Library role, so allow browsing of resources in this domain.
5832: return 'F';
5833: }
5834: if ($copyright eq 'custom') {
5835: unless (&customaccess($priv,$uri)) { return ''; }
5836: }
5837: }
5838: # Domain coordinator is trying to create a course
5839: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5840: # uri is the requested domain in this case.
5841: # comparison to 'request.role.domain' shows if the user has selected
5842: # a role of dc for the domain in question.
5843: return 'F' if ($uri eq $env{'request.role.domain'});
5844: }
5845:
5846: my $thisallowed='';
5847: my $statecond=0;
5848: my $courseprivid='';
5849:
5850: my $ownaccess;
5851: # Community Coordinator or Assistant Co-author browsing resource space.
5852: if (($priv eq 'bro') && ($env{'user.author'})) {
5853: if ($uri eq '') {
5854: $ownaccess = 1;
5855: } else {
5856: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5857: my $udom = $env{'user.domain'};
5858: my $uname = $env{'user.name'};
5859: if ($uri =~ m{^\Q$udom\E/?$}) {
5860: $ownaccess = 1;
5861: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5862: unless ($uri =~ m{\.\./}) {
5863: $ownaccess = 1;
5864: }
5865: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5866: my $now = time;
5867: if ($uri =~ m{^([^/]+)/?$}) {
5868: my $adom = $1;
5869: foreach my $key (keys(%env)) {
5870: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5871: my ($start,$end) = split('.',$env{$key});
5872: if (($now >= $start) && (!$end || $end < $now)) {
5873: $ownaccess = 1;
5874: last;
5875: }
5876: }
5877: }
5878: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5879: my $adom = $1;
5880: my $aname = $2;
5881: foreach my $role ('ca','aa') {
5882: if ($env{"user.role.$role./$adom/$aname"}) {
5883: my ($start,$end) =
5884: split('.',$env{"user.role.$role./$adom/$aname"});
5885: if (($now >= $start) && (!$end || $end < $now)) {
5886: $ownaccess = 1;
5887: last;
5888: }
5889: }
5890: }
5891: }
5892: }
5893: }
5894: }
5895: }
5896:
5897: # Course
5898:
5899: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5900: unless (($priv eq 'bro') && (!$ownaccess)) {
5901: $thisallowed.=$1;
5902: }
5903: }
5904:
5905: # Domain
5906:
5907: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5908: =~/\Q$priv\E\&([^\:]*)/) {
5909: unless (($priv eq 'bro') && (!$ownaccess)) {
5910: $thisallowed.=$1;
5911: }
5912: }
5913:
5914: # User who is not author or co-author might still be able to edit
5915: # resource of an author in the domain (e.g., if Domain Coordinator).
5916: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
5917: (&allowed('mdc',$env{'request.course.id'}))) {
5918: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
5919: $thisallowed.=$1;
5920: }
5921: }
5922:
5923: # Course: uri itself is a course
5924: my $courseuri=$uri;
5925: $courseuri=~s/\_(\d)/\/$1/;
5926: $courseuri=~s/^([^\/])/\/$1/;
5927:
5928: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5929: =~/\Q$priv\E\&([^\:]*)/) {
5930: unless (($priv eq 'bro') && (!$ownaccess)) {
5931: $thisallowed.=$1;
5932: }
5933: }
5934:
5935: # URI is an uploaded document for this course, default permissions don't matter
5936: # not allowing 'edit' access (editupload) to uploaded course docs
5937: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5938: $thisallowed='';
5939: my ($match)=&is_on_map($uri);
5940: if ($match) {
5941: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5942: =~/\Q$priv\E\&([^\:]*)/) {
5943: $thisallowed.=$1;
5944: }
5945: } else {
5946: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5947: if ($refuri) {
5948: if ($refuri =~ m|^/adm/|) {
5949: $thisallowed='F';
5950: } else {
5951: $refuri=&declutter($refuri);
5952: my ($match) = &is_on_map($refuri);
5953: if ($match) {
5954: $thisallowed='F';
5955: }
5956: }
5957: }
5958: }
5959: }
5960:
5961: if ($priv eq 'bre'
5962: && $thisallowed ne 'F'
5963: && $thisallowed ne '2'
5964: && &is_portfolio_url($uri)) {
5965: $thisallowed = &portfolio_access($uri);
5966: }
5967:
5968: # Full access at system, domain or course-wide level? Exit.
5969: if ($thisallowed=~/F/) {
5970: return 'F';
5971: }
5972:
5973: # If this is generating or modifying users, exit with special codes
5974:
5975: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5976: if (($priv eq 'cca') || ($priv eq 'caa')) {
5977: my ($audom,$auname)=split('/',$uri);
5978: # no author name given, so this just checks on the general right to make a co-author in this domain
5979: unless ($auname) { return $thisallowed; }
5980: # an author name is given, so we are about to actually make a co-author for a certain account
5981: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5982: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5983: ($audom ne $env{'request.role.domain'}))) { return ''; }
5984: }
5985: return $thisallowed;
5986: }
5987: #
5988: # Gathered so far: system, domain and course wide privileges
5989: #
5990: # Course: See if uri or referer is an individual resource that is part of
5991: # the course
5992:
5993: if ($env{'request.course.id'}) {
5994:
5995: $courseprivid=$env{'request.course.id'};
5996: if ($env{'request.course.sec'}) {
5997: $courseprivid.='/'.$env{'request.course.sec'};
5998: }
5999: $courseprivid=~s/\_/\//;
6000: my $checkreferer=1;
6001: my ($match,$cond)=&is_on_map($uri);
6002: if ($match) {
6003: $statecond=$cond;
6004: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6005: =~/\Q$priv\E\&([^\:]*)/) {
6006: $thisallowed.=$1;
6007: $checkreferer=0;
6008: }
6009: }
6010:
6011: if ($checkreferer) {
6012: my $refuri=$env{'httpref.'.$orguri};
6013: unless ($refuri) {
6014: foreach my $key (keys(%env)) {
6015: if ($key=~/^httpref\..*\*/) {
6016: my $pattern=$key;
6017: $pattern=~s/^httpref\.\/res\///;
6018: $pattern=~s/\*/\[\^\/\]\+/g;
6019: $pattern=~s/\//\\\//g;
6020: if ($orguri=~/$pattern/) {
6021: $refuri=$env{$key};
6022: }
6023: }
6024: }
6025: }
6026:
6027: if ($refuri) {
6028: $refuri=&declutter($refuri);
6029: my ($match,$cond)=&is_on_map($refuri);
6030: if ($match) {
6031: my $refstatecond=$cond;
6032: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6033: =~/\Q$priv\E\&([^\:]*)/) {
6034: $thisallowed.=$1;
6035: $uri=$refuri;
6036: $statecond=$refstatecond;
6037: }
6038: }
6039: }
6040: }
6041: }
6042:
6043: #
6044: # Gathered now: all privileges that could apply, and condition number
6045: #
6046: #
6047: # Full or no access?
6048: #
6049:
6050: if ($thisallowed=~/F/) {
6051: return 'F';
6052: }
6053:
6054: unless ($thisallowed) {
6055: return '';
6056: }
6057:
6058: # Restrictions exist, deal with them
6059: #
6060: # C:according to course preferences
6061: # R:according to resource settings
6062: # L:unless locked
6063: # X:according to user session state
6064: #
6065:
6066: # Possibly locked functionality, check all courses
6067: # Locks might take effect only after 10 minutes cache expiration for other
6068: # courses, and 2 minutes for current course
6069:
6070: my $envkey;
6071: if ($thisallowed=~/L/) {
6072: foreach $envkey (keys(%env)) {
6073: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6074: my $courseid=$2;
6075: my $roleid=$1.'.'.$2;
6076: $courseid=~s/^\///;
6077: my $expiretime=600;
6078: if ($env{'request.role'} eq $roleid) {
6079: $expiretime=120;
6080: }
6081: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6082: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6083: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6084: &coursedescription($courseid,{'freshen_cache' => 1});
6085: }
6086: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6087: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6088: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6089: &log($env{'user.domain'},$env{'user.name'},
6090: $env{'user.home'},
6091: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6092: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6093: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6094: return '';
6095: }
6096: }
6097: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6098: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6099: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6100: &log($env{'user.domain'},$env{'user.name'},
6101: $env{'user.home'},
6102: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6103: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6104: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6105: return '';
6106: }
6107: }
6108: }
6109: }
6110: }
6111:
6112: #
6113: # Rest of the restrictions depend on selected course
6114: #
6115:
6116: unless ($env{'request.course.id'}) {
6117: if ($thisallowed eq 'A') {
6118: return 'A';
6119: } elsif ($thisallowed eq 'B') {
6120: return 'B';
6121: } else {
6122: return '1';
6123: }
6124: }
6125:
6126: #
6127: # Now user is definitely in a course
6128: #
6129:
6130:
6131: # Course preferences
6132:
6133: if ($thisallowed=~/C/) {
6134: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6135: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6136: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6137: =~/\Q$rolecode\E/) {
6138: if (($priv ne 'pch') && ($priv ne 'plc')) {
6139: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6140: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6141: $env{'request.course.id'});
6142: }
6143: return '';
6144: }
6145:
6146: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6147: =~/\Q$unamedom\E/) {
6148: if (($priv ne 'pch') && ($priv ne 'plc')) {
6149: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6150: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6151: $env{'request.course.id'});
6152: }
6153: return '';
6154: }
6155: }
6156:
6157: # Resource preferences
6158:
6159: if ($thisallowed=~/R/) {
6160: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6161: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6162: if (($priv ne 'pch') && ($priv ne 'plc')) {
6163: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6164: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6165: }
6166: return '';
6167: }
6168: }
6169:
6170: # Restricted by state or randomout?
6171:
6172: if ($thisallowed=~/X/) {
6173: if ($env{'acc.randomout'}) {
6174: if (!$symb) { $symb=&symbread($uri,1); }
6175: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6176: return '';
6177: }
6178: }
6179: if (&condval($statecond)) {
6180: return '2';
6181: } else {
6182: return '';
6183: }
6184: }
6185:
6186: if ($thisallowed eq 'A') {
6187: return 'A';
6188: } elsif ($thisallowed eq 'B') {
6189: return 'B';
6190: }
6191: return 'F';
6192: }
6193: #
6194: # Removes the versino from a URI and
6195: # splits it in to its filename and path to the filename.
6196: # Seems like File::Basename could have done this more clearly.
6197: # Parameters:
6198: # $uri - input URI
6199: # Returns:
6200: # Two element list consisting of
6201: # $pathname - the URI up to and excluding the trailing /
6202: # $filename - The part of the URI following the last /
6203: # NOTE:
6204: # Another realization of this is simply:
6205: # use File::Basename;
6206: # ...
6207: # $uri = shift;
6208: # $filename = basename($uri);
6209: # $path = dirname($uri);
6210: # return ($filename, $path);
6211: #
6212: # The implementation below is probably faster however.
6213: #
6214: sub split_uri_for_cond {
6215: my $uri=&deversion(&declutter(shift));
6216: my @uriparts=split(/\//,$uri);
6217: my $filename=pop(@uriparts);
6218: my $pathname=join('/',@uriparts);
6219: return ($pathname,$filename);
6220: }
6221: # --------------------------------------------------- Is a resource on the map?
6222:
6223: sub is_on_map {
6224: my ($pathname,$filename) = &split_uri_for_cond(shift);
6225: #Trying to find the conditional for the file
6226: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6227: /\&\Q$filename\E\:([\d\|]+)\&/);
6228: if ($match) {
6229: return (1,$1);
6230: } else {
6231: return (0,0);
6232: }
6233: }
6234:
6235: # --------------------------------------------------------- Get symb from alias
6236:
6237: sub get_symb_from_alias {
6238: my $symb=shift;
6239: my ($map,$resid,$url)=&decode_symb($symb);
6240: # Already is a symb
6241: if ($url) { return $symb; }
6242: # Must be an alias
6243: my $aliassymb='';
6244: my %bighash;
6245: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6246: &GDBM_READER(),0640)) {
6247: my $rid=$bighash{'mapalias_'.$symb};
6248: if ($rid) {
6249: my ($mapid,$resid)=split(/\./,$rid);
6250: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6251: $resid,$bighash{'src_'.$rid});
6252: }
6253: untie %bighash;
6254: }
6255: return $aliassymb;
6256: }
6257:
6258: # ----------------------------------------------------------------- Define Role
6259:
6260: sub definerole {
6261: if (allowed('mcr','/')) {
6262: my ($rolename,$sysrole,$domrole,$courole)=@_;
6263: foreach my $role (split(':',$sysrole)) {
6264: my ($crole,$cqual)=split(/\&/,$role);
6265: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6266: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6267: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6268: return "refused:s:$crole&$cqual";
6269: }
6270: }
6271: }
6272: foreach my $role (split(':',$domrole)) {
6273: my ($crole,$cqual)=split(/\&/,$role);
6274: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6275: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6276: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6277: return "refused:d:$crole&$cqual";
6278: }
6279: }
6280: }
6281: foreach my $role (split(':',$courole)) {
6282: my ($crole,$cqual)=split(/\&/,$role);
6283: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6284: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6285: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6286: return "refused:c:$crole&$cqual";
6287: }
6288: }
6289: }
6290: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6291: "$env{'user.domain'}:$env{'user.name'}:".
6292: "rolesdef_$rolename=".
6293: escape($sysrole.'_'.$domrole.'_'.$courole);
6294: return reply($command,$env{'user.home'});
6295: } else {
6296: return 'refused';
6297: }
6298: }
6299:
6300: # ---------------- Make a metadata query against the network of library servers
6301:
6302: sub metadata_query {
6303: my ($query,$custom,$customshow,$server_array)=@_;
6304: my %rhash;
6305: my %libserv = &all_library();
6306: my @server_list = (defined($server_array) ? @$server_array
6307: : keys(%libserv) );
6308: for my $server (@server_list) {
6309: unless ($custom or $customshow) {
6310: my $reply=&reply("querysend:".&escape($query),$server);
6311: $rhash{$server}=$reply;
6312: }
6313: else {
6314: my $reply=&reply("querysend:".&escape($query).':'.
6315: &escape($custom).':'.&escape($customshow),
6316: $server);
6317: $rhash{$server}=$reply;
6318: }
6319: }
6320: return \%rhash;
6321: }
6322:
6323: # ----------------------------------------- Send log queries and wait for reply
6324:
6325: sub log_query {
6326: my ($uname,$udom,$query,%filters)=@_;
6327: my $uhome=&homeserver($uname,$udom);
6328: if ($uhome eq 'no_host') { return 'error: no_host'; }
6329: my $uhost=&hostname($uhome);
6330: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6331: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6332: $uhome);
6333: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6334: return get_query_reply($queryid);
6335: }
6336:
6337: # -------------------------- Update MySQL table for portfolio file
6338:
6339: sub update_portfolio_table {
6340: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6341: if ($group ne '') {
6342: $file_name =~s /^\Q$group\E//;
6343: }
6344: my $homeserver = &homeserver($uname,$udom);
6345: my $queryid=
6346: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6347: ':'.&escape($file_name).':'.$action,$homeserver);
6348: my $reply = &get_query_reply($queryid);
6349: return $reply;
6350: }
6351:
6352: # -------------------------- Update MySQL allusers table
6353:
6354: sub update_allusers_table {
6355: my ($uname,$udom,$names) = @_;
6356: my $homeserver = &homeserver($uname,$udom);
6357: my $queryid=
6358: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6359: 'lastname='.&escape($names->{'lastname'}).'%%'.
6360: 'firstname='.&escape($names->{'firstname'}).'%%'.
6361: 'middlename='.&escape($names->{'middlename'}).'%%'.
6362: 'generation='.&escape($names->{'generation'}).'%%'.
6363: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6364: 'id='.&escape($names->{'id'}),$homeserver);
6365: return;
6366: }
6367:
6368: # ------- Request retrieval of institutional classlists for course(s)
6369:
6370: sub fetch_enrollment_query {
6371: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6372: my $homeserver;
6373: my $maxtries = 1;
6374: if ($context eq 'automated') {
6375: $homeserver = $perlvar{'lonHostID'};
6376: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6377: } else {
6378: $homeserver = &homeserver($cnum,$dom);
6379: }
6380: my $host=&hostname($homeserver);
6381: my $cmd = '';
6382: foreach my $affiliate (keys(%{$affiliatesref})) {
6383: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6384: }
6385: $cmd =~ s/%%$//;
6386: $cmd = &escape($cmd);
6387: my $query = 'fetchenrollment';
6388: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6389: unless ($queryid=~/^\Q$host\E\_/) {
6390: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6391: return 'error: '.$queryid;
6392: }
6393: my $reply = &get_query_reply($queryid);
6394: my $tries = 1;
6395: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6396: $reply = &get_query_reply($queryid);
6397: $tries ++;
6398: }
6399: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6400: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6401: } else {
6402: my @responses = split(/:/,$reply);
6403: if ($homeserver eq $perlvar{'lonHostID'}) {
6404: foreach my $line (@responses) {
6405: my ($key,$value) = split(/=/,$line,2);
6406: $$replyref{$key} = $value;
6407: }
6408: } else {
6409: my $pathname = LONCAPA::tempdir();
6410: foreach my $line (@responses) {
6411: my ($key,$value) = split(/=/,$line);
6412: $$replyref{$key} = $value;
6413: if ($value > 0) {
6414: foreach my $item (@{$$affiliatesref{$key}}) {
6415: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6416: my $destname = $pathname.'/'.$filename;
6417: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6418: if ($xml_classlist =~ /^error/) {
6419: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6420: } else {
6421: if ( open(FILE,">$destname") ) {
6422: print FILE &unescape($xml_classlist);
6423: close(FILE);
6424: } else {
6425: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6426: }
6427: }
6428: }
6429: }
6430: }
6431: }
6432: return 'ok';
6433: }
6434: return 'error';
6435: }
6436:
6437: sub get_query_reply {
6438: my $queryid=shift;
6439: my $replyfile=LONCAPA::tempdir().$queryid;
6440: my $reply='';
6441: for (1..100) {
6442: sleep 2;
6443: if (-e $replyfile.'.end') {
6444: if (open(my $fh,$replyfile)) {
6445: $reply = join('',<$fh>);
6446: close($fh);
6447: } else { return 'error: reply_file_error'; }
6448: return &unescape($reply);
6449: }
6450: }
6451: return 'timeout:'.$queryid;
6452: }
6453:
6454: sub courselog_query {
6455: #
6456: # possible filters:
6457: # url: url or symb
6458: # username
6459: # domain
6460: # action: view, submit, grade
6461: # start: timestamp
6462: # end: timestamp
6463: #
6464: my (%filters)=@_;
6465: unless ($env{'request.course.id'}) { return 'no_course'; }
6466: if ($filters{'url'}) {
6467: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6468: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6469: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6470: }
6471: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6472: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6473: return &log_query($cname,$cdom,'courselog',%filters);
6474: }
6475:
6476: sub userlog_query {
6477: #
6478: # possible filters:
6479: # action: log check role
6480: # start: timestamp
6481: # end: timestamp
6482: #
6483: my ($uname,$udom,%filters)=@_;
6484: return &log_query($uname,$udom,'userlog',%filters);
6485: }
6486:
6487: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6488:
6489: sub auto_run {
6490: my ($cnum,$cdom) = @_;
6491: my $response = 0;
6492: my $settings;
6493: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6494: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6495: $settings = $domconfig{'autoenroll'};
6496: if ($settings->{'run'} eq '1') {
6497: $response = 1;
6498: }
6499: } else {
6500: my $homeserver;
6501: if (&is_course($cdom,$cnum)) {
6502: $homeserver = &homeserver($cnum,$cdom);
6503: } else {
6504: $homeserver = &domain($cdom,'primary');
6505: }
6506: if ($homeserver ne 'no_host') {
6507: $response = &reply('autorun:'.$cdom,$homeserver);
6508: }
6509: }
6510: return $response;
6511: }
6512:
6513: sub auto_get_sections {
6514: my ($cnum,$cdom,$inst_coursecode) = @_;
6515: my $homeserver;
6516: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6517: $homeserver = &homeserver($cnum,$cdom);
6518: }
6519: if (!defined($homeserver)) {
6520: if ($cdom =~ /^$match_domain$/) {
6521: $homeserver = &domain($cdom,'primary');
6522: }
6523: }
6524: my @secs;
6525: if (defined($homeserver)) {
6526: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6527: unless ($response eq 'refused') {
6528: @secs = split(/:/,$response);
6529: }
6530: }
6531: return @secs;
6532: }
6533:
6534: sub auto_new_course {
6535: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6536: my $homeserver = &homeserver($cnum,$cdom);
6537: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6538: return $response;
6539: }
6540:
6541: sub auto_validate_courseID {
6542: my ($cnum,$cdom,$inst_course_id) = @_;
6543: my $homeserver = &homeserver($cnum,$cdom);
6544: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6545: return $response;
6546: }
6547:
6548: sub auto_validate_instcode {
6549: my ($cnum,$cdom,$instcode,$owner) = @_;
6550: my ($homeserver,$response);
6551: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6552: $homeserver = &homeserver($cnum,$cdom);
6553: }
6554: if (!defined($homeserver)) {
6555: if ($cdom =~ /^$match_domain$/) {
6556: $homeserver = &domain($cdom,'primary');
6557: }
6558: }
6559: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6560: &escape($instcode).':'.&escape($owner),$homeserver));
6561: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6562: return ($outcome,$description);
6563: }
6564:
6565: sub auto_create_password {
6566: my ($cnum,$cdom,$authparam,$udom) = @_;
6567: my ($homeserver,$response);
6568: my $create_passwd = 0;
6569: my $authchk = '';
6570: if ($udom =~ /^$match_domain$/) {
6571: $homeserver = &domain($udom,'primary');
6572: }
6573: if ($homeserver eq '') {
6574: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6575: $homeserver = &homeserver($cnum,$cdom);
6576: }
6577: }
6578: if ($homeserver eq '') {
6579: $authchk = 'nodomain';
6580: } else {
6581: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6582: if ($response eq 'refused') {
6583: $authchk = 'refused';
6584: } else {
6585: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6586: }
6587: }
6588: return ($authparam,$create_passwd,$authchk);
6589: }
6590:
6591: sub auto_photo_permission {
6592: my ($cnum,$cdom,$students) = @_;
6593: my $homeserver = &homeserver($cnum,$cdom);
6594: my ($outcome,$perm_reqd,$conditions) =
6595: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6596: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6597: return (undef,undef);
6598: }
6599: return ($outcome,$perm_reqd,$conditions);
6600: }
6601:
6602: sub auto_checkphotos {
6603: my ($uname,$udom,$pid) = @_;
6604: my $homeserver = &homeserver($uname,$udom);
6605: my ($result,$resulttype);
6606: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6607: &escape($uname).':'.&escape($pid),
6608: $homeserver));
6609: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6610: return (undef,undef);
6611: }
6612: if ($outcome) {
6613: ($result,$resulttype) = split(/:/,$outcome);
6614: }
6615: return ($result,$resulttype);
6616: }
6617:
6618: sub auto_photochoice {
6619: my ($cnum,$cdom) = @_;
6620: my $homeserver = &homeserver($cnum,$cdom);
6621: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6622: &escape($cdom),
6623: $homeserver)));
6624: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6625: return (undef,undef);
6626: }
6627: return ($update,$comment);
6628: }
6629:
6630: sub auto_photoupdate {
6631: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6632: my $homeserver = &homeserver($cnum,$dom);
6633: my $host=&hostname($homeserver);
6634: my $cmd = '';
6635: my $maxtries = 1;
6636: foreach my $affiliate (keys(%{$affiliatesref})) {
6637: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6638: }
6639: $cmd =~ s/%%$//;
6640: $cmd = &escape($cmd);
6641: my $query = 'institutionalphotos';
6642: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6643: unless ($queryid=~/^\Q$host\E\_/) {
6644: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6645: return 'error: '.$queryid;
6646: }
6647: my $reply = &get_query_reply($queryid);
6648: my $tries = 1;
6649: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6650: $reply = &get_query_reply($queryid);
6651: $tries ++;
6652: }
6653: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6654: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6655: } else {
6656: my @responses = split(/:/,$reply);
6657: my $outcome = shift(@responses);
6658: foreach my $item (@responses) {
6659: my ($key,$value) = split(/=/,$item);
6660: $$photo{$key} = $value;
6661: }
6662: return $outcome;
6663: }
6664: return 'error';
6665: }
6666:
6667: sub auto_instcode_format {
6668: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6669: $cat_order) = @_;
6670: my $courses = '';
6671: my @homeservers;
6672: if ($caller eq 'global') {
6673: my %servers = &get_servers($codedom,'library');
6674: foreach my $tryserver (keys(%servers)) {
6675: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6676: push(@homeservers,$tryserver);
6677: }
6678: }
6679: } elsif ($caller eq 'requests') {
6680: if ($codedom =~ /^$match_domain$/) {
6681: my $chome = &domain($codedom,'primary');
6682: unless ($chome eq 'no_host') {
6683: push(@homeservers,$chome);
6684: }
6685: }
6686: } else {
6687: push(@homeservers,&homeserver($caller,$codedom));
6688: }
6689: foreach my $code (keys(%{$instcodes})) {
6690: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6691: }
6692: chop($courses);
6693: my $ok_response = 0;
6694: my $response;
6695: while (@homeservers > 0 && $ok_response == 0) {
6696: my $server = shift(@homeservers);
6697: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6698: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6699: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6700: split(/:/,$response);
6701: %{$codes} = (%{$codes},&str2hash($codes_str));
6702: push(@{$codetitles},&str2array($codetitles_str));
6703: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6704: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6705: $ok_response = 1;
6706: }
6707: }
6708: if ($ok_response) {
6709: return 'ok';
6710: } else {
6711: return $response;
6712: }
6713: }
6714:
6715: sub auto_instcode_defaults {
6716: my ($domain,$returnhash,$code_order) = @_;
6717: my @homeservers;
6718:
6719: my %servers = &get_servers($domain,'library');
6720: foreach my $tryserver (keys(%servers)) {
6721: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6722: push(@homeservers,$tryserver);
6723: }
6724: }
6725:
6726: my $response;
6727: foreach my $server (@homeservers) {
6728: $response=&reply('autoinstcodedefaults:'.$domain,$server);
6729: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6730:
6731: foreach my $pair (split(/\&/,$response)) {
6732: my ($name,$value)=split(/\=/,$pair);
6733: if ($name eq 'code_order') {
6734: @{$code_order} = split(/\&/,&unescape($value));
6735: } else {
6736: $returnhash->{&unescape($name)}=&unescape($value);
6737: }
6738: }
6739: return 'ok';
6740: }
6741:
6742: return $response;
6743: }
6744:
6745: sub auto_possible_instcodes {
6746: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6747: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6748: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6749: return;
6750: }
6751: my (@homeservers,$uhome);
6752: if (defined(&domain($domain,'primary'))) {
6753: $uhome=&domain($domain,'primary');
6754: push(@homeservers,&domain($domain,'primary'));
6755: } else {
6756: my %servers = &get_servers($domain,'library');
6757: foreach my $tryserver (keys(%servers)) {
6758: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6759: push(@homeservers,$tryserver);
6760: }
6761: }
6762: }
6763: my $response;
6764: foreach my $server (@homeservers) {
6765: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6766: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6767: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6768: split(':',$response);
6769: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6770: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
6771: foreach my $item (split('&',$cat_title)) {
6772: my ($name,$value)=split('=',$item);
6773: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
6774: }
6775: foreach my $item (split('&',$cat_order)) {
6776: my ($name,$value)=split('=',$item);
6777: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
6778: }
6779: return 'ok';
6780: }
6781: return $response;
6782: }
6783:
6784: sub auto_courserequest_checks {
6785: my ($dom) = @_;
6786: my ($homeserver,%validations);
6787: if ($dom =~ /^$match_domain$/) {
6788: $homeserver = &domain($dom,'primary');
6789: }
6790: unless ($homeserver eq 'no_host') {
6791: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6792: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6793: my @items = split(/&/,$response);
6794: foreach my $item (@items) {
6795: my ($key,$value) = split('=',$item);
6796: $validations{&unescape($key)} = &thaw_unescape($value);
6797: }
6798: }
6799: }
6800: return %validations;
6801: }
6802:
6803: sub auto_courserequest_validation {
6804: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6805: my ($homeserver,$response);
6806: if ($dom =~ /^$match_domain$/) {
6807: $homeserver = &domain($dom,'primary');
6808: }
6809: unless ($homeserver eq 'no_host') {
6810:
6811: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
6812: ':'.&escape($crstype).':'.&escape($inststatuslist).
6813: ':'.&escape($instcode).':'.&escape($instseclist),
6814: $homeserver));
6815: }
6816: return $response;
6817: }
6818:
6819: sub auto_validate_class_sec {
6820: my ($cdom,$cnum,$owners,$inst_class) = @_;
6821: my $homeserver = &homeserver($cnum,$cdom);
6822: my $ownerlist;
6823: if (ref($owners) eq 'ARRAY') {
6824: $ownerlist = join(',',@{$owners});
6825: } else {
6826: $ownerlist = $owners;
6827: }
6828: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
6829: &escape($ownerlist).':'.$cdom,$homeserver);
6830: return $response;
6831: }
6832:
6833: # ------------------------------------------------------- Course Group routines
6834:
6835: sub get_coursegroups {
6836: my ($cdom,$cnum,$group,$namespace) = @_;
6837: return(&dump($namespace,$cdom,$cnum,$group));
6838: }
6839:
6840: sub modify_coursegroup {
6841: my ($cdom,$cnum,$groupsettings) = @_;
6842: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6843: }
6844:
6845: sub toggle_coursegroup_status {
6846: my ($cdom,$cnum,$group,$action) = @_;
6847: my ($from_namespace,$to_namespace);
6848: if ($action eq 'delete') {
6849: $from_namespace = 'coursegroups';
6850: $to_namespace = 'deleted_groups';
6851: } else {
6852: $from_namespace = 'deleted_groups';
6853: $to_namespace = 'coursegroups';
6854: }
6855: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
6856: if (my $tmp = &error(%curr_group)) {
6857: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6858: return ('read error',$tmp);
6859: } else {
6860: my %savedsettings = %curr_group;
6861: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
6862: my $deloutcome;
6863: if ($result eq 'ok') {
6864: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
6865: } else {
6866: return ('write error',$result);
6867: }
6868: if ($deloutcome eq 'ok') {
6869: return 'ok';
6870: } else {
6871: return ('delete error',$deloutcome);
6872: }
6873: }
6874: }
6875:
6876: sub modify_group_roles {
6877: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
6878: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6879: my $role = 'gr/'.&escape($userprivs);
6880: my ($uname,$udom) = split(/:/,$user);
6881: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
6882: if ($result eq 'ok') {
6883: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6884: }
6885: return $result;
6886: }
6887:
6888: sub modify_coursegroup_membership {
6889: my ($cdom,$cnum,$membership) = @_;
6890: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6891: return $result;
6892: }
6893:
6894: sub get_active_groups {
6895: my ($udom,$uname,$cdom,$cnum) = @_;
6896: my $now = time;
6897: my %groups = ();
6898: foreach my $key (keys(%env)) {
6899: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
6900: my ($start,$end) = split(/\./,$env{$key});
6901: if (($end!=0) && ($end<$now)) { next; }
6902: if (($start!=0) && ($start>$now)) { next; }
6903: if ($1 eq $cdom && $2 eq $cnum) {
6904: $groups{$3} = $env{$key} ;
6905: }
6906: }
6907: }
6908: return %groups;
6909: }
6910:
6911: sub get_group_membership {
6912: my ($cdom,$cnum,$group) = @_;
6913: return(&dump('groupmembership',$cdom,$cnum,$group));
6914: }
6915:
6916: sub get_users_groups {
6917: my ($udom,$uname,$courseid) = @_;
6918: my @usersgroups;
6919: my $cachetime=1800;
6920:
6921: my $hashid="$udom:$uname:$courseid";
6922: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6923: if (defined($cached)) {
6924: @usersgroups = split(/:/,$grouplist);
6925: } else {
6926: $grouplist = '';
6927: my $courseurl = &courseid_to_courseurl($courseid);
6928: my $extra = &freeze_escape({'skipcheck' => 1});
6929: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
6930: my $access_end = $env{'course.'.$courseid.
6931: '.default_enrollment_end_date'};
6932: my $now = time;
6933: foreach my $key (keys(%roleshash)) {
6934: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6935: my $group = $1;
6936: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6937: my $start = $2;
6938: my $end = $1;
6939: if ($start == -1) { next; } # deleted from group
6940: if (($start!=0) && ($start>$now)) { next; }
6941: if (($end!=0) && ($end<$now)) {
6942: if ($access_end && $access_end < $now) {
6943: if ($access_end - $end < 86400) {
6944: push(@usersgroups,$group);
6945: }
6946: }
6947: next;
6948: }
6949: push(@usersgroups,$group);
6950: }
6951: }
6952: }
6953: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6954: $grouplist = join(':',@usersgroups);
6955: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6956: }
6957: return @usersgroups;
6958: }
6959:
6960: sub devalidate_getgroups_cache {
6961: my ($udom,$uname,$cdom,$cnum)=@_;
6962: my $courseid = $cdom.'_'.$cnum;
6963:
6964: my $hashid="$udom:$uname:$courseid";
6965: &devalidate_cache_new('getgroups',$hashid);
6966: }
6967:
6968: # ------------------------------------------------------------------ Plain Text
6969:
6970: sub plaintext {
6971: my ($short,$type,$cid,$forcedefault) = @_;
6972: if ($short =~ m{^cr/}) {
6973: return (split('/',$short))[-1];
6974: }
6975: if (!defined($cid)) {
6976: $cid = $env{'request.course.id'};
6977: }
6978: my %rolenames = (
6979: Course => 'std',
6980: Community => 'alt1',
6981: );
6982: if ($cid ne '') {
6983: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6984: unless ($forcedefault) {
6985: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6986: &Apache::lonlocal::mt_escape(\$roletext);
6987: return &Apache::lonlocal::mt($roletext);
6988: }
6989: }
6990: }
6991: if ((defined($type)) && (defined($rolenames{$type})) &&
6992: (defined($rolenames{$type})) &&
6993: (defined($prp{$short}{$rolenames{$type}}))) {
6994: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6995: } elsif ($cid ne '') {
6996: my $crstype = $env{'course.'.$cid.'.type'};
6997: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6998: (defined($prp{$short}{$rolenames{$crstype}}))) {
6999: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7000: }
7001: }
7002: return &Apache::lonlocal::mt($prp{$short}{'std'});
7003: }
7004:
7005: # ----------------------------------------------------------------- Assign Role
7006:
7007: sub assignrole {
7008: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7009: $context)=@_;
7010: my $mrole;
7011: if ($role =~ /^cr\//) {
7012: my $cwosec=$url;
7013: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7014: unless (&allowed('ccr',$cwosec)) {
7015: my $refused = 1;
7016: if ($context eq 'requestcourses') {
7017: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7018: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7019: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7020: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7021: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7022: if ($crsenv{'internal.courseowner'} eq
7023: $env{'user.name'}.':'.$env{'user.domain'}) {
7024: $refused = '';
7025: }
7026: }
7027: }
7028: }
7029: }
7030: if ($refused) {
7031: &logthis('Refused custom assignrole: '.
7032: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7033: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7034: return 'refused';
7035: }
7036: }
7037: $mrole='cr';
7038: } elsif ($role =~ /^gr\//) {
7039: my $cwogrp=$url;
7040: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7041: unless (&allowed('mdg',$cwogrp)) {
7042: &logthis('Refused group assignrole: '.
7043: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7044: $env{'user.name'}.' at '.$env{'user.domain'});
7045: return 'refused';
7046: }
7047: $mrole='gr';
7048: } else {
7049: my $cwosec=$url;
7050: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7051: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7052: my $refused;
7053: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7054: if (!(&allowed('c'.$role,$url))) {
7055: $refused = 1;
7056: }
7057: } else {
7058: $refused = 1;
7059: }
7060: if ($refused) {
7061: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7062: if (!$selfenroll && $context eq 'course') {
7063: my %crsenv;
7064: if ($role eq 'cc' || $role eq 'co') {
7065: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7066: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7067: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7068: if ($crsenv{'internal.courseowner'} eq
7069: $env{'user.name'}.':'.$env{'user.domain'}) {
7070: $refused = '';
7071: }
7072: }
7073: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7074: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7075: if ($crsenv{'internal.courseowner'} eq
7076: $env{'user.name'}.':'.$env{'user.domain'}) {
7077: $refused = '';
7078: }
7079: }
7080: }
7081: }
7082: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7083: $refused = '';
7084: } elsif ($context eq 'requestcourses') {
7085: my @possroles = ('st','ta','ep','in','cc','co');
7086: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7087: my $wrongcc;
7088: if ($cnum =~ /^$match_community$/) {
7089: $wrongcc = 1 if ($role eq 'cc');
7090: } else {
7091: $wrongcc = 1 if ($role eq 'co');
7092: }
7093: unless ($wrongcc) {
7094: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7095: if ($crsenv{'internal.courseowner'} eq
7096: $env{'user.name'}.':'.$env{'user.domain'}) {
7097: $refused = '';
7098: }
7099: }
7100: }
7101: }
7102: if ($refused) {
7103: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7104: ' '.$role.' '.$end.' '.$start.' by '.
7105: $env{'user.name'}.' at '.$env{'user.domain'});
7106: return 'refused';
7107: }
7108: }
7109: } elsif ($role eq 'au') {
7110: if ($url ne '/'.$udom.'/') {
7111: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7112: ' to assign author role for '.$uname.':'.$udom.
7113: ' in domain: '.$url.' refused (wrong domain).');
7114: return 'refused';
7115: }
7116: }
7117: $mrole=$role;
7118: }
7119: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7120: "$udom:$uname:$url".'_'."$mrole=$role";
7121: if ($end) { $command.='_'.$end; }
7122: if ($start) {
7123: if ($end) {
7124: $command.='_'.$start;
7125: } else {
7126: $command.='_0_'.$start;
7127: }
7128: }
7129: my $origstart = $start;
7130: my $origend = $end;
7131: my $delflag;
7132: # actually delete
7133: if ($deleteflag) {
7134: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7135: # modify command to delete the role
7136: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7137: "$udom:$uname:$url".'_'."$mrole";
7138: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7139: # set start and finish to negative values for userrolelog
7140: $start=-1;
7141: $end=-1;
7142: $delflag = 1;
7143: }
7144: }
7145: # send command
7146: my $answer=&reply($command,&homeserver($uname,$udom));
7147: # log new user role if status is ok
7148: if ($answer eq 'ok') {
7149: &userrolelog($role,$uname,$udom,$url,$start,$end);
7150: # for course roles, perform group memberships changes triggered by role change.
7151: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7152: unless ($role =~ /^gr/) {
7153: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7154: $origstart,$selfenroll,$context);
7155: }
7156: if ($role eq 'cc') {
7157: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7158: }
7159: }
7160: return $answer;
7161: }
7162:
7163: sub autoupdate_coowners {
7164: my ($url,$end,$start,$uname,$udom) = @_;
7165: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7166: if (($cdom ne '') && ($cnum ne '')) {
7167: my $now = time;
7168: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7169: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7170: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7171: my $instcode = $coursehash{'internal.coursecode'};
7172: if ($instcode ne '') {
7173: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7174: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7175: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7176: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7177: if ($result eq 'valid') {
7178: if ($coursehash{'internal.co-owners'}) {
7179: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7180: push(@newcoowners,$coowner);
7181: }
7182: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7183: push(@newcoowners,$uname.':'.$udom);
7184: }
7185: @newcoowners = sort(@newcoowners);
7186: } else {
7187: push(@newcoowners,$uname.':'.$udom);
7188: }
7189: } else {
7190: if ($coursehash{'internal.co-owners'}) {
7191: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7192: unless ($coowner eq $uname.':'.$udom) {
7193: push(@newcoowners,$coowner);
7194: }
7195: }
7196: unless (@newcoowners > 0) {
7197: $delcoowners = 1;
7198: $coowners = '';
7199: }
7200: }
7201: }
7202: if (@newcoowners || $delcoowners) {
7203: &store_coowners($cdom,$cnum,$coursehash{'home'},
7204: $delcoowners,@newcoowners);
7205: }
7206: }
7207: }
7208: }
7209: }
7210: }
7211: }
7212:
7213: sub store_coowners {
7214: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7215: my $cid = $cdom.'_'.$cnum;
7216: my ($coowners,$delresult,$putresult);
7217: if (@newcoowners) {
7218: $coowners = join(',',@newcoowners);
7219: my %coownershash = (
7220: 'internal.co-owners' => $coowners,
7221: );
7222: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7223: if ($putresult eq 'ok') {
7224: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7225: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7226: }
7227: }
7228: }
7229: if ($delcoowners) {
7230: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7231: if ($delresult eq 'ok') {
7232: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7233: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7234: }
7235: }
7236: }
7237: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7238: my %crsinfo =
7239: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7240: if (ref($crsinfo{$cid}) eq 'HASH') {
7241: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7242: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7243: }
7244: }
7245: }
7246:
7247: # -------------------------------------------------- Modify user authentication
7248: # Overrides without validation
7249:
7250: sub modifyuserauth {
7251: my ($udom,$uname,$umode,$upass)=@_;
7252: my $uhome=&homeserver($uname,$udom);
7253: unless (&allowed('mau',$udom)) { return 'refused'; }
7254: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7255: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7256: ' in domain '.$env{'request.role.domain'});
7257: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7258: &escape($upass),$uhome);
7259: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7260: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7261: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7262: &log($udom,,$uname,$uhome,
7263: 'Authentication changed by '.$env{'user.domain'}.', '.
7264: $env{'user.name'}.', '.$umode.
7265: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7266: unless ($reply eq 'ok') {
7267: &logthis('Authentication mode error: '.$reply);
7268: return 'error: '.$reply;
7269: }
7270: return 'ok';
7271: }
7272:
7273: # --------------------------------------------------------------- Modify a user
7274:
7275: sub modifyuser {
7276: my ($udom, $uname, $uid,
7277: $umode, $upass, $first,
7278: $middle, $last, $gene,
7279: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7280: $udom= &LONCAPA::clean_domain($udom);
7281: $uname=&LONCAPA::clean_username($uname);
7282: my $showcandelete = 'none';
7283: if (ref($candelete) eq 'ARRAY') {
7284: if (@{$candelete} > 0) {
7285: $showcandelete = join(', ',@{$candelete});
7286: }
7287: }
7288: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7289: $umode.', '.$first.', '.$middle.', '.
7290: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7291: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7292: ' desiredhome not specified').
7293: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7294: ' in domain '.$env{'request.role.domain'});
7295: my $uhome=&homeserver($uname,$udom,'true');
7296: my $newuser;
7297: if ($uhome eq 'no_host') {
7298: $newuser = 1;
7299: }
7300: # ----------------------------------------------------------------- Create User
7301: if (($uhome eq 'no_host') &&
7302: (($umode && $upass) || ($umode eq 'localauth'))) {
7303: my $unhome='';
7304: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7305: $unhome = $desiredhome;
7306: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7307: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7308: } else { # load balancing routine for determining $unhome
7309: my $loadm=10000000;
7310: my %servers = &get_servers($udom,'library');
7311: foreach my $tryserver (keys(%servers)) {
7312: my $answer=reply('load',$tryserver);
7313: if (($answer=~/\d+/) && ($answer<$loadm)) {
7314: $loadm=$answer;
7315: $unhome=$tryserver;
7316: }
7317: }
7318: }
7319: if (($unhome eq '') || ($unhome eq 'no_host')) {
7320: return 'error: unable to find a home server for '.$uname.
7321: ' in domain '.$udom;
7322: }
7323: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7324: &escape($upass),$unhome);
7325: unless ($reply eq 'ok') {
7326: return 'error: '.$reply;
7327: }
7328: $uhome=&homeserver($uname,$udom,'true');
7329: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7330: return 'error: unable verify users home machine.';
7331: }
7332: } # End of creation of new user
7333: # ---------------------------------------------------------------------- Add ID
7334: if ($uid) {
7335: $uid=~tr/A-Z/a-z/;
7336: my %uidhash=&idrget($udom,$uname);
7337: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7338: && (!$forceid)) {
7339: unless ($uid eq $uidhash{$uname}) {
7340: return 'error: user id "'.$uid.'" does not match '.
7341: 'current user id "'.$uidhash{$uname}.'".';
7342: }
7343: } else {
7344: &idput($udom,($uname => $uid));
7345: }
7346: }
7347: # -------------------------------------------------------------- Add names, etc
7348: my @tmp=&get('environment',
7349: ['firstname','middlename','lastname','generation','id',
7350: 'permanentemail','inststatus'],
7351: $udom,$uname);
7352: my (%names,%oldnames);
7353: if ($tmp[0] =~ m/^error:.*/) {
7354: %names=();
7355: } else {
7356: %names = @tmp;
7357: %oldnames = %names;
7358: }
7359: #
7360: # If name, email and/or uid are blank (e.g., because an uploaded file
7361: # of users did not contain them), do not overwrite existing values
7362: # unless field is in $candelete array ref.
7363: #
7364:
7365: my @fields = ('firstname','middlename','lastname','generation',
7366: 'permanentemail','id');
7367: my %newvalues;
7368: if (ref($candelete) eq 'ARRAY') {
7369: foreach my $field (@fields) {
7370: if (grep(/^\Q$field\E$/,@{$candelete})) {
7371: if ($field eq 'firstname') {
7372: $names{$field} = $first;
7373: } elsif ($field eq 'middlename') {
7374: $names{$field} = $middle;
7375: } elsif ($field eq 'lastname') {
7376: $names{$field} = $last;
7377: } elsif ($field eq 'generation') {
7378: $names{$field} = $gene;
7379: } elsif ($field eq 'permanentemail') {
7380: $names{$field} = $email;
7381: } elsif ($field eq 'id') {
7382: $names{$field} = $uid;
7383: }
7384: }
7385: }
7386: }
7387: if ($first) { $names{'firstname'} = $first; }
7388: if (defined($middle)) { $names{'middlename'} = $middle; }
7389: if ($last) { $names{'lastname'} = $last; }
7390: if (defined($gene)) { $names{'generation'} = $gene; }
7391: if ($email) {
7392: $email=~s/[^\w\@\.\-\,]//gs;
7393: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7394: }
7395: if ($uid) { $names{'id'} = $uid; }
7396: if (defined($inststatus)) {
7397: $names{'inststatus'} = '';
7398: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7399: if (ref($usertypes) eq 'HASH') {
7400: my @okstatuses;
7401: foreach my $item (split(/:/,$inststatus)) {
7402: if (defined($usertypes->{$item})) {
7403: push(@okstatuses,$item);
7404: }
7405: }
7406: if (@okstatuses) {
7407: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7408: }
7409: }
7410: }
7411: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7412: $umode.', '.$first.', '.$middle.', '.
7413: $last.', '.$gene.', '.$email.', '.$inststatus;
7414: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7415: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7416: } else {
7417: $logmsg .= ' during self creation';
7418: }
7419: my $changed;
7420: if ($newuser) {
7421: $changed = 1;
7422: } else {
7423: foreach my $field (@fields) {
7424: if ($names{$field} ne $oldnames{$field}) {
7425: $changed = 1;
7426: last;
7427: }
7428: }
7429: }
7430: unless ($changed) {
7431: $logmsg = 'No changes in user information needed for: '.$logmsg;
7432: &logthis($logmsg);
7433: return 'ok';
7434: }
7435: my $reply = &put('environment', \%names, $udom,$uname);
7436: if ($reply ne 'ok') {
7437: return 'error: '.$reply;
7438: }
7439: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7440: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7441: }
7442: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7443: &devalidate_cache_new('namescache',$uname.':'.$udom);
7444: $logmsg = 'Success modifying user '.$logmsg;
7445: &logthis($logmsg);
7446: return 'ok';
7447: }
7448:
7449: # -------------------------------------------------------------- Modify student
7450:
7451: sub modifystudent {
7452: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7453: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7454: $selfenroll,$context,$inststatus)=@_;
7455: if (!$cid) {
7456: unless ($cid=$env{'request.course.id'}) {
7457: return 'not_in_class';
7458: }
7459: }
7460: # --------------------------------------------------------------- Make the user
7461: my $reply=&modifyuser
7462: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7463: $desiredhome,$email,$inststatus);
7464: unless ($reply eq 'ok') { return $reply; }
7465: # This will cause &modify_student_enrollment to get the uid from the
7466: # students environment
7467: $uid = undef if (!$forceid);
7468: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7469: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7470: return $reply;
7471: }
7472:
7473: sub modify_student_enrollment {
7474: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7475: my ($cdom,$cnum,$chome);
7476: if (!$cid) {
7477: unless ($cid=$env{'request.course.id'}) {
7478: return 'not_in_class';
7479: }
7480: $cdom=$env{'course.'.$cid.'.domain'};
7481: $cnum=$env{'course.'.$cid.'.num'};
7482: } else {
7483: ($cdom,$cnum)=split(/_/,$cid);
7484: }
7485: $chome=$env{'course.'.$cid.'.home'};
7486: if (!$chome) {
7487: $chome=&homeserver($cnum,$cdom);
7488: }
7489: if (!$chome) { return 'unknown_course'; }
7490: # Make sure the user exists
7491: my $uhome=&homeserver($uname,$udom);
7492: if (($uhome eq '') || ($uhome eq 'no_host')) {
7493: return 'error: no such user';
7494: }
7495: # Get student data if we were not given enough information
7496: if (!defined($first) || $first eq '' ||
7497: !defined($last) || $last eq '' ||
7498: !defined($uid) || $uid eq '' ||
7499: !defined($middle) || $middle eq '' ||
7500: !defined($gene) || $gene eq '') {
7501: # They did not supply us with enough data to enroll the student, so
7502: # we need to pick up more information.
7503: my %tmp = &get('environment',
7504: ['firstname','middlename','lastname', 'generation','id']
7505: ,$udom,$uname);
7506:
7507: #foreach my $key (keys(%tmp)) {
7508: # &logthis("key $key = ".$tmp{$key});
7509: #}
7510: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7511: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7512: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7513: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7514: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7515: }
7516: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7517: my $reply=cput('classlist',
7518: {"$uname:$udom" =>
7519: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7520: $cdom,$cnum);
7521: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7522: return 'error: '.$reply;
7523: } else {
7524: &devalidate_getsection_cache($udom,$uname,$cid);
7525: }
7526: # Add student role to user
7527: my $uurl='/'.$cid;
7528: $uurl=~s/\_/\//g;
7529: if ($usec) {
7530: $uurl.='/'.$usec;
7531: }
7532: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
7533: }
7534:
7535: sub format_name {
7536: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7537: my $name;
7538: if ($first ne 'lastname') {
7539: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7540: } else {
7541: if ($lastname=~/\S/) {
7542: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7543: $name=~s/\s+,/,/;
7544: } else {
7545: $name.= $firstname.' '.$middlename.' '.$generation;
7546: }
7547: }
7548: $name=~s/^\s+//;
7549: $name=~s/\s+$//;
7550: $name=~s/\s+/ /g;
7551: return $name;
7552: }
7553:
7554: # ------------------------------------------------- Write to course preferences
7555:
7556: sub writecoursepref {
7557: my ($courseid,%prefs)=@_;
7558: $courseid=~s/^\///;
7559: $courseid=~s/\_/\//g;
7560: my ($cdomain,$cnum)=split(/\//,$courseid);
7561: my $chome=homeserver($cnum,$cdomain);
7562: if (($chome eq '') || ($chome eq 'no_host')) {
7563: return 'error: no such course';
7564: }
7565: my $cstring='';
7566: foreach my $pref (keys(%prefs)) {
7567: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7568: }
7569: $cstring=~s/\&$//;
7570: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7571: }
7572:
7573: # ---------------------------------------------------------- Make/modify course
7574:
7575: sub createcourse {
7576: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7577: $course_owner,$crstype,$cnum,$context,$category)=@_;
7578: $url=&declutter($url);
7579: my $cid='';
7580: if ($context eq 'requestcourses') {
7581: my $can_create = 0;
7582: my ($ownername,$ownerdom) = split(':',$course_owner);
7583: if ($udom eq $ownerdom) {
7584: if (&usertools_access($ownername,$ownerdom,$category,undef,
7585: $context)) {
7586: $can_create = 1;
7587: }
7588: } else {
7589: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7590: $category);
7591: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7592: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7593: if (@curr > 0) {
7594: my @options = qw(approval validate autolimit);
7595: my $optregex = join('|',@options);
7596: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7597: $can_create = 1;
7598: }
7599: }
7600: }
7601: }
7602: if ($can_create) {
7603: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7604: unless (&allowed('ccc',$udom)) {
7605: return 'refused';
7606: }
7607: }
7608: } else {
7609: return 'refused';
7610: }
7611: } elsif (!&allowed('ccc',$udom)) {
7612: return 'refused';
7613: }
7614: # --------------------------------------------------------------- Get Unique ID
7615: my $uname;
7616: if ($cnum =~ /^$match_courseid$/) {
7617: my $chome=&homeserver($cnum,$udom,'true');
7618: if (($chome eq '') || ($chome eq 'no_host')) {
7619: $uname = $cnum;
7620: } else {
7621: $uname = &generate_coursenum($udom,$crstype);
7622: }
7623: } else {
7624: $uname = &generate_coursenum($udom,$crstype);
7625: }
7626: return $uname if ($uname =~ /^error/);
7627: # -------------------------------------------------- Check supplied server name
7628: if (!defined($course_server)) {
7629: if (defined(&domain($udom,'primary'))) {
7630: $course_server = &domain($udom,'primary');
7631: } else {
7632: $course_server = $env{'user.home'};
7633: }
7634: }
7635: my %host_servers =
7636: &Apache::lonnet::get_servers($udom,'library');
7637: unless ($host_servers{$course_server}) {
7638: return 'error: invalid home server for course: '.$course_server;
7639: }
7640: # ------------------------------------------------------------- Make the course
7641: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7642: $course_server);
7643: unless ($reply eq 'ok') { return 'error: '.$reply; }
7644: my $uhome=&homeserver($uname,$udom,'true');
7645: if (($uhome eq '') || ($uhome eq 'no_host')) {
7646: return 'error: no such course';
7647: }
7648: # ----------------------------------------------------------------- Course made
7649: # log existence
7650: my $now = time;
7651: my $newcourse = {
7652: $udom.'_'.$uname => {
7653: description => $description,
7654: inst_code => $inst_code,
7655: owner => $course_owner,
7656: type => $crstype,
7657: creator => $env{'user.name'}.':'.
7658: $env{'user.domain'},
7659: created => $now,
7660: context => $context,
7661: },
7662: };
7663: &courseidput($udom,$newcourse,$uhome,'notime');
7664: # set toplevel url
7665: my $topurl=$url;
7666: unless ($nonstandard) {
7667: # ------------------------------------------ For standard courses, make top url
7668: my $mapurl=&clutter($url);
7669: if ($mapurl eq '/res/') { $mapurl=''; }
7670: $env{'form.initmap'}=(<<ENDINITMAP);
7671: <map>
7672: <resource id="1" type="start"></resource>
7673: <resource id="2" src="$mapurl"></resource>
7674: <resource id="3" type="finish"></resource>
7675: <link index="1" from="1" to="2"></link>
7676: <link index="2" from="2" to="3"></link>
7677: </map>
7678: ENDINITMAP
7679: $topurl=&declutter(
7680: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7681: );
7682: }
7683: # ----------------------------------------------------------- Write preferences
7684: &writecoursepref($udom.'_'.$uname,
7685: ('description' => $description,
7686: 'url' => $topurl,
7687: 'internal.creator' => $env{'user.name'}.':'.
7688: $env{'user.domain'},
7689: 'internal.created' => $now,
7690: 'internal.creationcontext' => $context)
7691: );
7692: return '/'.$udom.'/'.$uname;
7693: }
7694:
7695: # ------------------------------------------------------------------- Create ID
7696: sub generate_coursenum {
7697: my ($udom,$crstype) = @_;
7698: my $domdesc = &domain($udom);
7699: return 'error: invalid domain' if ($domdesc eq '');
7700: my $first;
7701: if ($crstype eq 'Community') {
7702: $first = '0';
7703: } else {
7704: $first = int(1+rand(9));
7705: }
7706: my $uname=$first.
7707: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7708: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7709: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7710: # ----------------------------------------------- Make sure that does not exist
7711: my $uhome=&homeserver($uname,$udom,'true');
7712: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7713: if ($crstype eq 'Community') {
7714: $first = '0';
7715: } else {
7716: $first = int(1+rand(9));
7717: }
7718: $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: $uhome=&homeserver($uname,$udom,'true');
7723: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7724: return 'error: unable to generate unique course-ID';
7725: }
7726: }
7727: return $uname;
7728: }
7729:
7730: sub is_course {
7731: my ($cdom,$cnum) = @_;
7732: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
7733: undef,'.');
7734: if (exists($courses{$cdom.'_'.$cnum})) {
7735: return 1;
7736: }
7737: return 0;
7738: }
7739:
7740: sub store_userdata {
7741: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
7742: my $result;
7743: if ($datakey ne '') {
7744: if (ref($storehash) eq 'HASH') {
7745: if ($udom eq '' || $uname eq '') {
7746: $udom = $env{'user.domain'};
7747: $uname = $env{'user.name'};
7748: }
7749: my $uhome=&homeserver($uname,$udom);
7750: if (($uhome eq '') || ($uhome eq 'no_host')) {
7751: $result = 'error: no_host';
7752: } else {
7753: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7754: $storehash->{'host'} = $perlvar{'lonHostID'};
7755:
7756: my $namevalue='';
7757: foreach my $key (keys(%{$storehash})) {
7758: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7759: }
7760: $namevalue=~s/\&$//;
7761: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7762: $namevalue,$uhome);
7763: }
7764: } else {
7765: $result = 'error: data to store was not a hash reference';
7766: }
7767: } else {
7768: $result= 'error: invalid requestkey';
7769: }
7770: return $result;
7771: }
7772:
7773: # ---------------------------------------------------------- Assign Custom Role
7774:
7775: sub assigncustomrole {
7776: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
7777: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
7778: $end,$start,$deleteflag,$selfenroll,$context);
7779: }
7780:
7781: # ----------------------------------------------------------------- Revoke Role
7782:
7783: sub revokerole {
7784: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
7785: my $now=time;
7786: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
7787: }
7788:
7789: # ---------------------------------------------------------- Revoke Custom Role
7790:
7791: sub revokecustomrole {
7792: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
7793: my $now=time;
7794: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
7795: $deleteflag,$selfenroll,$context);
7796: }
7797:
7798: # ------------------------------------------------------------ Disk usage
7799: sub diskusage {
7800: my ($udom,$uname,$directorypath,$getpropath)=@_;
7801: $directorypath =~ s/\/$//;
7802: my $listing=&reply('du2:'.&escape($directorypath).':'
7803: .&escape($getpropath).':'.&escape($uname).':'
7804: .&escape($udom),homeserver($uname,$udom));
7805: if ($listing eq 'unknown_cmd') {
7806: if ($getpropath) {
7807: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7808: }
7809: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7810: }
7811: return $listing;
7812: }
7813:
7814: sub is_locked {
7815: my ($file_name, $domain, $user, $which) = @_;
7816: my @check;
7817: my $is_locked;
7818: push (@check,$file_name);
7819: my %locked = &get('file_permissions',\@check,
7820: $env{'user.domain'},$env{'user.name'});
7821: my ($tmp)=keys(%locked);
7822: if ($tmp=~/^error:/) { undef(%locked); }
7823:
7824: if (ref($locked{$file_name}) eq 'ARRAY') {
7825: $is_locked = 'false';
7826: foreach my $entry (@{$locked{$file_name}}) {
7827: if (ref($entry) eq 'ARRAY') {
7828: $is_locked = 'true';
7829: if (ref($which) eq 'ARRAY') {
7830: push(@{$which},$entry);
7831: } else {
7832: last;
7833: }
7834: }
7835: }
7836: } else {
7837: $is_locked = 'false';
7838: }
7839: return $is_locked;
7840: }
7841:
7842: sub declutter_portfile {
7843: my ($file) = @_;
7844: $file =~ s{^(/portfolio/|portfolio/)}{/};
7845: return $file;
7846: }
7847:
7848: # ------------------------------------------------------------- Mark as Read Only
7849:
7850: sub mark_as_readonly {
7851: my ($domain,$user,$files,$what) = @_;
7852: my %current_permissions = &dump('file_permissions',$domain,$user);
7853: my ($tmp)=keys(%current_permissions);
7854: if ($tmp=~/^error:/) { undef(%current_permissions); }
7855: foreach my $file (@{$files}) {
7856: $file = &declutter_portfile($file);
7857: push(@{$current_permissions{$file}},$what);
7858: }
7859: &put('file_permissions',\%current_permissions,$domain,$user);
7860: return;
7861: }
7862:
7863: # ------------------------------------------------------------Save Selected Files
7864:
7865: sub save_selected_files {
7866: my ($user, $path, @files) = @_;
7867: my $filename = $user."savedfiles";
7868: my @other_files = &files_not_in_path($user, $path);
7869: open (OUT, '>'.$tmpdir.$filename);
7870: foreach my $file (@files) {
7871: print (OUT $env{'form.currentpath'}.$file."\n");
7872: }
7873: foreach my $file (@other_files) {
7874: print (OUT $file."\n");
7875: }
7876: close (OUT);
7877: return 'ok';
7878: }
7879:
7880: sub clear_selected_files {
7881: my ($user) = @_;
7882: my $filename = $user."savedfiles";
7883: open (OUT, '>'.LONCAPA::tempdir().$filename);
7884: print (OUT undef);
7885: close (OUT);
7886: return ("ok");
7887: }
7888:
7889: sub files_in_path {
7890: my ($user, $path) = @_;
7891: my $filename = $user."savedfiles";
7892: my %return_files;
7893: open (IN, '<'.LONCAPA::tempdir().$filename);
7894: while (my $line_in = <IN>) {
7895: chomp ($line_in);
7896: my @paths_and_file = split (m!/!, $line_in);
7897: my $file_part = pop (@paths_and_file);
7898: my $path_part = join ('/', @paths_and_file);
7899: $path_part.='/';
7900: my $path_and_file = $path_part.$file_part;
7901: if ($path_part eq $path) {
7902: $return_files{$file_part}= 'selected';
7903: }
7904: }
7905: close (IN);
7906: return (\%return_files);
7907: }
7908:
7909: # called in portfolio select mode, to show files selected NOT in current directory
7910: sub files_not_in_path {
7911: my ($user, $path) = @_;
7912: my $filename = $user."savedfiles";
7913: my @return_files;
7914: my $path_part;
7915: open(IN, '<'.LONCAPA::.$filename);
7916: while (my $line = <IN>) {
7917: #ok, I know it's clunky, but I want it to work
7918: my @paths_and_file = split(m|/|, $line);
7919: my $file_part = pop(@paths_and_file);
7920: chomp($file_part);
7921: my $path_part = join('/', @paths_and_file);
7922: $path_part .= '/';
7923: my $path_and_file = $path_part.$file_part;
7924: if ($path_part ne $path) {
7925: push(@return_files, ($path_and_file));
7926: }
7927: }
7928: close(OUT);
7929: return (@return_files);
7930: }
7931:
7932: #----------------------------------------------Get portfolio file permissions
7933:
7934: sub get_portfile_permissions {
7935: my ($domain,$user) = @_;
7936: my %current_permissions = &dump('file_permissions',$domain,$user);
7937: my ($tmp)=keys(%current_permissions);
7938: if ($tmp=~/^error:/) { undef(%current_permissions); }
7939: return \%current_permissions;
7940: }
7941:
7942: #---------------------------------------------Get portfolio file access controls
7943:
7944: sub get_access_controls {
7945: my ($current_permissions,$group,$file) = @_;
7946: my %access;
7947: my $real_file = $file;
7948: $file =~ s/\.meta$//;
7949: if (defined($file)) {
7950: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7951: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
7952: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
7953: }
7954: }
7955: } else {
7956: foreach my $key (keys(%{$current_permissions})) {
7957: if ($key =~ /\0accesscontrol$/) {
7958: if (defined($group)) {
7959: if ($key !~ m-^\Q$group\E/-) {
7960: next;
7961: }
7962: }
7963: my ($fullpath) = split(/\0/,$key);
7964: if (ref($$current_permissions{$key}) eq 'HASH') {
7965: foreach my $control (keys(%{$$current_permissions{$key}})) {
7966: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7967: }
7968: }
7969: }
7970: }
7971: }
7972: return %access;
7973: }
7974:
7975: sub modify_access_controls {
7976: my ($file_name,$changes,$domain,$user)=@_;
7977: my ($outcome,$deloutcome);
7978: my %store_permissions;
7979: my %new_values;
7980: my %new_control;
7981: my %translation;
7982: my @deletions = ();
7983: my $now = time;
7984: if (exists($$changes{'activate'})) {
7985: if (ref($$changes{'activate'}) eq 'HASH') {
7986: my @newitems = sort(keys(%{$$changes{'activate'}}));
7987: my $numnew = scalar(@newitems);
7988: for (my $i=0; $i<$numnew; $i++) {
7989: my $newkey = $newitems[$i];
7990: my $newid = &Apache::loncommon::get_cgi_id();
7991: if ($newkey =~ /^\d+:/) {
7992: $newkey =~ s/^(\d+)/$newid/;
7993: $translation{$1} = $newid;
7994: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7995: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7996: $translation{$1} = $newid;
7997: }
7998: $new_values{$file_name."\0".$newkey} =
7999: $$changes{'activate'}{$newitems[$i]};
8000: $new_control{$newkey} = $now;
8001: }
8002: }
8003: }
8004: my %todelete;
8005: my %changed_items;
8006: foreach my $action ('delete','update') {
8007: if (exists($$changes{$action})) {
8008: if (ref($$changes{$action}) eq 'HASH') {
8009: foreach my $key (keys(%{$$changes{$action}})) {
8010: my ($itemnum) = ($key =~ /^([^:]+):/);
8011: if ($action eq 'delete') {
8012: $todelete{$itemnum} = 1;
8013: } else {
8014: $changed_items{$itemnum} = $key;
8015: }
8016: }
8017: }
8018: }
8019: }
8020: # get lock on access controls for file.
8021: my $lockhash = {
8022: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8023: ':'.$env{'user.domain'},
8024: };
8025: my $tries = 0;
8026: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8027:
8028: while (($gotlock ne 'ok') && $tries <3) {
8029: $tries ++;
8030: sleep 1;
8031: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8032: }
8033: if ($gotlock eq 'ok') {
8034: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8035: my ($tmp)=keys(%curr_permissions);
8036: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8037: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8038: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8039: if (ref($curr_controls) eq 'HASH') {
8040: foreach my $control_item (keys(%{$curr_controls})) {
8041: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8042: if (defined($todelete{$itemnum})) {
8043: push(@deletions,$file_name."\0".$control_item);
8044: } else {
8045: if (defined($changed_items{$itemnum})) {
8046: $new_control{$changed_items{$itemnum}} = $now;
8047: push(@deletions,$file_name."\0".$control_item);
8048: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8049: } else {
8050: $new_control{$control_item} = $$curr_controls{$control_item};
8051: }
8052: }
8053: }
8054: }
8055: }
8056: my ($group);
8057: if (&is_course($domain,$user)) {
8058: ($group,my $file) = split(/\//,$file_name,2);
8059: }
8060: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8061: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8062: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8063: # remove lock
8064: my @del_lock = ($file_name."\0".'locked_access_records');
8065: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8066: my $sqlresult =
8067: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8068: $group);
8069: } else {
8070: $outcome = "error: could not obtain lockfile\n";
8071: }
8072: return ($outcome,$deloutcome,\%new_values,\%translation);
8073: }
8074:
8075: sub make_public_indefinitely {
8076: my ($requrl) = @_;
8077: my $now = time;
8078: my $action = 'activate';
8079: my $aclnum = 0;
8080: if (&is_portfolio_url($requrl)) {
8081: my (undef,$udom,$unum,$file_name,$group) =
8082: &parse_portfolio_url($requrl);
8083: my $current_perms = &get_portfile_permissions($udom,$unum);
8084: my %access_controls = &get_access_controls($current_perms,
8085: $group,$file_name);
8086: foreach my $key (keys(%{$access_controls{$file_name}})) {
8087: my ($num,$scope,$end,$start) =
8088: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8089: if ($scope eq 'public') {
8090: if ($start <= $now && $end == 0) {
8091: $action = 'none';
8092: } else {
8093: $action = 'update';
8094: $aclnum = $num;
8095: }
8096: last;
8097: }
8098: }
8099: if ($action eq 'none') {
8100: return 'ok';
8101: } else {
8102: my %changes;
8103: my $newend = 0;
8104: my $newstart = $now;
8105: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8106: $changes{$action}{$newkey} = {
8107: type => 'public',
8108: time => {
8109: start => $newstart,
8110: end => $newend,
8111: },
8112: };
8113: my ($outcome,$deloutcome,$new_values,$translation) =
8114: &modify_access_controls($file_name,\%changes,$udom,$unum);
8115: return $outcome;
8116: }
8117: } else {
8118: return 'invalid';
8119: }
8120: }
8121:
8122: #------------------------------------------------------Get Marked as Read Only
8123:
8124: sub get_marked_as_readonly {
8125: my ($domain,$user,$what,$group) = @_;
8126: my $current_permissions = &get_portfile_permissions($domain,$user);
8127: my @readonly_files;
8128: my $cmp1=$what;
8129: if (ref($what)) { $cmp1=join('',@{$what}) };
8130: while (my ($file_name,$value) = each(%{$current_permissions})) {
8131: if (defined($group)) {
8132: if ($file_name !~ m-^\Q$group\E/-) {
8133: next;
8134: }
8135: }
8136: if (ref($value) eq "ARRAY"){
8137: foreach my $stored_what (@{$value}) {
8138: my $cmp2=$stored_what;
8139: if (ref($stored_what) eq 'ARRAY') {
8140: $cmp2=join('',@{$stored_what});
8141: }
8142: if ($cmp1 eq $cmp2) {
8143: push(@readonly_files, $file_name);
8144: last;
8145: } elsif (!defined($what)) {
8146: push(@readonly_files, $file_name);
8147: last;
8148: }
8149: }
8150: }
8151: }
8152: return @readonly_files;
8153: }
8154: #-----------------------------------------------------------Get Marked as Read Only Hash
8155:
8156: sub get_marked_as_readonly_hash {
8157: my ($current_permissions,$group,$what) = @_;
8158: my %readonly_files;
8159: while (my ($file_name,$value) = each(%{$current_permissions})) {
8160: if (defined($group)) {
8161: if ($file_name !~ m-^\Q$group\E/-) {
8162: next;
8163: }
8164: }
8165: if (ref($value) eq "ARRAY"){
8166: foreach my $stored_what (@{$value}) {
8167: if (ref($stored_what) eq 'ARRAY') {
8168: foreach my $lock_descriptor(@{$stored_what}) {
8169: if ($lock_descriptor eq 'graded') {
8170: $readonly_files{$file_name} = 'graded';
8171: } elsif ($lock_descriptor eq 'handback') {
8172: $readonly_files{$file_name} = 'handback';
8173: } else {
8174: if (!exists($readonly_files{$file_name})) {
8175: $readonly_files{$file_name} = 'locked';
8176: }
8177: }
8178: }
8179: }
8180: }
8181: }
8182: }
8183: return %readonly_files;
8184: }
8185: # ------------------------------------------------------------ Unmark as Read Only
8186:
8187: sub unmark_as_readonly {
8188: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8189: # for portfolio submissions, $what contains [$symb,$crsid]
8190: my ($domain,$user,$what,$file_name,$group) = @_;
8191: $file_name = &declutter_portfile($file_name);
8192: my $symb_crs = $what;
8193: if (ref($what)) { $symb_crs=join('',@$what); }
8194: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8195: my ($tmp)=keys(%current_permissions);
8196: if ($tmp=~/^error:/) { undef(%current_permissions); }
8197: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8198: foreach my $file (@readonly_files) {
8199: my $clean_file = &declutter_portfile($file);
8200: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8201: my $current_locks = $current_permissions{$file};
8202: my @new_locks;
8203: my @del_keys;
8204: if (ref($current_locks) eq "ARRAY"){
8205: foreach my $locker (@{$current_locks}) {
8206: my $compare=$locker;
8207: if (ref($locker) eq 'ARRAY') {
8208: $compare=join('',@{$locker});
8209: if ($compare ne $symb_crs) {
8210: push(@new_locks, $locker);
8211: }
8212: }
8213: }
8214: if (scalar(@new_locks) > 0) {
8215: $current_permissions{$file} = \@new_locks;
8216: } else {
8217: push(@del_keys, $file);
8218: &del('file_permissions',\@del_keys, $domain, $user);
8219: delete($current_permissions{$file});
8220: }
8221: }
8222: }
8223: &put('file_permissions',\%current_permissions,$domain,$user);
8224: return;
8225: }
8226:
8227: # ------------------------------------------------------------ Directory lister
8228:
8229: sub dirlist {
8230: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8231: $uri=~s/^\///;
8232: $uri=~s/\/$//;
8233: my ($udom, $uname);
8234: if ($getuserdir) {
8235: $udom = $userdomain;
8236: $uname = $username;
8237: } else {
8238: (undef,$udom,$uname)=split(/\//,$uri);
8239: if(defined($userdomain)) {
8240: $udom = $userdomain;
8241: }
8242: if(defined($username)) {
8243: $uname = $username;
8244: }
8245: }
8246: my ($dirRoot,$listing,@listing_results);
8247:
8248: $dirRoot = $perlvar{'lonDocRoot'};
8249: if (defined($getpropath)) {
8250: $dirRoot = &propath($udom,$uname);
8251: $dirRoot =~ s/\/$//;
8252: } elsif (defined($getuserdir)) {
8253: my $subdir=$uname.'__';
8254: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8255: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8256: ."/$udom/$subdir/$uname";
8257: } elsif (defined($alternateRoot)) {
8258: $dirRoot = $alternateRoot;
8259: }
8260:
8261: if($udom) {
8262: if($uname) {
8263: my $uhome = &homeserver($uname,$udom);
8264: if ($uhome eq 'no_host') {
8265: return ([],'no_host');
8266: }
8267: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8268: .$getuserdir.':'.&escape($dirRoot)
8269: .':'.&escape($uname).':'.&escape($udom),$uhome);
8270: if ($listing eq 'unknown_cmd') {
8271: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8272: } else {
8273: @listing_results = map { &unescape($_); } split(/:/,$listing);
8274: }
8275: if ($listing eq 'unknown_cmd') {
8276: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8277: @listing_results = split(/:/,$listing);
8278: } else {
8279: @listing_results = map { &unescape($_); } split(/:/,$listing);
8280: }
8281: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8282: ($listing eq 'rejected') || ($listing eq 'refused') ||
8283: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8284: return ([],$listing);
8285: } else {
8286: return (\@listing_results);
8287: }
8288: } elsif(!$alternateRoot) {
8289: my (%allusers,%listerror);
8290: my %servers = &get_servers($udom,'library');
8291: foreach my $tryserver (keys(%servers)) {
8292: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8293: &escape($udom),$tryserver);
8294: if ($listing eq 'unknown_cmd') {
8295: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8296: $udom, $tryserver);
8297: } else {
8298: @listing_results = map { &unescape($_); } split(/:/,$listing);
8299: }
8300: if ($listing eq 'unknown_cmd') {
8301: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8302: $udom, $tryserver);
8303: @listing_results = split(/:/,$listing);
8304: } else {
8305: @listing_results =
8306: map { &unescape($_); } split(/:/,$listing);
8307: }
8308: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8309: ($listing eq 'rejected') || ($listing eq 'refused') ||
8310: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8311: $listerror{$tryserver} = $listing;
8312: } else {
8313: foreach my $line (@listing_results) {
8314: my ($entry) = split(/&/,$line,2);
8315: $allusers{$entry} = 1;
8316: }
8317: }
8318: }
8319: my @alluserslist=();
8320: foreach my $user (sort(keys(%allusers))) {
8321: push(@alluserslist,$user.'&user');
8322: }
8323: return (\@alluserslist);
8324: } else {
8325: return ([],'missing username');
8326: }
8327: } elsif(!defined($getpropath)) {
8328: my $path = $perlvar{'lonDocRoot'}.'/res/';
8329: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8330: return (\@all_domains);
8331: } else {
8332: return ([],'missing domain');
8333: }
8334: }
8335:
8336: # --------------------------------------------- GetFileTimestamp
8337: # This function utilizes dirlist and returns the date stamp for
8338: # when it was last modified. It will also return an error of -1
8339: # if an error occurs
8340:
8341: sub GetFileTimestamp {
8342: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8343: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8344: $studentName = &LONCAPA::clean_username($studentName);
8345: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8346: undef,$getuserdir);
8347: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8348: return -1;
8349: }
8350: if (ref($fileref) eq 'ARRAY') {
8351: my @stats = split('&',$fileref->[0]);
8352: # @stats contains first the filename, then the stat output
8353: return $stats[10]; # so this is 10 instead of 9.
8354: } else {
8355: return -1;
8356: }
8357: }
8358:
8359: sub stat_file {
8360: my ($uri) = @_;
8361: $uri = &clutter_with_no_wrapper($uri);
8362:
8363: my ($udom,$uname,$file);
8364: if ($uri =~ m-^/(uploaded|editupload)/-) {
8365: ($udom,$uname,$file) =
8366: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8367: $file = 'userfiles/'.$file;
8368: }
8369: if ($uri =~ m-^/res/-) {
8370: ($udom,$uname) =
8371: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8372: $file = $uri;
8373: }
8374:
8375: if (!$udom || !$uname || !$file) {
8376: # unable to handle the uri
8377: return ();
8378: }
8379: my $getpropath;
8380: if ($file =~ /^userfiles\//) {
8381: $getpropath = 1;
8382: }
8383: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8384: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8385: return ();
8386: } else {
8387: if (ref($listref) eq 'ARRAY') {
8388: my @stats = split('&',$listref->[0]);
8389: shift(@stats); #filename is first
8390: return @stats;
8391: }
8392: }
8393: return ();
8394: }
8395:
8396: # -------------------------------------------------------- Value of a Condition
8397:
8398: # gets the value of a specific preevaluated condition
8399: # stored in the string $env{user.state.<cid>}
8400: # or looks up a condition reference in the bighash and if if hasn't
8401: # already been evaluated recurses into docondval to get the value of
8402: # the condition, then memoizing it to
8403: # $env{user.state.<cid>.<condition>}
8404: sub directcondval {
8405: my $number=shift;
8406: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8407: &Apache::lonuserstate::evalstate();
8408: }
8409: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8410: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8411: } elsif ($number =~ /^_/) {
8412: my $sub_condition;
8413: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8414: &GDBM_READER(),0640)) {
8415: $sub_condition=$bighash{'conditions'.$number};
8416: untie(%bighash);
8417: }
8418: my $value = &docondval($sub_condition);
8419: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8420: return $value;
8421: }
8422: if ($env{'user.state.'.$env{'request.course.id'}}) {
8423: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8424: } else {
8425: return 2;
8426: }
8427: }
8428:
8429: # get the collection of conditions for this resource
8430: sub condval {
8431: my $condidx=shift;
8432: my $allpathcond='';
8433: foreach my $cond (split(/\|/,$condidx)) {
8434: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8435: $allpathcond.=
8436: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8437: }
8438: }
8439: $allpathcond=~s/\|$//;
8440: return &docondval($allpathcond);
8441: }
8442:
8443: #evaluates an expression of conditions
8444: sub docondval {
8445: my ($allpathcond) = @_;
8446: my $result=0;
8447: if ($env{'request.course.id'}
8448: && defined($allpathcond)) {
8449: my $operand='|';
8450: my @stack;
8451: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8452: if ($chunk eq '(') {
8453: push @stack,($operand,$result);
8454: } elsif ($chunk eq ')') {
8455: my $before=pop @stack;
8456: if (pop @stack eq '&') {
8457: $result=$result>$before?$before:$result;
8458: } else {
8459: $result=$result>$before?$result:$before;
8460: }
8461: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8462: $operand=$chunk;
8463: } else {
8464: my $new=directcondval($chunk);
8465: if ($operand eq '&') {
8466: $result=$result>$new?$new:$result;
8467: } else {
8468: $result=$result>$new?$result:$new;
8469: }
8470: }
8471: }
8472: }
8473: return $result;
8474: }
8475:
8476: # ---------------------------------------------------- Devalidate courseresdata
8477:
8478: sub devalidatecourseresdata {
8479: my ($coursenum,$coursedomain)=@_;
8480: my $hashid=$coursenum.':'.$coursedomain;
8481: &devalidate_cache_new('courseres',$hashid);
8482: }
8483:
8484:
8485: # --------------------------------------------------- Course Resourcedata Query
8486: #
8487: # Parameters:
8488: # $coursenum - Number of the course.
8489: # $coursedomain - Domain at which the course was created.
8490: # Returns:
8491: # A hash of the course parameters along (I think) with timestamps
8492: # and version info.
8493:
8494: sub get_courseresdata {
8495: my ($coursenum,$coursedomain)=@_;
8496: my $coursehom=&homeserver($coursenum,$coursedomain);
8497: my $hashid=$coursenum.':'.$coursedomain;
8498: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8499: my %dumpreply;
8500: unless (defined($cached)) {
8501: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8502: $result=\%dumpreply;
8503: my ($tmp) = keys(%dumpreply);
8504: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8505: &do_cache_new('courseres',$hashid,$result,600);
8506: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8507: return $tmp;
8508: } elsif ($tmp =~ /^(error)/) {
8509: $result=undef;
8510: &do_cache_new('courseres',$hashid,$result,600);
8511: }
8512: }
8513: return $result;
8514: }
8515:
8516: sub devalidateuserresdata {
8517: my ($uname,$udom)=@_;
8518: my $hashid="$udom:$uname";
8519: &devalidate_cache_new('userres',$hashid);
8520: }
8521:
8522: sub get_userresdata {
8523: my ($uname,$udom)=@_;
8524: #most student don\'t have any data set, check if there is some data
8525: if (&EXT_cache_status($udom,$uname)) { return undef; }
8526:
8527: my $hashid="$udom:$uname";
8528: my ($result,$cached)=&is_cached_new('userres',$hashid);
8529: if (!defined($cached)) {
8530: my %resourcedata=&dump('resourcedata',$udom,$uname);
8531: $result=\%resourcedata;
8532: &do_cache_new('userres',$hashid,$result,600);
8533: }
8534: my ($tmp)=keys(%$result);
8535: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8536: return $result;
8537: }
8538: #error 2 occurs when the .db doesn't exist
8539: if ($tmp!~/error: 2 /) {
8540: &logthis("<font color=\"blue\">WARNING:".
8541: " Trying to get resource data for ".
8542: $uname." at ".$udom.": ".
8543: $tmp."</font>");
8544: } elsif ($tmp=~/error: 2 /) {
8545: #&EXT_cache_set($udom,$uname);
8546: &do_cache_new('userres',$hashid,undef,600);
8547: undef($tmp); # not really an error so don't send it back
8548: }
8549: return $tmp;
8550: }
8551: #----------------------------------------------- resdata - return resource data
8552: # Purpose:
8553: # Return resource data for either users or for a course.
8554: # Parameters:
8555: # $name - Course/user name.
8556: # $domain - Name of the domain the user/course is registered on.
8557: # $type - Type of thing $name is (must be 'course' or 'user'
8558: # @which - Array of names of resources desired.
8559: # Returns:
8560: # The value of the first reasource in @which that is found in the
8561: # resource hash.
8562: # Exceptional Conditions:
8563: # If the $type passed in is not valid (not the string 'course' or
8564: # 'user', an undefined reference is returned.
8565: # If none of the resources are found, an undef is returned
8566: sub resdata {
8567: my ($name,$domain,$type,@which)=@_;
8568: my $result;
8569: if ($type eq 'course') {
8570: $result=&get_courseresdata($name,$domain);
8571: } elsif ($type eq 'user') {
8572: $result=&get_userresdata($name,$domain);
8573: }
8574: if (!ref($result)) { return $result; }
8575: foreach my $item (@which) {
8576: if (defined($result->{$item->[0]})) {
8577: return [$result->{$item->[0]},$item->[1]];
8578: }
8579: }
8580: return undef;
8581: }
8582:
8583: #
8584: # EXT resource caching routines
8585: #
8586:
8587: sub clear_EXT_cache_status {
8588: &delenv('cache.EXT.');
8589: }
8590:
8591: sub EXT_cache_status {
8592: my ($target_domain,$target_user) = @_;
8593: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8594: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8595: # We know already the user has no data
8596: return 1;
8597: } else {
8598: return 0;
8599: }
8600: }
8601:
8602: sub EXT_cache_set {
8603: my ($target_domain,$target_user) = @_;
8604: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8605: #&appenv({$cachename => time});
8606: }
8607:
8608: # --------------------------------------------------------- Value of a Variable
8609: sub EXT {
8610:
8611: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8612: unless ($varname) { return ''; }
8613: #get real user name/domain, courseid and symb
8614: my $courseid;
8615: my $publicuser;
8616: if ($symbparm) {
8617: $symbparm=&get_symb_from_alias($symbparm);
8618: }
8619: if (!($uname && $udom)) {
8620: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8621: if (!$symbparm) { $symbparm=$cursymb; }
8622: } else {
8623: $courseid=$env{'request.course.id'};
8624: }
8625: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8626: my $rest;
8627: if (defined($therest[0])) {
8628: $rest=join('.',@therest);
8629: } else {
8630: $rest='';
8631: }
8632:
8633: my $qualifierrest=$qualifier;
8634: if ($rest) { $qualifierrest.='.'.$rest; }
8635: my $spacequalifierrest=$space;
8636: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8637: if ($realm eq 'user') {
8638: # --------------------------------------------------------------- user.resource
8639: if ($space eq 'resource') {
8640: if ( (defined($Apache::lonhomework::parsing_a_problem)
8641: || defined($Apache::lonhomework::parsing_a_task))
8642: &&
8643: ($symbparm eq &symbread()) ) {
8644: # if we are in the middle of processing the resource the
8645: # get the value we are planning on committing
8646: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8647: return $Apache::lonhomework::results{$qualifierrest};
8648: } else {
8649: return $Apache::lonhomework::history{$qualifierrest};
8650: }
8651: } else {
8652: my %restored;
8653: if ($publicuser || $env{'request.state'} eq 'construct') {
8654: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8655: } else {
8656: %restored=&restore($symbparm,$courseid,$udom,$uname);
8657: }
8658: return $restored{$qualifierrest};
8659: }
8660: # ----------------------------------------------------------------- user.access
8661: } elsif ($space eq 'access') {
8662: # FIXME - not supporting calls for a specific user
8663: return &allowed($qualifier,$rest);
8664: # ------------------------------------------ user.preferences, user.environment
8665: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8666: if (($uname eq $env{'user.name'}) &&
8667: ($udom eq $env{'user.domain'})) {
8668: return $env{join('.',('environment',$qualifierrest))};
8669: } else {
8670: my %returnhash;
8671: if (!$publicuser) {
8672: %returnhash=&userenvironment($udom,$uname,
8673: $qualifierrest);
8674: }
8675: return $returnhash{$qualifierrest};
8676: }
8677: # ----------------------------------------------------------------- user.course
8678: } elsif ($space eq 'course') {
8679: # FIXME - not supporting calls for a specific user
8680: return $env{join('.',('request.course',$qualifier))};
8681: # ------------------------------------------------------------------- user.role
8682: } elsif ($space eq 'role') {
8683: # FIXME - not supporting calls for a specific user
8684: my ($role,$where)=split(/\./,$env{'request.role'});
8685: if ($qualifier eq 'value') {
8686: return $role;
8687: } elsif ($qualifier eq 'extent') {
8688: return $where;
8689: }
8690: # ----------------------------------------------------------------- user.domain
8691: } elsif ($space eq 'domain') {
8692: return $udom;
8693: # ------------------------------------------------------------------- user.name
8694: } elsif ($space eq 'name') {
8695: return $uname;
8696: # ---------------------------------------------------- Any other user namespace
8697: } else {
8698: my %reply;
8699: if (!$publicuser) {
8700: %reply=&get($space,[$qualifierrest],$udom,$uname);
8701: }
8702: return $reply{$qualifierrest};
8703: }
8704: } elsif ($realm eq 'query') {
8705: # ---------------------------------------------- pull stuff out of query string
8706: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8707: [$spacequalifierrest]);
8708: return $env{'form.'.$spacequalifierrest};
8709: } elsif ($realm eq 'request') {
8710: # ------------------------------------------------------------- request.browser
8711: if ($space eq 'browser') {
8712: if ($qualifier eq 'textremote') {
8713: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
8714: return 1;
8715: } else {
8716: return 0;
8717: }
8718: } else {
8719: return $env{'browser.'.$qualifier};
8720: }
8721: # ------------------------------------------------------------ request.filename
8722: } else {
8723: return $env{'request.'.$spacequalifierrest};
8724: }
8725: } elsif ($realm eq 'course') {
8726: # ---------------------------------------------------------- course.description
8727: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
8728: } elsif ($realm eq 'resource') {
8729:
8730: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
8731: if (!$symbparm) { $symbparm=&symbread(); }
8732: }
8733:
8734: if ($space eq 'title') {
8735: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8736: return &gettitle($symbparm);
8737: }
8738:
8739: if ($space eq 'map') {
8740: my ($map) = &decode_symb($symbparm);
8741: return &symbread($map);
8742: }
8743: if ($space eq 'filename') {
8744: if ($symbparm) {
8745: return &clutter((&decode_symb($symbparm))[2]);
8746: }
8747: return &hreflocation('',$env{'request.filename'});
8748: }
8749:
8750: my ($section, $group, @groups);
8751: my ($courselevelm,$courselevel);
8752: if ($symbparm && defined($courseid) &&
8753: $courseid eq $env{'request.course.id'}) {
8754:
8755: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
8756:
8757: # ----------------------------------------------------- Cascading lookup scheme
8758: my $symbp=$symbparm;
8759: my $mapp=&deversion((&decode_symb($symbp))[0]);
8760:
8761: my $symbparm=$symbp.'.'.$spacequalifierrest;
8762: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8763:
8764: if (($env{'user.name'} eq $uname) &&
8765: ($env{'user.domain'} eq $udom)) {
8766: $section=$env{'request.course.sec'};
8767: @groups = split(/:/,$env{'request.course.groups'});
8768: @groups=&sort_course_groups($courseid,@groups);
8769: } else {
8770: if (! defined($usection)) {
8771: $section=&getsection($udom,$uname,$courseid);
8772: } else {
8773: $section = $usection;
8774: }
8775: @groups = &get_users_groups($udom,$uname,$courseid);
8776: }
8777:
8778: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8779: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8780: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8781:
8782: $courselevel=$courseid.'.'.$spacequalifierrest;
8783: my $courselevelr=$courseid.'.'.$symbparm;
8784: $courselevelm=$courseid.'.'.$mapparm;
8785:
8786: # ----------------------------------------------------------- first, check user
8787:
8788: my $userreply=&resdata($uname,$udom,'user',
8789: ([$courselevelr,'resource'],
8790: [$courselevelm,'map' ],
8791: [$courselevel, 'course' ]));
8792: if (defined($userreply)) { return &get_reply($userreply); }
8793:
8794: # ------------------------------------------------ second, check some of course
8795: my $coursereply;
8796: if (@groups > 0) {
8797: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8798: $mapparm,$spacequalifierrest);
8799: if (defined($coursereply)) { return &get_reply($coursereply); }
8800: }
8801:
8802: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8803: $env{'course.'.$courseid.'.domain'},
8804: 'course',
8805: ([$seclevelr, 'resource'],
8806: [$seclevelm, 'map' ],
8807: [$seclevel, 'course' ],
8808: [$courselevelr,'resource']));
8809: if (defined($coursereply)) { return &get_reply($coursereply); }
8810:
8811: # ------------------------------------------------------ third, check map parms
8812: my %parmhash=();
8813: my $thisparm='';
8814: if (tie(%parmhash,'GDBM_File',
8815: $env{'request.course.fn'}.'_parms.db',
8816: &GDBM_READER(),0640)) {
8817: $thisparm=$parmhash{$symbparm};
8818: untie(%parmhash);
8819: }
8820: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
8821: }
8822: # ------------------------------------------ fourth, look in resource metadata
8823:
8824: $spacequalifierrest=~s/\./\_/;
8825: my $filename;
8826: if (!$symbparm) { $symbparm=&symbread(); }
8827: if ($symbparm) {
8828: $filename=(&decode_symb($symbparm))[2];
8829: } else {
8830: $filename=$env{'request.filename'};
8831: }
8832: my $metadata=&metadata($filename,$spacequalifierrest);
8833: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8834: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
8835: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8836:
8837: # ---------------------------------------------- fourth, look in rest of course
8838: if ($symbparm && defined($courseid) &&
8839: $courseid eq $env{'request.course.id'}) {
8840: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8841: $env{'course.'.$courseid.'.domain'},
8842: 'course',
8843: ([$courselevelm,'map' ],
8844: [$courselevel, 'course']));
8845: if (defined($coursereply)) { return &get_reply($coursereply); }
8846: }
8847: # ------------------------------------------------------------------ Cascade up
8848: unless ($space eq '0') {
8849: my @parts=split(/_/,$space);
8850: my $id=pop(@parts);
8851: my $part=join('_',@parts);
8852: if ($part eq '') { $part='0'; }
8853: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
8854: $symbparm,$udom,$uname,$section,1);
8855: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
8856: }
8857: if ($recurse) { return undef; }
8858: my $pack_def=&packages_tab_default($filename,$varname);
8859: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
8860: # ---------------------------------------------------- Any other user namespace
8861: } elsif ($realm eq 'environment') {
8862: # ----------------------------------------------------------------- environment
8863: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8864: return $env{'environment.'.$spacequalifierrest};
8865: } else {
8866: if ($uname eq 'anonymous' && $udom eq '') {
8867: return '';
8868: }
8869: my %returnhash=&userenvironment($udom,$uname,
8870: $spacequalifierrest);
8871: return $returnhash{$spacequalifierrest};
8872: }
8873: } elsif ($realm eq 'system') {
8874: # ----------------------------------------------------------------- system.time
8875: if ($space eq 'time') {
8876: return time;
8877: }
8878: } elsif ($realm eq 'server') {
8879: # ----------------------------------------------------------------- system.time
8880: if ($space eq 'name') {
8881: return $ENV{'SERVER_NAME'};
8882: }
8883: }
8884: return '';
8885: }
8886:
8887: sub get_reply {
8888: my ($reply_value) = @_;
8889: if (ref($reply_value) eq 'ARRAY') {
8890: if (wantarray) {
8891: return @$reply_value;
8892: }
8893: return $reply_value->[0];
8894: } else {
8895: return $reply_value;
8896: }
8897: }
8898:
8899: sub check_group_parms {
8900: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8901: my @groupitems = ();
8902: my $resultitem;
8903: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
8904: foreach my $group (@{$groups}) {
8905: foreach my $level (@levels) {
8906: my $item = $courseid.'.['.$group.'].'.$level->[0];
8907: push(@groupitems,[$item,$level->[1]]);
8908: }
8909: }
8910: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8911: $env{'course.'.$courseid.'.domain'},
8912: 'course',@groupitems);
8913: return $coursereply;
8914: }
8915:
8916: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
8917: my ($courseid,@groups) = @_;
8918: @groups = sort(@groups);
8919: return @groups;
8920: }
8921:
8922: sub packages_tab_default {
8923: my ($uri,$varname)=@_;
8924: my (undef,$part,$name)=split(/\./,$varname);
8925:
8926: my (@extension,@specifics,$do_default);
8927: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
8928: my ($pack_type,$pack_part)=split(/_/,$package,2);
8929: if ($pack_type eq 'default') {
8930: $do_default=1;
8931: } elsif ($pack_type eq 'extension') {
8932: push(@extension,[$package,$pack_type,$pack_part]);
8933: } elsif ($pack_part eq $part || $pack_type eq 'part') {
8934: # only look at packages defaults for packages that this id is
8935: push(@specifics,[$package,$pack_type,$pack_part]);
8936: }
8937: }
8938: # first look for a package that matches the requested part id
8939: foreach my $package (@specifics) {
8940: my (undef,$pack_type,$pack_part)=@{$package};
8941: next if ($pack_part ne $part);
8942: if (defined($packagetab{"$pack_type&$name&default"})) {
8943: return $packagetab{"$pack_type&$name&default"};
8944: }
8945: }
8946: # look for any possible matching non extension_ package
8947: foreach my $package (@specifics) {
8948: my (undef,$pack_type,$pack_part)=@{$package};
8949: if (defined($packagetab{"$pack_type&$name&default"})) {
8950: return $packagetab{"$pack_type&$name&default"};
8951: }
8952: if ($pack_type eq 'part') { $pack_part='0'; }
8953: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8954: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
8955: }
8956: }
8957: # look for any posible extension_ match
8958: foreach my $package (@extension) {
8959: my ($package,$pack_type)=@{$package};
8960: if (defined($packagetab{"$pack_type&$name&default"})) {
8961: return $packagetab{"$pack_type&$name&default"};
8962: }
8963: if (defined($packagetab{$package."&$name&default"})) {
8964: return $packagetab{$package."&$name&default"};
8965: }
8966: }
8967: # look for a global default setting
8968: if ($do_default && defined($packagetab{"default&$name&default"})) {
8969: return $packagetab{"default&$name&default"};
8970: }
8971: return undef;
8972: }
8973:
8974: sub add_prefix_and_part {
8975: my ($prefix,$part)=@_;
8976: my $keyroot;
8977: if (defined($prefix) && $prefix !~ /^__/) {
8978: # prefix that has a part already
8979: $keyroot=$prefix;
8980: } elsif (defined($prefix)) {
8981: # prefix that is missing a part
8982: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8983: } else {
8984: # no prefix at all
8985: if (defined($part)) { $keyroot='_'.$part; }
8986: }
8987: return $keyroot;
8988: }
8989:
8990: # ---------------------------------------------------------------- Get metadata
8991:
8992: my %metaentry;
8993: my %importedpartids;
8994: sub metadata {
8995: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
8996: $uri=&declutter($uri);
8997: # if it is a non metadata possible uri return quickly
8998: if (($uri eq '') ||
8999: (($uri =~ m|^/*adm/|) &&
9000: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9001: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9002: return undef;
9003: }
9004: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9005: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9006: return undef;
9007: }
9008: my $filename=$uri;
9009: $uri=~s/\.meta$//;
9010: #
9011: # Is the metadata already cached?
9012: # Look at timestamp of caching
9013: # Everything is cached by the main uri, libraries are never directly cached
9014: #
9015: if (!defined($liburi)) {
9016: my ($result,$cached)=&is_cached_new('meta',$uri);
9017: if (defined($cached)) { return $result->{':'.$what}; }
9018: }
9019: {
9020: # Imported parts would go here
9021: my %importedids=();
9022: my @origfileimportpartids=();
9023: my $importedparts=0;
9024: #
9025: # Is this a recursive call for a library?
9026: #
9027: # if (! exists($metacache{$uri})) {
9028: # $metacache{$uri}={};
9029: # }
9030: my $cachetime = 60*60;
9031: if ($liburi) {
9032: $liburi=&declutter($liburi);
9033: $filename=$liburi;
9034: } else {
9035: &devalidate_cache_new('meta',$uri);
9036: undef(%metaentry);
9037: }
9038: my %metathesekeys=();
9039: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9040: my $metastring;
9041: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9042: my $which = &hreflocation('','/'.($liburi || $uri));
9043: $metastring =
9044: &Apache::lonnet::ssi_body($which,
9045: ('grade_target' => 'meta'));
9046: $cachetime = 1; # only want this cached in the child not long term
9047: } elsif (($uri !~ m -^(editupload)/-) &&
9048: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9049: my $file=&filelocation('',&clutter($filename));
9050: #push(@{$metaentry{$uri.'.file'}},$file);
9051: $metastring=&getfile($file);
9052: }
9053: my $parser=HTML::LCParser->new(\$metastring);
9054: my $token;
9055: undef %metathesekeys;
9056: while ($token=$parser->get_token) {
9057: if ($token->[0] eq 'S') {
9058: if (defined($token->[2]->{'package'})) {
9059: #
9060: # This is a package - get package info
9061: #
9062: my $package=$token->[2]->{'package'};
9063: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9064: if (defined($token->[2]->{'id'})) {
9065: $keyroot.='_'.$token->[2]->{'id'};
9066: }
9067: if ($metaentry{':packages'}) {
9068: $metaentry{':packages'}.=','.$package.$keyroot;
9069: } else {
9070: $metaentry{':packages'}=$package.$keyroot;
9071: }
9072: foreach my $pack_entry (keys(%packagetab)) {
9073: my $part=$keyroot;
9074: $part=~s/^\_//;
9075: if ($pack_entry=~/^\Q$package\E\&/ ||
9076: $pack_entry=~/^\Q$package\E_0\&/) {
9077: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9078: # ignore package.tab specified default values
9079: # here &package_tab_default() will fetch those
9080: if ($subp eq 'default') { next; }
9081: my $value=$packagetab{$pack_entry};
9082: my $unikey;
9083: if ($pack =~ /_0$/) {
9084: $unikey='parameter_0_'.$name;
9085: $part=0;
9086: } else {
9087: $unikey='parameter'.$keyroot.'_'.$name;
9088: }
9089: if ($subp eq 'display') {
9090: $value.=' [Part: '.$part.']';
9091: }
9092: $metaentry{':'.$unikey.'.part'}=$part;
9093: $metathesekeys{$unikey}=1;
9094: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9095: $metaentry{':'.$unikey.'.'.$subp}=$value;
9096: }
9097: if (defined($metaentry{':'.$unikey.'.default'})) {
9098: $metaentry{':'.$unikey}=
9099: $metaentry{':'.$unikey.'.default'};
9100: }
9101: }
9102: }
9103: } else {
9104: #
9105: # This is not a package - some other kind of start tag
9106: #
9107: my $entry=$token->[1];
9108: my $unikey='';
9109:
9110: if ($entry eq 'import') {
9111: #
9112: # Importing a library here
9113: #
9114: my $location=$parser->get_text('/import');
9115: my $dir=$filename;
9116: $dir=~s|[^/]*$||;
9117: $location=&filelocation($dir,$location);
9118:
9119: my $importmode=$token->[2]->{'importmode'};
9120: if ($importmode eq 'problem') {
9121: # Import as problem/response
9122: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9123: } elsif ($importmode eq 'part') {
9124: # Import as part(s)
9125: $importedparts=1;
9126: # We need to get the original file and the imported file to get the part order correct
9127: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9128: # Load and inspect original file
9129: if ($#origfileimportpartids<0) {
9130: undef(%importedpartids);
9131: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9132: my $origfile=&getfile($origfilelocation);
9133: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9134: }
9135:
9136: # Load and inspect imported file
9137: my $impfile=&getfile($location);
9138: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9139: if ($#impfilepartids>=0) {
9140: # This problem had parts
9141: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9142: } else {
9143: # Importing by turning a single problem into a problem part
9144: # It gets the import-tags ID as part-ID
9145: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9146: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9147: }
9148: } else {
9149: # Normal import
9150: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9151: if (defined($token->[2]->{'id'})) {
9152: $unikey.='_'.$token->[2]->{'id'};
9153: }
9154: }
9155:
9156: if ($depthcount<20) {
9157: my $metadata =
9158: &metadata($uri,'keys', $location,$unikey,
9159: $depthcount+1);
9160: foreach my $meta (split(',',$metadata)) {
9161: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9162: $metathesekeys{$meta}=1;
9163: }
9164:
9165: }
9166: } else {
9167: #
9168: # Not importing, some other kind of non-package, non-library start tag
9169: #
9170: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9171: if (defined($token->[2]->{'id'})) {
9172: $unikey.='_'.$token->[2]->{'id'};
9173: }
9174: if (defined($token->[2]->{'name'})) {
9175: $unikey.='_'.$token->[2]->{'name'};
9176: }
9177: $metathesekeys{$unikey}=1;
9178: foreach my $param (@{$token->[3]}) {
9179: $metaentry{':'.$unikey.'.'.$param} =
9180: $token->[2]->{$param};
9181: }
9182: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9183: my $default=$metaentry{':'.$unikey.'.default'};
9184: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9185: # only ws inside the tag, and not in default, so use default
9186: # as value
9187: $metaentry{':'.$unikey}=$default;
9188: } elsif ( $internaltext =~ /\S/ ) {
9189: # something interesting inside the tag
9190: $metaentry{':'.$unikey}=$internaltext;
9191: } else {
9192: # no interesting values, don't set a default
9193: }
9194: # end of not-a-package not-a-library import
9195: }
9196: # end of not-a-package start tag
9197: }
9198: # the next is the end of "start tag"
9199: }
9200: }
9201: my ($extension) = ($uri =~ /\.(\w+)$/);
9202: $extension = lc($extension);
9203: if ($extension eq 'htm') { $extension='html'; }
9204:
9205: foreach my $key (keys(%packagetab)) {
9206: #no specific packages #how's our extension
9207: if ($key!~/^extension_\Q$extension\E&/) { next; }
9208: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9209: \%metathesekeys);
9210: }
9211:
9212: if (!exists($metaentry{':packages'})
9213: || $packagetab{"import_defaults&extension_$extension"}) {
9214: foreach my $key (keys(%packagetab)) {
9215: #no specific packages well let's get default then
9216: if ($key!~/^default&/) { next; }
9217: &metadata_create_package_def($uri,$key,'default',
9218: \%metathesekeys);
9219: }
9220: }
9221: # are there custom rights to evaluate
9222: if ($metaentry{':copyright'} eq 'custom') {
9223:
9224: #
9225: # Importing a rights file here
9226: #
9227: unless ($depthcount) {
9228: my $location=$metaentry{':customdistributionfile'};
9229: my $dir=$filename;
9230: $dir=~s|[^/]*$||;
9231: $location=&filelocation($dir,$location);
9232: my $rights_metadata =
9233: &metadata($uri,'keys',$location,'_rights',
9234: $depthcount+1);
9235: foreach my $rights (split(',',$rights_metadata)) {
9236: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9237: $metathesekeys{$rights}=1;
9238: }
9239: }
9240: }
9241: # uniqifiy package listing
9242: my %seen;
9243: my @uniq_packages =
9244: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9245: $metaentry{':packages'} = join(',',@uniq_packages);
9246:
9247: if ($importedparts) {
9248: # We had imported parts and need to rebuild partorder
9249: $metaentry{':partorder'}='';
9250: $metathesekeys{'partorder'}=1;
9251: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9252: if ($origfileimportpartids[$index] eq 'part') {
9253: # original part, part of the problem
9254: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9255: } else {
9256: # we have imported parts at this position
9257: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9258: }
9259: }
9260: $metaentry{':partorder'}=~s/^\,//;
9261: }
9262:
9263: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9264: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9265: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9266: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9267: # this is the end of "was not already recently cached
9268: }
9269: return $metaentry{':'.$what};
9270: }
9271:
9272: sub metadata_create_package_def {
9273: my ($uri,$key,$package,$metathesekeys)=@_;
9274: my ($pack,$name,$subp)=split(/\&/,$key);
9275: if ($subp eq 'default') { next; }
9276:
9277: if (defined($metaentry{':packages'})) {
9278: $metaentry{':packages'}.=','.$package;
9279: } else {
9280: $metaentry{':packages'}=$package;
9281: }
9282: my $value=$packagetab{$key};
9283: my $unikey;
9284: $unikey='parameter_0_'.$name;
9285: $metaentry{':'.$unikey.'.part'}=0;
9286: $$metathesekeys{$unikey}=1;
9287: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9288: $metaentry{':'.$unikey.'.'.$subp}=$value;
9289: }
9290: if (defined($metaentry{':'.$unikey.'.default'})) {
9291: $metaentry{':'.$unikey}=
9292: $metaentry{':'.$unikey.'.default'};
9293: }
9294: }
9295:
9296: sub metadata_generate_part0 {
9297: my ($metadata,$metacache,$uri) = @_;
9298: my %allnames;
9299: foreach my $metakey (keys(%$metadata)) {
9300: if ($metakey=~/^parameter\_(.*)/) {
9301: my $part=$$metacache{':'.$metakey.'.part'};
9302: my $name=$$metacache{':'.$metakey.'.name'};
9303: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9304: $allnames{$name}=$part;
9305: }
9306: }
9307: }
9308: foreach my $name (keys(%allnames)) {
9309: $$metadata{"parameter_0_$name"}=1;
9310: my $key=":parameter_0_$name";
9311: $$metacache{"$key.part"}='0';
9312: $$metacache{"$key.name"}=$name;
9313: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9314: $allnames{$name}.'_'.$name.
9315: '.type'};
9316: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9317: '.display'};
9318: my $expr='[Part: '.$allnames{$name}.']';
9319: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9320: $$metacache{"$key.display"}=$olddis;
9321: }
9322: }
9323:
9324: # ------------------------------------------------------ Devalidate title cache
9325:
9326: sub devalidate_title_cache {
9327: my ($url)=@_;
9328: if (!$env{'request.course.id'}) { return; }
9329: my $symb=&symbread($url);
9330: if (!$symb) { return; }
9331: my $key=$env{'request.course.id'}."\0".$symb;
9332: &devalidate_cache_new('title',$key);
9333: }
9334:
9335: # ------------------------------------------------- Get the title of a course
9336:
9337: sub current_course_title {
9338: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9339: }
9340: # ------------------------------------------------- Get the title of a resource
9341:
9342: sub gettitle {
9343: my $urlsymb=shift;
9344: my $symb=&symbread($urlsymb);
9345: if ($symb) {
9346: my $key=$env{'request.course.id'}."\0".$symb;
9347: my ($result,$cached)=&is_cached_new('title',$key);
9348: if (defined($cached)) {
9349: return $result;
9350: }
9351: my ($map,$resid,$url)=&decode_symb($symb);
9352: my $title='';
9353: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9354: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9355: } else {
9356: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9357: &GDBM_READER(),0640)) {
9358: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9359: $title=$bighash{'title_'.$mapid.'.'.$resid};
9360: untie(%bighash);
9361: }
9362: }
9363: $title=~s/\&colon\;/\:/gs;
9364: if ($title) {
9365: return &do_cache_new('title',$key,$title,600);
9366: }
9367: $urlsymb=$url;
9368: }
9369: my $title=&metadata($urlsymb,'title');
9370: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9371: return $title;
9372: }
9373:
9374: sub get_slot {
9375: my ($which,$cnum,$cdom)=@_;
9376: if (!$cnum || !$cdom) {
9377: (undef,my $courseid)=&whichuser();
9378: $cdom=$env{'course.'.$courseid.'.domain'};
9379: $cnum=$env{'course.'.$courseid.'.num'};
9380: }
9381: my $key=join("\0",'slots',$cdom,$cnum,$which);
9382: my %slotinfo;
9383: if (exists($remembered{$key})) {
9384: $slotinfo{$which} = $remembered{$key};
9385: } else {
9386: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9387: &Apache::lonhomework::showhash(%slotinfo);
9388: my ($tmp)=keys(%slotinfo);
9389: if ($tmp=~/^error:/) { return (); }
9390: $remembered{$key} = $slotinfo{$which};
9391: }
9392: if (ref($slotinfo{$which}) eq 'HASH') {
9393: return %{$slotinfo{$which}};
9394: }
9395: return $slotinfo{$which};
9396: }
9397: # ------------------------------------------------- Update symbolic store links
9398:
9399: sub symblist {
9400: my ($mapname,%newhash)=@_;
9401: $mapname=&deversion(&declutter($mapname));
9402: my %hash;
9403: if (($env{'request.course.fn'}) && (%newhash)) {
9404: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9405: &GDBM_WRCREAT(),0640)) {
9406: foreach my $url (keys(%newhash)) {
9407: next if ($url eq 'last_known'
9408: && $env{'form.no_update_last_known'});
9409: $hash{declutter($url)}=&encode_symb($mapname,
9410: $newhash{$url}->[1],
9411: $newhash{$url}->[0]);
9412: }
9413: if (untie(%hash)) {
9414: return 'ok';
9415: }
9416: }
9417: }
9418: return 'error';
9419: }
9420:
9421: # --------------------------------------------------------------- Verify a symb
9422:
9423: sub symbverify {
9424: my ($symb,$thisurl)=@_;
9425: my $thisfn=$thisurl;
9426: $thisfn=&declutter($thisfn);
9427: # direct jump to resource in page or to a sequence - will construct own symbs
9428: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9429: # check URL part
9430: my ($map,$resid,$url)=&decode_symb($symb);
9431:
9432: unless ($url eq $thisfn) { return 0; }
9433:
9434: $symb=&symbclean($symb);
9435: $thisurl=&deversion($thisurl);
9436: $thisfn=&deversion($thisfn);
9437:
9438: my %bighash;
9439: my $okay=0;
9440:
9441: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9442: &GDBM_READER(),0640)) {
9443: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9444: $thisurl =~ s/\?.+$//;
9445: }
9446: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9447: unless ($ids) {
9448: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9449: $ids=$bighash{$idkey};
9450: }
9451: if ($ids) {
9452: # ------------------------------------------------------------------- Has ID(s)
9453: foreach my $id (split(/\,/,$ids)) {
9454: my ($mapid,$resid)=split(/\./,$id);
9455: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9456: $symb =~ s/\?.+$//;
9457: }
9458: if (
9459: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9460: eq $symb) {
9461: if (($env{'request.role.adv'}) ||
9462: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9463: ($thisurl eq '/adm/navmaps')) {
9464: $okay=1;
9465: }
9466: }
9467: }
9468: }
9469: untie(%bighash);
9470: }
9471: return $okay;
9472: }
9473:
9474: # --------------------------------------------------------------- Clean-up symb
9475:
9476: sub symbclean {
9477: my $symb=shift;
9478: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9479: # remove version from map
9480: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9481:
9482: # remove version from URL
9483: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9484:
9485: # remove wrapper
9486:
9487: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9488: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9489: return $symb;
9490: }
9491:
9492: # ---------------------------------------------- Split symb to find map and url
9493:
9494: sub encode_symb {
9495: my ($map,$resid,$url)=@_;
9496: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9497: }
9498:
9499: sub decode_symb {
9500: my $symb=shift;
9501: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9502: my ($map,$resid,$url)=split(/___/,$symb);
9503: return (&fixversion($map),$resid,&fixversion($url));
9504: }
9505:
9506: sub fixversion {
9507: my $fn=shift;
9508: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9509: my %bighash;
9510: my $uri=&clutter($fn);
9511: my $key=$env{'request.course.id'}.'_'.$uri;
9512: # is this cached?
9513: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9514: if (defined($cached)) { return $result; }
9515: # unfortunately not cached, or expired
9516: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9517: &GDBM_READER(),0640)) {
9518: if ($bighash{'version_'.$uri}) {
9519: my $version=$bighash{'version_'.$uri};
9520: unless (($version eq 'mostrecent') ||
9521: ($version==&getversion($uri))) {
9522: $uri=~s/\.(\w+)$/\.$version\.$1/;
9523: }
9524: }
9525: untie %bighash;
9526: }
9527: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9528: }
9529:
9530: sub deversion {
9531: my $url=shift;
9532: $url=~s/\.\d+\.(\w+)$/\.$1/;
9533: return $url;
9534: }
9535:
9536: # ------------------------------------------------------ Return symb list entry
9537:
9538: sub symbread {
9539: my ($thisfn,$donotrecurse)=@_;
9540: my $cache_str='request.symbread.cached.'.$thisfn;
9541: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9542: # no filename provided? try from environment
9543: unless ($thisfn) {
9544: if ($env{'request.symb'}) {
9545: return $env{$cache_str}=&symbclean($env{'request.symb'});
9546: }
9547: $thisfn=$env{'request.filename'};
9548: }
9549: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9550: # is that filename actually a symb? Verify, clean, and return
9551: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9552: if (&symbverify($thisfn,$1)) {
9553: return $env{$cache_str}=&symbclean($thisfn);
9554: }
9555: }
9556: $thisfn=declutter($thisfn);
9557: my %hash;
9558: my %bighash;
9559: my $syval='';
9560: if (($env{'request.course.fn'}) && ($thisfn)) {
9561: my $targetfn = $thisfn;
9562: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9563: $targetfn = 'adm/wrapper/'.$thisfn;
9564: }
9565: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9566: $targetfn=$1;
9567: }
9568: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9569: &GDBM_READER(),0640)) {
9570: $syval=$hash{$targetfn};
9571: untie(%hash);
9572: }
9573: # ---------------------------------------------------------- There was an entry
9574: if ($syval) {
9575: #unless ($syval=~/\_\d+$/) {
9576: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9577: #&appenv({'request.ambiguous' => $thisfn});
9578: #return $env{$cache_str}='';
9579: #}
9580: #$syval.=$1;
9581: #}
9582: } else {
9583: # ------------------------------------------------------- Was not in symb table
9584: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9585: &GDBM_READER(),0640)) {
9586: # ---------------------------------------------- Get ID(s) for current resource
9587: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9588: unless ($ids) {
9589: $ids=$bighash{'ids_/'.$thisfn};
9590: }
9591: unless ($ids) {
9592: # alias?
9593: $ids=$bighash{'mapalias_'.$thisfn};
9594: }
9595: if ($ids) {
9596: # ------------------------------------------------------------------- Has ID(s)
9597: my @possibilities=split(/\,/,$ids);
9598: if ($#possibilities==0) {
9599: # ----------------------------------------------- There is only one possibility
9600: my ($mapid,$resid)=split(/\./,$ids);
9601: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9602: $resid,$thisfn);
9603: } elsif (!$donotrecurse) {
9604: # ------------------------------------------ There is more than one possibility
9605: my $realpossible=0;
9606: foreach my $id (@possibilities) {
9607: my $file=$bighash{'src_'.$id};
9608: if (&allowed('bre',$file)) {
9609: my ($mapid,$resid)=split(/\./,$id);
9610: if ($bighash{'map_type_'.$mapid} ne 'page') {
9611: $realpossible++;
9612: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9613: $resid,$thisfn);
9614: }
9615: }
9616: }
9617: if ($realpossible!=1) { $syval=''; }
9618: } else {
9619: $syval='';
9620: }
9621: }
9622: untie(%bighash)
9623: }
9624: }
9625: if ($syval) {
9626: return $env{$cache_str}=$syval;
9627: }
9628: }
9629: &appenv({'request.ambiguous' => $thisfn});
9630: return $env{$cache_str}='';
9631: }
9632:
9633: # ---------------------------------------------------------- Return random seed
9634:
9635: sub numval {
9636: my $txt=shift;
9637: $txt=~tr/A-J/0-9/;
9638: $txt=~tr/a-j/0-9/;
9639: $txt=~tr/K-T/0-9/;
9640: $txt=~tr/k-t/0-9/;
9641: $txt=~tr/U-Z/0-5/;
9642: $txt=~tr/u-z/0-5/;
9643: $txt=~s/\D//g;
9644: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9645: return int($txt);
9646: }
9647:
9648: sub numval2 {
9649: my $txt=shift;
9650: $txt=~tr/A-J/0-9/;
9651: $txt=~tr/a-j/0-9/;
9652: $txt=~tr/K-T/0-9/;
9653: $txt=~tr/k-t/0-9/;
9654: $txt=~tr/U-Z/0-5/;
9655: $txt=~tr/u-z/0-5/;
9656: $txt=~s/\D//g;
9657: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9658: my $total;
9659: foreach my $val (@txts) { $total+=$val; }
9660: if ($_64bit) { if ($total > 2**32) { return -1; } }
9661: return int($total);
9662: }
9663:
9664: sub numval3 {
9665: use integer;
9666: my $txt=shift;
9667: $txt=~tr/A-J/0-9/;
9668: $txt=~tr/a-j/0-9/;
9669: $txt=~tr/K-T/0-9/;
9670: $txt=~tr/k-t/0-9/;
9671: $txt=~tr/U-Z/0-5/;
9672: $txt=~tr/u-z/0-5/;
9673: $txt=~s/\D//g;
9674: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9675: my $total;
9676: foreach my $val (@txts) { $total+=$val; }
9677: if ($_64bit) { $total=(($total<<32)>>32); }
9678: return $total;
9679: }
9680:
9681: sub digest {
9682: my ($data)=@_;
9683: my $digest=&Digest::MD5::md5($data);
9684: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9685: my ($e,$f);
9686: {
9687: use integer;
9688: $e=($a+$b);
9689: $f=($c+$d);
9690: if ($_64bit) {
9691: $e=(($e<<32)>>32);
9692: $f=(($f<<32)>>32);
9693: }
9694: }
9695: if (wantarray) {
9696: return ($e,$f);
9697: } else {
9698: my $g;
9699: {
9700: use integer;
9701: $g=($e+$f);
9702: if ($_64bit) {
9703: $g=(($g<<32)>>32);
9704: }
9705: }
9706: return $g;
9707: }
9708: }
9709:
9710: sub latest_rnd_algorithm_id {
9711: return '64bit5';
9712: }
9713:
9714: sub get_rand_alg {
9715: my ($courseid)=@_;
9716: if (!$courseid) { $courseid=(&whichuser())[1]; }
9717: if ($courseid) {
9718: return $env{"course.$courseid.rndseed"};
9719: }
9720: return &latest_rnd_algorithm_id();
9721: }
9722:
9723: sub validCODE {
9724: my ($CODE)=@_;
9725: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9726: return 0;
9727: }
9728:
9729: sub getCODE {
9730: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
9731: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9732: defined($Apache::lonhomework::parsing_a_task) ) &&
9733: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
9734: return $Apache::lonhomework::history{'resource.CODE'};
9735: }
9736: return undef;
9737: }
9738: #
9739: # Determines the random seed for a specific context:
9740: #
9741: # parameters:
9742: # symb - in course context the symb for the seed.
9743: # course_id - The course id of the form domain_coursenum.
9744: # domain - Domain for the user.
9745: # course - Course for the user.
9746: # cenv - environment of the course.
9747: #
9748: # NOTE:
9749: # All parameters are picked out of the environment if missing
9750: # or not defined.
9751: # If a symb cannot be determined the current time is used instead.
9752: #
9753: # For a given well defined symb, courside, domain, username,
9754: # and course environment, the seed is reproducible.
9755: #
9756: sub rndseed {
9757: my ($symb,$courseid,$domain,$username, $cenv)=@_;
9758: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
9759: if (!defined($symb)) {
9760: unless ($symb=$wsymb) { return time; }
9761: }
9762: if (!$courseid) { $courseid=$wcourseid; }
9763: if (!$domain) { $domain=$wdomain; }
9764: if (!$username) { $username=$wusername }
9765:
9766: my $which;
9767: if (defined($cenv->{'rndseed'})) {
9768: $which = $cenv->{'rndseed'};
9769: } else {
9770: $which =&get_rand_alg($courseid);
9771: }
9772:
9773: if (defined(&getCODE())) {
9774:
9775: if ($which eq '64bit5') {
9776: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9777: } elsif ($which eq '64bit4') {
9778: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9779: } else {
9780: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9781: }
9782: } elsif ($which eq '64bit5') {
9783: return &rndseed_64bit5($symb,$courseid,$domain,$username);
9784: } elsif ($which eq '64bit4') {
9785: return &rndseed_64bit4($symb,$courseid,$domain,$username);
9786: } elsif ($which eq '64bit3') {
9787: return &rndseed_64bit3($symb,$courseid,$domain,$username);
9788: } elsif ($which eq '64bit2') {
9789: return &rndseed_64bit2($symb,$courseid,$domain,$username);
9790: } elsif ($which eq '64bit') {
9791: return &rndseed_64bit($symb,$courseid,$domain,$username);
9792: }
9793: return &rndseed_32bit($symb,$courseid,$domain,$username);
9794: }
9795:
9796: sub rndseed_32bit {
9797: my ($symb,$courseid,$domain,$username)=@_;
9798: {
9799: use integer;
9800: my $symbchck=unpack("%32C*",$symb) << 27;
9801: my $symbseed=numval($symb) << 22;
9802: my $namechck=unpack("%32C*",$username) << 17;
9803: my $nameseed=numval($username) << 12;
9804: my $domainseed=unpack("%32C*",$domain) << 7;
9805: my $courseseed=unpack("%32C*",$courseid);
9806: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
9807: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9808: #&logthis("rndseed :$num:$symb");
9809: if ($_64bit) { $num=(($num<<32)>>32); }
9810: return $num;
9811: }
9812: }
9813:
9814: sub rndseed_64bit {
9815: my ($symb,$courseid,$domain,$username)=@_;
9816: {
9817: use integer;
9818: my $symbchck=unpack("%32S*",$symb) << 21;
9819: my $symbseed=numval($symb) << 10;
9820: my $namechck=unpack("%32S*",$username);
9821:
9822: my $nameseed=numval($username) << 21;
9823: my $domainseed=unpack("%32S*",$domain) << 10;
9824: my $courseseed=unpack("%32S*",$courseid);
9825:
9826: my $num1=$symbchck+$symbseed+$namechck;
9827: my $num2=$nameseed+$domainseed+$courseseed;
9828: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9829: #&logthis("rndseed :$num:$symb");
9830: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9831: return "$num1,$num2";
9832: }
9833: }
9834:
9835: sub rndseed_64bit2 {
9836: my ($symb,$courseid,$domain,$username)=@_;
9837: {
9838: use integer;
9839: # strings need to be an even # of cahracters long, it it is odd the
9840: # last characters gets thrown away
9841: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9842: my $symbseed=numval($symb) << 10;
9843: my $namechck=unpack("%32S*",$username.' ');
9844:
9845: my $nameseed=numval($username) << 21;
9846: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9847: my $courseseed=unpack("%32S*",$courseid.' ');
9848:
9849: my $num1=$symbchck+$symbseed+$namechck;
9850: my $num2=$nameseed+$domainseed+$courseseed;
9851: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9852: #&logthis("rndseed :$num:$symb");
9853: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9854: return "$num1,$num2";
9855: }
9856: }
9857:
9858: sub rndseed_64bit3 {
9859: my ($symb,$courseid,$domain,$username)=@_;
9860: {
9861: use integer;
9862: # strings need to be an even # of cahracters long, it it is odd the
9863: # last characters gets thrown away
9864: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9865: my $symbseed=numval2($symb) << 10;
9866: my $namechck=unpack("%32S*",$username.' ');
9867:
9868: my $nameseed=numval2($username) << 21;
9869: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9870: my $courseseed=unpack("%32S*",$courseid.' ');
9871:
9872: my $num1=$symbchck+$symbseed+$namechck;
9873: my $num2=$nameseed+$domainseed+$courseseed;
9874: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9875: #&logthis("rndseed :$num1:$num2:$_64bit");
9876: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9877:
9878: return "$num1:$num2";
9879: }
9880: }
9881:
9882: sub rndseed_64bit4 {
9883: my ($symb,$courseid,$domain,$username)=@_;
9884: {
9885: use integer;
9886: # strings need to be an even # of cahracters long, it it is odd the
9887: # last characters gets thrown away
9888: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9889: my $symbseed=numval3($symb) << 10;
9890: my $namechck=unpack("%32S*",$username.' ');
9891:
9892: my $nameseed=numval3($username) << 21;
9893: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9894: my $courseseed=unpack("%32S*",$courseid.' ');
9895:
9896: my $num1=$symbchck+$symbseed+$namechck;
9897: my $num2=$nameseed+$domainseed+$courseseed;
9898: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9899: #&logthis("rndseed :$num1:$num2:$_64bit");
9900: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9901:
9902: return "$num1:$num2";
9903: }
9904: }
9905:
9906: sub rndseed_64bit5 {
9907: my ($symb,$courseid,$domain,$username)=@_;
9908: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9909: return "$num1:$num2";
9910: }
9911:
9912: sub rndseed_CODE_64bit {
9913: my ($symb,$courseid,$domain,$username)=@_;
9914: {
9915: use integer;
9916: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9917: my $symbseed=numval2($symb);
9918: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9919: my $CODEseed=numval(&getCODE());
9920: my $courseseed=unpack("%32S*",$courseid.' ');
9921: my $num1=$symbseed+$CODEchck;
9922: my $num2=$CODEseed+$courseseed+$symbchck;
9923: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9924: #&logthis("rndseed :$num1:$num2:$symb");
9925: if ($_64bit) { $num1=(($num1<<32)>>32); }
9926: if ($_64bit) { $num2=(($num2<<32)>>32); }
9927: return "$num1:$num2";
9928: }
9929: }
9930:
9931: sub rndseed_CODE_64bit4 {
9932: my ($symb,$courseid,$domain,$username)=@_;
9933: {
9934: use integer;
9935: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9936: my $symbseed=numval3($symb);
9937: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9938: my $CODEseed=numval3(&getCODE());
9939: my $courseseed=unpack("%32S*",$courseid.' ');
9940: my $num1=$symbseed+$CODEchck;
9941: my $num2=$CODEseed+$courseseed+$symbchck;
9942: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9943: #&logthis("rndseed :$num1:$num2:$symb");
9944: if ($_64bit) { $num1=(($num1<<32)>>32); }
9945: if ($_64bit) { $num2=(($num2<<32)>>32); }
9946: return "$num1:$num2";
9947: }
9948: }
9949:
9950: sub rndseed_CODE_64bit5 {
9951: my ($symb,$courseid,$domain,$username)=@_;
9952: my $code = &getCODE();
9953: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9954: return "$num1:$num2";
9955: }
9956:
9957: sub setup_random_from_rndseed {
9958: my ($rndseed)=@_;
9959: if ($rndseed =~/([,:])/) {
9960: my ($num1,$num2)=split(/[,:]/,$rndseed);
9961: &Math::Random::random_set_seed(abs($num1),abs($num2));
9962: } else {
9963: &Math::Random::random_set_seed_from_phrase($rndseed);
9964: }
9965: }
9966:
9967: sub latest_receipt_algorithm_id {
9968: return 'receipt3';
9969: }
9970:
9971: sub recunique {
9972: my $fucourseid=shift;
9973: my $unique;
9974: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9975: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9976: $unique=$env{"course.$fucourseid.internal.encseed"};
9977: } else {
9978: $unique=$perlvar{'lonReceipt'};
9979: }
9980: return unpack("%32C*",$unique);
9981: }
9982:
9983: sub recprefix {
9984: my $fucourseid=shift;
9985: my $prefix;
9986: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9987: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9988: $prefix=$env{"course.$fucourseid.internal.encpref"};
9989: } else {
9990: $prefix=$perlvar{'lonHostID'};
9991: }
9992: return unpack("%32C*",$prefix);
9993: }
9994:
9995: sub ireceipt {
9996: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
9997:
9998: my $return =&recprefix($fucourseid).'-';
9999:
10000: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10001: $env{'request.state'} eq 'construct') {
10002: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10003: return $return;
10004: }
10005:
10006: my $cuname=unpack("%32C*",$funame);
10007: my $cudom=unpack("%32C*",$fudom);
10008: my $cucourseid=unpack("%32C*",$fucourseid);
10009: my $cusymb=unpack("%32C*",$fusymb);
10010: my $cunique=&recunique($fucourseid);
10011: my $cpart=unpack("%32S*",$part);
10012: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10013:
10014: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10015:
10016: $return.= ($cunique%$cuname+
10017: $cunique%$cudom+
10018: $cusymb%$cuname+
10019: $cusymb%$cudom+
10020: $cucourseid%$cuname+
10021: $cucourseid%$cudom+
10022: $cpart%$cuname+
10023: $cpart%$cudom);
10024: } else {
10025: $return.= ($cunique%$cuname+
10026: $cunique%$cudom+
10027: $cusymb%$cuname+
10028: $cusymb%$cudom+
10029: $cucourseid%$cuname+
10030: $cucourseid%$cudom);
10031: }
10032: return $return;
10033: }
10034:
10035: sub receipt {
10036: my ($part)=@_;
10037: my ($symb,$courseid,$domain,$name) = &whichuser();
10038: return &ireceipt($name,$domain,$courseid,$symb,$part);
10039: }
10040:
10041: sub whichuser {
10042: my ($passedsymb)=@_;
10043: my ($symb,$courseid,$domain,$name,$publicuser);
10044: if (defined($env{'form.grade_symb'})) {
10045: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10046: my $allowed=&allowed('vgr',$tmp_courseid);
10047: if (!$allowed &&
10048: exists($env{'request.course.sec'}) &&
10049: $env{'request.course.sec'} !~ /^\s*$/) {
10050: $allowed=&allowed('vgr',$tmp_courseid.
10051: '/'.$env{'request.course.sec'});
10052: }
10053: if ($allowed) {
10054: ($symb)=&get_env_multiple('form.grade_symb');
10055: $courseid=$tmp_courseid;
10056: ($domain)=&get_env_multiple('form.grade_domain');
10057: ($name)=&get_env_multiple('form.grade_username');
10058: return ($symb,$courseid,$domain,$name,$publicuser);
10059: }
10060: }
10061: if (!$passedsymb) {
10062: $symb=&symbread();
10063: } else {
10064: $symb=$passedsymb;
10065: }
10066: $courseid=$env{'request.course.id'};
10067: $domain=$env{'user.domain'};
10068: $name=$env{'user.name'};
10069: if ($name eq 'public' && $domain eq 'public') {
10070: if (!defined($env{'form.username'})) {
10071: $env{'form.username'}.=time.rand(10000000);
10072: }
10073: $name.=$env{'form.username'};
10074: }
10075: return ($symb,$courseid,$domain,$name,$publicuser);
10076:
10077: }
10078:
10079: # ------------------------------------------------------------ Serves up a file
10080: # returns either the contents of the file or
10081: # -1 if the file doesn't exist
10082: #
10083: # if the target is a file that was uploaded via DOCS,
10084: # a check will be made to see if a current copy exists on the local server,
10085: # if it does this will be served, otherwise a copy will be retrieved from
10086: # the home server for the course and stored in /home/httpd/html/userfiles on
10087: # the local server.
10088:
10089: sub getfile {
10090: my ($file) = @_;
10091: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10092: &repcopy($file);
10093: return &readfile($file);
10094: }
10095:
10096: sub repcopy_userfile {
10097: my ($file)=@_;
10098: my $londocroot = $perlvar{'lonDocRoot'};
10099: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10100: if ($file =~ m{^\Q$londocroot/lonUsers/\E}) { return 'ok'; }
10101: my ($cdom,$cnum,$filename) =
10102: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10103: my $uri="/uploaded/$cdom/$cnum/$filename";
10104: if (-e "$file") {
10105: # we already have a local copy, check it out
10106: my @fileinfo = stat($file);
10107: my $rtncode;
10108: my $info;
10109: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10110: if ($lwpresp ne 'ok') {
10111: # there is no such file anymore, even though we had a local copy
10112: if ($rtncode eq '404') {
10113: unlink($file);
10114: }
10115: return -1;
10116: }
10117: if ($info < $fileinfo[9]) {
10118: # nice, the file we have is up-to-date, just say okay
10119: return 'ok';
10120: } else {
10121: # the file is outdated, get rid of it
10122: unlink($file);
10123: }
10124: }
10125: # one way or the other, at this point, we don't have the file
10126: # construct the correct path for the file
10127: my @parts = ($cdom,$cnum);
10128: if ($filename =~ m|^(.+)/[^/]+$|) {
10129: push @parts, split(/\//,$1);
10130: }
10131: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10132: foreach my $part (@parts) {
10133: $path .= '/'.$part;
10134: if (!-e $path) {
10135: mkdir($path,0770);
10136: }
10137: }
10138: # now the path exists for sure
10139: # get a user agent
10140: my $ua=new LWP::UserAgent;
10141: my $transferfile=$file.'.in.transfer';
10142: # FIXME: this should flock
10143: if (-e $transferfile) { return 'ok'; }
10144: my $request;
10145: $uri=~s/^\///;
10146: my $homeserver = &homeserver($cnum,$cdom);
10147: my $protocol = $protocol{$homeserver};
10148: $protocol = 'http' if ($protocol ne 'https');
10149: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10150: my $response=$ua->request($request,$transferfile);
10151: # did it work?
10152: if ($response->is_error()) {
10153: unlink($transferfile);
10154: &logthis("Userfile repcopy failed for $uri");
10155: return -1;
10156: }
10157: # worked, rename the transfer file
10158: rename($transferfile,$file);
10159: return 'ok';
10160: }
10161:
10162: sub tokenwrapper {
10163: my $uri=shift;
10164: $uri=~s|^https?\://([^/]+)||;
10165: $uri=~s|^/||;
10166: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10167: my $token=$1;
10168: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10169: if ($udom && $uname && $file) {
10170: $file=~s|(\?\.*)*$||;
10171: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10172: my $homeserver = &homeserver($uname,$udom);
10173: my $protocol = $protocol{$homeserver};
10174: $protocol = 'http' if ($protocol ne 'https');
10175: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10176: (($uri=~/\?/)?'&':'?').'token='.$token.
10177: '&tokenissued='.$perlvar{'lonHostID'};
10178: } else {
10179: return '/adm/notfound.html';
10180: }
10181: }
10182:
10183: # call with reqtype HEAD: get last modification time
10184: # call with reqtype GET: get the file contents
10185: # Do not call this with reqtype GET for large files! It loads everything into memory
10186: #
10187: sub getuploaded {
10188: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10189: $uri=~s/^\///;
10190: my $homeserver = &homeserver($cnum,$cdom);
10191: my $protocol = $protocol{$homeserver};
10192: $protocol = 'http' if ($protocol ne 'https');
10193: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10194: my $ua=new LWP::UserAgent;
10195: my $request=new HTTP::Request($reqtype,$uri);
10196: my $response=$ua->request($request);
10197: $$rtncode = $response->code;
10198: if (! $response->is_success()) {
10199: return 'failed';
10200: }
10201: if ($reqtype eq 'HEAD') {
10202: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10203: } elsif ($reqtype eq 'GET') {
10204: $$info = $response->content;
10205: }
10206: return 'ok';
10207: }
10208:
10209: sub readfile {
10210: my $file = shift;
10211: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10212: my $fh;
10213: open($fh,"<$file");
10214: my $a='';
10215: while (my $line = <$fh>) { $a .= $line; }
10216: return $a;
10217: }
10218:
10219: sub filelocation {
10220: my ($dir,$file) = @_;
10221: my $location;
10222: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10223:
10224: if ($file =~ m-^/adm/-) {
10225: $file=~s-^/adm/wrapper/-/-;
10226: $file=~s-^/adm/coursedocs/showdoc/-/-;
10227: }
10228:
10229: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10230: $location = $file;
10231: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10232: my ($udom,$uname,$filename)=
10233: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10234: my $home=&homeserver($uname,$udom);
10235: my $is_me=0;
10236: my @ids=¤t_machine_ids();
10237: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10238: if ($is_me) {
10239: $location=propath($udom,$uname).'/userfiles/'.$filename;
10240: } else {
10241: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10242: $udom.'/'.$uname.'/'.$filename;
10243: }
10244: } elsif ($file =~ m-^/adm/-) {
10245: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10246: } else {
10247: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10248: $file=~s:^/(res|priv)/:/:;
10249: my $space=$1;
10250: if ( !( $file =~ m:^/:) ) {
10251: $location = $dir. '/'.$file;
10252: } else {
10253: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10254: }
10255: }
10256: $location=~s://+:/:g; # remove duplicate /
10257: while ($location=~m{/\.\./}) {
10258: if ($location =~ m{/[^/]+/\.\./}) {
10259: $location=~ s{/[^/]+/\.\./}{/}g;
10260: } else {
10261: $location=~ s{/\.\./}{/}g;
10262: }
10263: } #remove dir/..
10264: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10265: return $location;
10266: }
10267:
10268: sub hreflocation {
10269: my ($dir,$file)=@_;
10270: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10271: $file=filelocation($dir,$file);
10272: } elsif ($file=~m-^/adm/-) {
10273: $file=~s-^/adm/wrapper/-/-;
10274: $file=~s-^/adm/coursedocs/showdoc/-/-;
10275: }
10276: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10277: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10278: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10279: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10280: {/uploaded/$1/$2/}x;
10281: }
10282: if ($file=~ m{^/userfiles/}) {
10283: $file =~ s{^/userfiles/}{/uploaded/};
10284: }
10285: return $file;
10286: }
10287:
10288:
10289:
10290:
10291:
10292: sub current_machine_domains {
10293: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10294: }
10295:
10296: sub machine_domains {
10297: my ($hostname) = @_;
10298: my @domains;
10299: my %hostname = &all_hostnames();
10300: while( my($id, $name) = each(%hostname)) {
10301: # &logthis("-$id-$name-$hostname-");
10302: if ($hostname eq $name) {
10303: push(@domains,&host_domain($id));
10304: }
10305: }
10306: return @domains;
10307: }
10308:
10309: sub current_machine_ids {
10310: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10311: }
10312:
10313: sub machine_ids {
10314: my ($hostname) = @_;
10315: $hostname ||= &hostname($perlvar{'lonHostID'});
10316: my @ids;
10317: my %name_to_host = &all_names();
10318: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10319: return @{ $name_to_host{$hostname} };
10320: }
10321: return;
10322: }
10323:
10324: sub additional_machine_domains {
10325: my @domains;
10326: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10327: while( my $line = <$fh>) {
10328: $line =~ s/\s//g;
10329: push(@domains,$line);
10330: }
10331: return @domains;
10332: }
10333:
10334: sub default_login_domain {
10335: my $domain = $perlvar{'lonDefDomain'};
10336: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10337: foreach my $posdom (¤t_machine_domains(),
10338: &additional_machine_domains()) {
10339: if (lc($posdom) eq lc($testdomain)) {
10340: $domain=$posdom;
10341: last;
10342: }
10343: }
10344: return $domain;
10345: }
10346:
10347: # ------------------------------------------------------------- Declutters URLs
10348:
10349: sub declutter {
10350: my $thisfn=shift;
10351: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10352: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10353: $thisfn=~s/^\///;
10354: $thisfn=~s|^adm/wrapper/||;
10355: $thisfn=~s|^adm/coursedocs/showdoc/||;
10356: $thisfn=~s/^res\///;
10357: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10358: $thisfn=~s/\?.+$//;
10359: }
10360: return $thisfn;
10361: }
10362:
10363: # ------------------------------------------------------------- Clutter up URLs
10364:
10365: sub clutter {
10366: my $thisfn='/'.&declutter(shift);
10367: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10368: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10369: $thisfn='/res'.$thisfn;
10370: }
10371: if ($thisfn !~m|^/adm|) {
10372: if ($thisfn =~ m|^/ext/|) {
10373: $thisfn='/adm/wrapper'.$thisfn;
10374: } else {
10375: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10376: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10377: if ($embstyle eq 'ssi'
10378: || ($embstyle eq 'hdn')
10379: || ($embstyle eq 'rat')
10380: || ($embstyle eq 'prv')
10381: || ($embstyle eq 'ign')) {
10382: #do nothing with these
10383: } elsif (($embstyle eq 'img')
10384: || ($embstyle eq 'emb')
10385: || ($embstyle eq 'wrp')) {
10386: $thisfn='/adm/wrapper'.$thisfn;
10387: } elsif ($embstyle eq 'unk'
10388: && $thisfn!~/\.(sequence|page)$/) {
10389: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10390: } else {
10391: # &logthis("Got a blank emb style");
10392: }
10393: }
10394: }
10395: return $thisfn;
10396: }
10397:
10398: sub clutter_with_no_wrapper {
10399: my $uri = &clutter(shift);
10400: if ($uri =~ m-^/adm/-) {
10401: $uri =~ s-^/adm/wrapper/-/-;
10402: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10403: }
10404: return $uri;
10405: }
10406:
10407: sub freeze_escape {
10408: my ($value)=@_;
10409: if (ref($value)) {
10410: $value=&nfreeze($value);
10411: return '__FROZEN__'.&escape($value);
10412: }
10413: return &escape($value);
10414: }
10415:
10416:
10417: sub thaw_unescape {
10418: my ($value)=@_;
10419: if ($value =~ /^__FROZEN__/) {
10420: substr($value,0,10,undef);
10421: $value=&unescape($value);
10422: return &thaw($value);
10423: }
10424: return &unescape($value);
10425: }
10426:
10427: sub correct_line_ends {
10428: my ($result)=@_;
10429: $$result =~s/\r\n/\n/mg;
10430: $$result =~s/\r/\n/mg;
10431: }
10432: # ================================================================ Main Program
10433:
10434: sub goodbye {
10435: &logthis("Starting Shut down");
10436: #not converted to using infrastruture and probably shouldn't be
10437: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10438: #converted
10439: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10440: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10441: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10442: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10443: #1.1 only
10444: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10445: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10446: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10447: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10448: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10449: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10450: &logthis(sprintf("%-20s is %s",'hits',$hits));
10451: &flushcourselogs();
10452: &logthis("Shutting down");
10453: }
10454:
10455: sub get_dns {
10456: my ($url,$func,$ignore_cache) = @_;
10457: if (!$ignore_cache) {
10458: my ($content,$cached)=
10459: &Apache::lonnet::is_cached_new('dns',$url);
10460: if ($cached) {
10461: &$func($content);
10462: return;
10463: }
10464: }
10465:
10466: my %alldns;
10467: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10468: foreach my $dns (<$config>) {
10469: next if ($dns !~ /^\^(\S*)/x);
10470: my $line = $1;
10471: my ($host,$protocol) = split(/:/,$line);
10472: if ($protocol ne 'https') {
10473: $protocol = 'http';
10474: }
10475: $alldns{$host} = $protocol;
10476: }
10477: while (%alldns) {
10478: my ($dns) = keys(%alldns);
10479: my $ua=new LWP::UserAgent;
10480: $ua->timeout(30);
10481: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10482: my $response=$ua->request($request);
10483: delete($alldns{$dns});
10484: next if ($response->is_error());
10485: my @content = split("\n",$response->content);
10486: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10487: &$func(\@content);
10488: return;
10489: }
10490: close($config);
10491: my $which = (split('/',$url))[3];
10492: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10493: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10494: my @content = <$config>;
10495: &$func(\@content);
10496: return;
10497: }
10498: # ------------------------------------------------------------ Read domain file
10499: {
10500: my $loaded;
10501: my %domain;
10502:
10503: sub parse_domain_tab {
10504: my ($lines) = @_;
10505: foreach my $line (@$lines) {
10506: next if ($line =~ /^(\#|\s*$ )/x);
10507:
10508: chomp($line);
10509: my ($name,@elements) = split(/:/,$line,9);
10510: my %this_domain;
10511: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10512: 'lang_def', 'city', 'longi', 'lati',
10513: 'primary') {
10514: $this_domain{$field} = shift(@elements);
10515: }
10516: $domain{$name} = \%this_domain;
10517: }
10518: }
10519:
10520: sub reset_domain_info {
10521: undef($loaded);
10522: undef(%domain);
10523: }
10524:
10525: sub load_domain_tab {
10526: my ($ignore_cache) = @_;
10527: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10528: my $fh;
10529: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10530: my @lines = <$fh>;
10531: &parse_domain_tab(\@lines);
10532: }
10533: close($fh);
10534: $loaded = 1;
10535: }
10536:
10537: sub domain {
10538: &load_domain_tab() if (!$loaded);
10539:
10540: my ($name,$what) = @_;
10541: return if ( !exists($domain{$name}) );
10542:
10543: if (!$what) {
10544: return $domain{$name}{'description'};
10545: }
10546: return $domain{$name}{$what};
10547: }
10548:
10549: sub domain_info {
10550: &load_domain_tab() if (!$loaded);
10551: return %domain;
10552: }
10553:
10554: }
10555:
10556:
10557: # ------------------------------------------------------------- Read hosts file
10558: {
10559: my %hostname;
10560: my %hostdom;
10561: my %libserv;
10562: my $loaded;
10563: my %name_to_host;
10564: my %internetdom;
10565: my %LC_dns_serv;
10566:
10567: sub parse_hosts_tab {
10568: my ($file) = @_;
10569: foreach my $configline (@$file) {
10570: next if ($configline =~ /^(\#|\s*$ )/x);
10571: chomp($configline);
10572: if ($configline =~ /^\^/) {
10573: if ($configline =~ /^\^([\w.\-]+)/) {
10574: $LC_dns_serv{$1} = 1;
10575: }
10576: next;
10577: }
10578: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10579: $name=~s/\s//g;
10580: if ($id && $domain && $role && $name) {
10581: $hostname{$id}=$name;
10582: push(@{$name_to_host{$name}}, $id);
10583: $hostdom{$id}=$domain;
10584: if ($role eq 'library') { $libserv{$id}=$name; }
10585: if (defined($protocol)) {
10586: if ($protocol eq 'https') {
10587: $protocol{$id} = $protocol;
10588: } else {
10589: $protocol{$id} = 'http';
10590: }
10591: } else {
10592: $protocol{$id} = 'http';
10593: }
10594: if (defined($intdom)) {
10595: $internetdom{$id} = $intdom;
10596: }
10597: }
10598: }
10599: }
10600:
10601: sub reset_hosts_info {
10602: &purge_remembered();
10603: &reset_domain_info();
10604: &reset_hosts_ip_info();
10605: undef(%name_to_host);
10606: undef(%hostname);
10607: undef(%hostdom);
10608: undef(%libserv);
10609: undef($loaded);
10610: }
10611:
10612: sub load_hosts_tab {
10613: my ($ignore_cache) = @_;
10614: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10615: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10616: my @config = <$config>;
10617: &parse_hosts_tab(\@config);
10618: close($config);
10619: $loaded=1;
10620: }
10621:
10622: sub hostname {
10623: &load_hosts_tab() if (!$loaded);
10624:
10625: my ($lonid) = @_;
10626: return $hostname{$lonid};
10627: }
10628:
10629: sub all_hostnames {
10630: &load_hosts_tab() if (!$loaded);
10631:
10632: return %hostname;
10633: }
10634:
10635: sub all_names {
10636: &load_hosts_tab() if (!$loaded);
10637:
10638: return %name_to_host;
10639: }
10640:
10641: sub all_host_domain {
10642: &load_hosts_tab() if (!$loaded);
10643: return %hostdom;
10644: }
10645:
10646: sub is_library {
10647: &load_hosts_tab() if (!$loaded);
10648:
10649: return exists($libserv{$_[0]});
10650: }
10651:
10652: sub all_library {
10653: &load_hosts_tab() if (!$loaded);
10654:
10655: return %libserv;
10656: }
10657:
10658: sub unique_library {
10659: #2x reverse removes all hostnames that appear more than once
10660: my %unique = reverse &all_library();
10661: return reverse %unique;
10662: }
10663:
10664: sub get_servers {
10665: &load_hosts_tab() if (!$loaded);
10666:
10667: my ($domain,$type) = @_;
10668: my %possible_hosts = ($type eq 'library') ? %libserv
10669: : %hostname;
10670: my %result;
10671: if (ref($domain) eq 'ARRAY') {
10672: while ( my ($host,$hostname) = each(%possible_hosts)) {
10673: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10674: $result{$host} = $hostname;
10675: }
10676: }
10677: } else {
10678: while ( my ($host,$hostname) = each(%possible_hosts)) {
10679: if ($hostdom{$host} eq $domain) {
10680: $result{$host} = $hostname;
10681: }
10682: }
10683: }
10684: return %result;
10685: }
10686:
10687: sub get_unique_servers {
10688: my %unique = reverse &get_servers(@_);
10689: return reverse %unique;
10690: }
10691:
10692: sub host_domain {
10693: &load_hosts_tab() if (!$loaded);
10694:
10695: my ($lonid) = @_;
10696: return $hostdom{$lonid};
10697: }
10698:
10699: sub all_domains {
10700: &load_hosts_tab() if (!$loaded);
10701:
10702: my %seen;
10703: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10704: return @uniq;
10705: }
10706:
10707: sub internet_dom {
10708: &load_hosts_tab() if (!$loaded);
10709:
10710: my ($lonid) = @_;
10711: return $internetdom{$lonid};
10712: }
10713:
10714: sub is_LC_dns {
10715: &load_hosts_tab() if (!$loaded);
10716:
10717: my ($hostname) = @_;
10718: return exists($LC_dns_serv{$hostname});
10719: }
10720:
10721: }
10722:
10723: {
10724: my %iphost;
10725: my %name_to_ip;
10726: my %lonid_to_ip;
10727:
10728: sub get_hosts_from_ip {
10729: my ($ip) = @_;
10730: my %iphosts = &get_iphost();
10731: if (ref($iphosts{$ip})) {
10732: return @{$iphosts{$ip}};
10733: }
10734: return;
10735: }
10736:
10737: sub reset_hosts_ip_info {
10738: undef(%iphost);
10739: undef(%name_to_ip);
10740: undef(%lonid_to_ip);
10741: }
10742:
10743: sub get_host_ip {
10744: my ($lonid) = @_;
10745: if (exists($lonid_to_ip{$lonid})) {
10746: return $lonid_to_ip{$lonid};
10747: }
10748: my $name=&hostname($lonid);
10749: my $ip = gethostbyname($name);
10750: return if (!$ip || length($ip) ne 4);
10751: $ip=inet_ntoa($ip);
10752: $name_to_ip{$name} = $ip;
10753: $lonid_to_ip{$lonid} = $ip;
10754: return $ip;
10755: }
10756:
10757: sub get_iphost {
10758: my ($ignore_cache) = @_;
10759:
10760: if (!$ignore_cache) {
10761: if (%iphost) {
10762: return %iphost;
10763: }
10764: my ($ip_info,$cached)=
10765: &Apache::lonnet::is_cached_new('iphost','iphost');
10766: if ($cached) {
10767: %iphost = %{$ip_info->[0]};
10768: %name_to_ip = %{$ip_info->[1]};
10769: %lonid_to_ip = %{$ip_info->[2]};
10770: return %iphost;
10771: }
10772: }
10773:
10774: # get yesterday's info for fallback
10775: my %old_name_to_ip;
10776: my ($ip_info,$cached)=
10777: &Apache::lonnet::is_cached_new('iphost','iphost');
10778: if ($cached) {
10779: %old_name_to_ip = %{$ip_info->[1]};
10780: }
10781:
10782: my %name_to_host = &all_names();
10783: foreach my $name (keys(%name_to_host)) {
10784: my $ip;
10785: if (!exists($name_to_ip{$name})) {
10786: $ip = gethostbyname($name);
10787: if (!$ip || length($ip) ne 4) {
10788: if (defined($old_name_to_ip{$name})) {
10789: $ip = $old_name_to_ip{$name};
10790: &logthis("Can't find $name defaulting to old $ip");
10791: } else {
10792: &logthis("Name $name no IP found");
10793: next;
10794: }
10795: } else {
10796: $ip=inet_ntoa($ip);
10797: }
10798: $name_to_ip{$name} = $ip;
10799: } else {
10800: $ip = $name_to_ip{$name};
10801: }
10802: foreach my $id (@{ $name_to_host{$name} }) {
10803: $lonid_to_ip{$id} = $ip;
10804: }
10805: push(@{$iphost{$ip}},@{$name_to_host{$name}});
10806: }
10807: &Apache::lonnet::do_cache_new('iphost','iphost',
10808: [\%iphost,\%name_to_ip,\%lonid_to_ip],
10809: 48*60*60);
10810:
10811: return %iphost;
10812: }
10813:
10814: #
10815: # Given a DNS returns the loncapa host name for that DNS
10816: #
10817: sub host_from_dns {
10818: my ($dns) = @_;
10819: my @hosts;
10820: my $ip;
10821:
10822: if (exists($name_to_ip{$dns})) {
10823: $ip = $name_to_ip{$dns};
10824: }
10825: if (!$ip) {
10826: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10827: if (length($ip) == 4) {
10828: $ip = &IO::Socket::inet_ntoa($ip);
10829: }
10830: }
10831: if ($ip) {
10832: @hosts = get_hosts_from_ip($ip);
10833: return $hosts[0];
10834: }
10835: return undef;
10836: }
10837:
10838: sub get_internet_names {
10839: my ($lonid) = @_;
10840: return if ($lonid eq '');
10841: my ($idnref,$cached)=
10842: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10843: if ($cached) {
10844: return $idnref;
10845: }
10846: my $ip = &get_host_ip($lonid);
10847: my @hosts = &get_hosts_from_ip($ip);
10848: my %iphost = &get_iphost();
10849: my (@idns,%seen);
10850: foreach my $id (@hosts) {
10851: my $dom = &host_domain($id);
10852: my $prim_id = &domain($dom,'primary');
10853: my $prim_ip = &get_host_ip($prim_id);
10854: next if ($seen{$prim_ip});
10855: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10856: foreach my $id (@{$iphost{$prim_ip}}) {
10857: my $intdom = &internet_dom($id);
10858: unless (grep(/^\Q$intdom\E$/,@idns)) {
10859: push(@idns,$intdom);
10860: }
10861: }
10862: }
10863: $seen{$prim_ip} = 1;
10864: }
10865: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10866: }
10867:
10868: }
10869:
10870: sub all_loncaparevs {
10871: 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);
10872: }
10873:
10874: BEGIN {
10875:
10876: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10877: unless ($readit) {
10878: {
10879: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10880: %perlvar = (%perlvar,%{$configvars});
10881: }
10882:
10883:
10884: # ------------------------------------------------------ Read spare server file
10885: {
10886: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10887:
10888: while (my $configline=<$config>) {
10889: chomp($configline);
10890: if ($configline) {
10891: my ($host,$type) = split(':',$configline,2);
10892: if (!defined($type) || $type eq '') { $type = 'default' };
10893: push(@{ $spareid{$type} }, $host);
10894: }
10895: }
10896: close($config);
10897: }
10898: # ------------------------------------------------------------ Read permissions
10899: {
10900: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10901:
10902: while (my $configline=<$config>) {
10903: chomp($configline);
10904: if ($configline) {
10905: my ($role,$perm)=split(/ /,$configline);
10906: if ($perm ne '') { $pr{$role}=$perm; }
10907: }
10908: }
10909: close($config);
10910: }
10911:
10912: # -------------------------------------------- Read plain texts for permissions
10913: {
10914: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10915:
10916: while (my $configline=<$config>) {
10917: chomp($configline);
10918: if ($configline) {
10919: my ($short,@plain)=split(/:/,$configline);
10920: %{$prp{$short}} = ();
10921: if (@plain > 0) {
10922: $prp{$short}{'std'} = $plain[0];
10923: for (my $i=1; $i<@plain; $i++) {
10924: $prp{$short}{'alt'.$i} = $plain[$i];
10925: }
10926: }
10927: }
10928: }
10929: close($config);
10930: }
10931:
10932: # ---------------------------------------------------------- Read package table
10933: {
10934: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10935:
10936: while (my $configline=<$config>) {
10937: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10938: chomp($configline);
10939: my ($short,$plain)=split(/:/,$configline);
10940: my ($pack,$name)=split(/\&/,$short);
10941: if ($plain ne '') {
10942: $packagetab{$pack.'&'.$name.'&name'}=$name;
10943: $packagetab{$short}=$plain;
10944: }
10945: }
10946: close($config);
10947: }
10948:
10949: # ---------------------------------------------------------- Read loncaparev table
10950: {
10951: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10952: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10953: while (my $configline=<$config>) {
10954: chomp($configline);
10955: my ($hostid,$loncaparev)=split(/:/,$configline);
10956: $loncaparevs{$hostid}=$loncaparev;
10957: }
10958: close($config);
10959: }
10960: }
10961: }
10962:
10963: # ---------------------------------------------------------- Read serverhostID table
10964: {
10965: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10966: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10967: while (my $configline=<$config>) {
10968: chomp($configline);
10969: my ($name,$id)=split(/:/,$configline);
10970: $serverhomeIDs{$name}=$id;
10971: }
10972: close($config);
10973: }
10974: }
10975: }
10976:
10977: {
10978: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10979: if (-e $file) {
10980: my $parser = HTML::LCParser->new($file);
10981: while (my $token = $parser->get_token()) {
10982: if ($token->[0] eq 'S') {
10983: my $item = $token->[1];
10984: my $name = $token->[2]{'name'};
10985: my $value = $token->[2]{'value'};
10986: if ($item ne '' && $name ne '' && $value ne '') {
10987: my $release = $parser->get_text();
10988: $release =~ s/(^\s*|\s*$ )//gx;
10989: $needsrelease{$item.':'.$name.':'.$value} = $release;
10990: }
10991: }
10992: }
10993: }
10994: }
10995:
10996: # ---------------------------------------------------------- Read managers table
10997: {
10998: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
10999: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11000: while (my $configline=<$config>) {
11001: chomp($configline);
11002: next if ($configline =~ /^\#/);
11003: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11004: $managerstab{$configline} = 1;
11005: }
11006: }
11007: close($config);
11008: }
11009: }
11010: }
11011:
11012: # ------------- set up temporary directory
11013: {
11014: $tmpdir = LONCAPA::tempdir();
11015:
11016: }
11017:
11018: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11019: 'compress_threshold'=> 20_000,
11020: });
11021:
11022: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11023: $dumpcount=0;
11024: $locknum=0;
11025:
11026: &logtouch();
11027: &logthis('<font color="yellow">INFO: Read configuration</font>');
11028: $readit=1;
11029: {
11030: use integer;
11031: my $test=(2**32)+1;
11032: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11033: &logthis(" Detected 64bit platform ($_64bit)");
11034: }
11035: }
11036: }
11037:
11038: 1;
11039: __END__
11040:
11041: =pod
11042:
11043: =head1 NAME
11044:
11045: Apache::lonnet - Subroutines to ask questions about things in the network.
11046:
11047: =head1 SYNOPSIS
11048:
11049: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11050:
11051: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11052:
11053: Common parameters:
11054:
11055: =over 4
11056:
11057: =item *
11058:
11059: $uname : an internal username (if $cname expecting a course Id specifically)
11060:
11061: =item *
11062:
11063: $udom : a domain (if $cdom expecting a course's domain specifically)
11064:
11065: =item *
11066:
11067: $symb : a resource instance identifier
11068:
11069: =item *
11070:
11071: $namespace : the name of a .db file that contains the data needed or
11072: being set.
11073:
11074: =back
11075:
11076: =head1 OVERVIEW
11077:
11078: lonnet provides subroutines which interact with the
11079: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11080: about classes, users, and resources.
11081:
11082: For many of these objects you can also use this to store data about
11083: them or modify them in various ways.
11084:
11085: =head2 Symbs
11086:
11087: To identify a specific instance of a resource, LON-CAPA uses symbols
11088: or "symbs"X<symb>. These identifiers are built from the URL of the
11089: map, the resource number of the resource in the map, and the URL of
11090: the resource itself. The latter is somewhat redundant, but might help
11091: if maps change.
11092:
11093: An example is
11094:
11095: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11096:
11097: The respective map entry is
11098:
11099: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11100: title="Problem 2">
11101: </resource>
11102:
11103: Symbs are used by the random number generator, as well as to store and
11104: restore data specific to a certain instance of for example a problem.
11105:
11106: =head2 Storing And Retrieving Data
11107:
11108: X<store()>X<cstore()>X<restore()>Three of the most important functions
11109: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11110: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11111: is is the non-critical message twin of cstore. These functions are for
11112: handlers to store a perl hash to a user's permanent data space in an
11113: easy manner, and to retrieve it again on another call. It is expected
11114: that a handler would use this once at the beginning to retrieve data,
11115: and then again once at the end to send only the new data back.
11116:
11117: The data is stored in the user's data directory on the user's
11118: homeserver under the ID of the course.
11119:
11120: The hash that is returned by restore will have all of the previous
11121: value for all of the elements of the hash.
11122:
11123: Example:
11124:
11125: #creating a hash
11126: my %hash;
11127: $hash{'foo'}='bar';
11128:
11129: #storing it
11130: &Apache::lonnet::cstore(\%hash);
11131:
11132: #changing a value
11133: $hash{'foo'}='notbar';
11134:
11135: #adding a new value
11136: $hash{'bar'}='foo';
11137: &Apache::lonnet::cstore(\%hash);
11138:
11139: #retrieving the hash
11140: my %history=&Apache::lonnet::restore();
11141:
11142: #print the hash
11143: foreach my $key (sort(keys(%history))) {
11144: print("\%history{$key} = $history{$key}");
11145: }
11146:
11147: Will print out:
11148:
11149: %history{1:foo} = bar
11150: %history{1:keys} = foo:timestamp
11151: %history{1:timestamp} = 990455579
11152: %history{2:bar} = foo
11153: %history{2:foo} = notbar
11154: %history{2:keys} = foo:bar:timestamp
11155: %history{2:timestamp} = 990455580
11156: %history{bar} = foo
11157: %history{foo} = notbar
11158: %history{timestamp} = 990455580
11159: %history{version} = 2
11160:
11161: Note that the special hash entries C<keys>, C<version> and
11162: C<timestamp> were added to the hash. C<version> will be equal to the
11163: total number of versions of the data that have been stored. The
11164: C<timestamp> attribute will be the UNIX time the hash was
11165: stored. C<keys> is available in every historical section to list which
11166: keys were added or changed at a specific historical revision of a
11167: hash.
11168:
11169: B<Warning>: do not store the hash that restore returns directly. This
11170: will cause a mess since it will restore the historical keys as if the
11171: were new keys. I.E. 1:foo will become 1:1:foo etc.
11172:
11173: Calling convention:
11174:
11175: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11176: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11177:
11178: For more detailed information, see lonnet specific documentation.
11179:
11180: =head1 RETURN MESSAGES
11181:
11182: =over 4
11183:
11184: =item * B<con_lost>: unable to contact remote host
11185:
11186: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11187: when the connection is brought back up
11188:
11189: =item * B<con_failed>: unable to contact remote host and unable to save message
11190: for later delivery
11191:
11192: =item * B<error:>: an error a occurred, a description of the error follows the :
11193:
11194: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11195: that was requested
11196:
11197: =back
11198:
11199: =head1 PUBLIC SUBROUTINES
11200:
11201: =head2 Session Environment Functions
11202:
11203: =over 4
11204:
11205: =item *
11206: X<appenv()>
11207: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11208: the user envirnoment file, and will be restored for each access this
11209: user makes during this session, also modifies the %env for the current
11210: process. Optional rolesarrayref - if defined contains a reference to an array
11211: of roles which are exempt from the restriction on modifying user.role entries
11212: in the user's environment.db and in %env.
11213:
11214: =item *
11215: X<delenv()>
11216: B<delenv($delthis,$regexp)>: removes all items from the session
11217: environment file that begin with $delthis. If the
11218: optional second arg - $regexp - is true, $delthis is treated as a
11219: regular expression, otherwise \Q$delthis\E is used.
11220: The values are also deleted from the current processes %env.
11221:
11222: =item * get_env_multiple($name)
11223:
11224: gets $name from the %env hash, it seemlessly handles the cases where multiple
11225: values may be defined and end up as an array ref.
11226:
11227: returns an array of values
11228:
11229: =back
11230:
11231: =head2 User Information
11232:
11233: =over 4
11234:
11235: =item *
11236: X<queryauthenticate()>
11237: B<queryauthenticate($uname,$udom)>: try to determine user's current
11238: authentication scheme
11239:
11240: =item *
11241: X<authenticate()>
11242: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11243: authenticate user from domain's lib servers (first use the current
11244: one). C<$upass> should be the users password.
11245: $checkdefauth is optional (value is 1 if a check should be made to
11246: authenticate user using default authentication method, and allow
11247: account creation if username does not have account in the domain).
11248: $clientcancheckhost is optional (value is 1 if checking whether the
11249: server can host will occur on the client side in lonauth.pm).
11250:
11251: =item *
11252: X<homeserver()>
11253: B<homeserver($uname,$udom)>: find the server which has
11254: the user's directory and files (there must be only one), this caches
11255: the answer, and also caches if there is a borken connection.
11256:
11257: =item *
11258: X<idget()>
11259: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11260: (IDs are a unique resource in a domain, there must be only 1 ID per
11261: username, and only 1 username per ID in a specific domain) (returns
11262: hash: id=>name,id=>name)
11263:
11264: =item *
11265: X<idrget()>
11266: B<idrget($udom,@unames)>: find the IDs behind a list of
11267: usernames (returns hash: name=>id,name=>id)
11268:
11269: =item *
11270: X<idput()>
11271: B<idput($udom,%ids)>: store away a list of names and associated IDs
11272:
11273: =item *
11274: X<rolesinit()>
11275: B<rolesinit($udom,$username,$authhost)>: get user privileges
11276:
11277: =item *
11278: X<getsection()>
11279: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11280: course $cname, return section name/number or '' for "not in course"
11281: and '-1' for "no section"
11282:
11283: =item *
11284: X<userenvironment()>
11285: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11286: passed in @what from the requested user's environment, returns a hash
11287:
11288: =item *
11289: X<userlog_query()>
11290: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11291: activity.log file. %filters defines filters applied when parsing the
11292: log file. These can be start or end timestamps, or the type of action
11293: - log to look for Login or Logout events, check for Checkin or
11294: Checkout, role for role selection. The response is in the form
11295: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11296: escaped strings of the action recorded in the activity.log file.
11297:
11298: =back
11299:
11300: =head2 User Roles
11301:
11302: =over 4
11303:
11304: =item *
11305:
11306: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11307: F: full access
11308: U,I,K: authentication modes (cxx only)
11309: '': forbidden
11310: 1: user needs to choose course
11311: 2: browse allowed
11312: A: passphrase authentication needed
11313:
11314: =item *
11315:
11316: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11317: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11318: and course level
11319:
11320: =item *
11321:
11322: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11323: (rolesplain.tab); plain text explanation of a user role term.
11324: $type is Course (default) or Community.
11325: If $forcedefault evaluates to true, text returned will be default
11326: text for $type. Otherwise, if this is a course, the text returned
11327: will be a custom name for the role (if defined in the course's
11328: environment). If no custom name is defined the default is returned.
11329:
11330: =item *
11331:
11332: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11333: All arguments are optional. Returns a hash of a roles, either for
11334: co-author/assistant author roles for a user's Construction Space
11335: (default), or if $context is 'userroles', roles for the user himself,
11336: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11337: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11338: For each key, value is set to colon-separated start and end times for
11339: the role. If no username and domain are specified, will default to
11340: current user/domain. Types, roles, and roledoms are references to arrays
11341: of role statuses (active, future or previous), roles
11342: (e.g., cc,in, st etc.) and domains of the roles which can be used
11343: to restrict the list of roles reported. If no array ref is
11344: provided for types, will default to return only active roles.
11345:
11346: =back
11347:
11348: =head2 User Modification
11349:
11350: =over 4
11351:
11352: =item *
11353:
11354: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11355: user for the level given by URL. Optional start and end dates (leave empty
11356: string or zero for "no date")
11357:
11358: =item *
11359:
11360: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11361: change a users, password, possible return values are: ok,
11362: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11363: refused
11364:
11365: =item *
11366:
11367: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11368:
11369: =item *
11370:
11371: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11372: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11373:
11374: will update user information (firstname,middlename,lastname,generation,
11375: permanentemail), and if forceid is true, student/employee ID also.
11376: A user's institutional affiliation(s) can also be updated.
11377: User information fields will not be overwritten with empty entries
11378: unless the field is included in the $candelete array reference.
11379: This array is included when a single user is modified via "Manage Users",
11380: or when Autoupdate.pl is run by cron in a domain.
11381:
11382: =item *
11383:
11384: modifystudent
11385:
11386: modify a student's enrollment and identification information.
11387: The course id is resolved based on the current users environment.
11388: This means the envoking user must be a course coordinator or otherwise
11389: associated with a course.
11390:
11391: This call is essentially a wrapper for lonnet::modifyuser and
11392: lonnet::modify_student_enrollment
11393:
11394: Inputs:
11395:
11396: =over 4
11397:
11398: =item B<$udom> Student's loncapa domain
11399:
11400: =item B<$uname> Student's loncapa login name
11401:
11402: =item B<$uid> Student/Employee ID
11403:
11404: =item B<$umode> Student's authentication mode
11405:
11406: =item B<$upass> Student's password
11407:
11408: =item B<$first> Student's first name
11409:
11410: =item B<$middle> Student's middle name
11411:
11412: =item B<$last> Student's last name
11413:
11414: =item B<$gene> Student's generation
11415:
11416: =item B<$usec> Student's section in course
11417:
11418: =item B<$end> Unix time of the roles expiration
11419:
11420: =item B<$start> Unix time of the roles start date
11421:
11422: =item B<$forceid> If defined, allow $uid to be changed
11423:
11424: =item B<$desiredhome> server to use as home server for student
11425:
11426: =item B<$email> Student's permanent e-mail address
11427:
11428: =item B<$type> Type of enrollment (auto or manual)
11429:
11430: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11431:
11432: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11433:
11434: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11435:
11436: =item B<$context> role change context (shown in User Management Logs display in a course)
11437:
11438: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11439:
11440: =back
11441:
11442: =item *
11443:
11444: modify_student_enrollment
11445:
11446: Change a students enrollment status in a class. The environment variable
11447: 'role.request.course' must be defined for this function to proceed.
11448:
11449: Inputs:
11450:
11451: =over 4
11452:
11453: =item $udom, students domain
11454:
11455: =item $uname, students name
11456:
11457: =item $uid, students user id
11458:
11459: =item $first, students first name
11460:
11461: =item $middle
11462:
11463: =item $last
11464:
11465: =item $gene
11466:
11467: =item $usec
11468:
11469: =item $end
11470:
11471: =item $start
11472:
11473: =item $type
11474:
11475: =item $locktype
11476:
11477: =item $cid
11478:
11479: =item $selfenroll
11480:
11481: =item $context
11482:
11483: =back
11484:
11485:
11486: =item *
11487:
11488: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11489: custom role; give a custom role to a user for the level given by URL. Specify
11490: name and domain of role author, and role name
11491:
11492: =item *
11493:
11494: revokerole($udom,$uname,$url,$role) : revoke a role for url
11495:
11496: =item *
11497:
11498: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11499:
11500: =back
11501:
11502: =head2 Course Infomation
11503:
11504: =over 4
11505:
11506: =item *
11507:
11508: coursedescription($courseid,$options) : returns a hash of information about the
11509: specified course id, including all environment settings for the
11510: course, the description of the course will be in the hash under the
11511: key 'description'
11512:
11513: $options is an optional parameter that if supplied is a hash reference that controls
11514: what how this function works. It has the following key/values:
11515:
11516: =over 4
11517:
11518: =item freshen_cache
11519:
11520: If defined, and the environment cache for the course is valid, it is
11521: returned in the returned hash.
11522:
11523: =item one_time
11524:
11525: If defined, the last cache time is set to _now_
11526:
11527: =item user
11528:
11529: If defined, the supplied username is used instead of the current user.
11530:
11531:
11532: =back
11533:
11534: =item *
11535:
11536: resdata($name,$domain,$type,@which) : request for current parameter
11537: setting for a specific $type, where $type is either 'course' or 'user',
11538: @what should be a list of parameters to ask about. This routine caches
11539: answers for 5 minutes.
11540:
11541: =item *
11542:
11543: get_courseresdata($courseid, $domain) : dump the entire course resource
11544: data base, returning a hash that is keyed by the resource name and has
11545: values that are the resource value. I believe that the timestamps and
11546: versions are also returned.
11547:
11548:
11549: =back
11550:
11551: =head2 Course Modification
11552:
11553: =over 4
11554:
11555: =item *
11556:
11557: writecoursepref($courseid,%prefs) : write preferences (environment
11558: database) for a course
11559:
11560: =item *
11561:
11562: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11563:
11564: =item *
11565:
11566: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11567:
11568: =back
11569:
11570: =head2 Resource Subroutines
11571:
11572: =over 4
11573:
11574: =item *
11575:
11576: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11577:
11578: =item *
11579:
11580: repcopy($filename) : subscribes to the requested file, and attempts to
11581: replicate from the owning library server, Might return
11582: 'unavailable', 'not_found', 'forbidden', 'ok', or
11583: 'bad_request', also attempts to grab the metadata for the
11584: resource. Expects the local filesystem pathname
11585: (/home/httpd/html/res/....)
11586:
11587: =back
11588:
11589: =head2 Resource Information
11590:
11591: =over 4
11592:
11593: =item *
11594:
11595: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11596: a vairety of different possible values, $varname should be a request
11597: string, and the other parameters can be used to specify who and what
11598: one is asking about.
11599:
11600: Possible values for $varname are environment.lastname (or other item
11601: from the envirnment hash), user.name (or someother aspect about the
11602: user), resource.0.maxtries (or some other part and parameter of a
11603: resource)
11604:
11605: =item *
11606:
11607: directcondval($number) : get current value of a condition; reads from a state
11608: string
11609:
11610: =item *
11611:
11612: condval($condidx) : value of condition index based on state
11613:
11614: =item *
11615:
11616: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11617: resource's metadata, $what should be either a specific key, or either
11618: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11619: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11620:
11621: this function automatically caches all requests
11622:
11623: =item *
11624:
11625: metadata_query($query,$custom,$customshow) : make a metadata query against the
11626: network of library servers; returns file handle of where SQL and regex results
11627: will be stored for query
11628:
11629: =item *
11630:
11631: symbread($filename) : return symbolic list entry (filename argument optional);
11632: returns the data handle
11633:
11634: =item *
11635:
11636: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11637: a possible symb for the URL in $thisfn, and if is an encryypted
11638: resource that the user accessed using /enc/ returns a 1 on success, 0
11639: on failure, user must be in a course, as it assumes the existance of
11640: the course initial hash, and uses $env('request.course.id'}
11641:
11642:
11643: =item *
11644:
11645: symbclean($symb) : removes versions numbers from a symb, returns the
11646: cleaned symb
11647:
11648: =item *
11649:
11650: is_on_map($uri) : checks if the $uri is somewhere on the current
11651: course map, user must be in a course for it to work.
11652:
11653: =item *
11654:
11655: numval($salt) : return random seed value (addend for rndseed)
11656:
11657: =item *
11658:
11659: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11660: a random seed, all arguments are optional, if they aren't sent it uses the
11661: environment to derive them. Note: if symb isn't sent and it can't get one
11662: from &symbread it will use the current time as its return value
11663:
11664: =item *
11665:
11666: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11667: unfakeable, receipt
11668:
11669: =item *
11670:
11671: receipt() : API to ireceipt working off of env values; given out to users
11672:
11673: =item *
11674:
11675: countacc($url) : count the number of accesses to a given URL
11676:
11677: =item *
11678:
11679: 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
11680:
11681: =item *
11682:
11683: 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)
11684:
11685: =item *
11686:
11687: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11688:
11689: =item *
11690:
11691: devalidate($symb) : devalidate temporary spreadsheet calculations,
11692: forcing spreadsheet to reevaluate the resource scores next time.
11693:
11694: =back
11695:
11696: =head2 Storing/Retreiving Data
11697:
11698: =over 4
11699:
11700: =item *
11701:
11702: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11703: for this url; hashref needs to be given and should be a \%hashname; the
11704: remaining args aren't required and if they aren't passed or are '' they will
11705: be derived from the env
11706:
11707: =item *
11708:
11709: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11710: uses critical subroutine
11711:
11712: =item *
11713:
11714: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11715: all args are optional
11716:
11717: =item *
11718:
11719: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11720: dumps the complete (or key matching regexp) namespace into a hash
11721: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11722: normally &store()ed into
11723:
11724: $range should be either an integer '100' (give me the first 100
11725: matching records)
11726: or be two integers sperated by a - with no spaces
11727: '30-50' (give me the 30th through the 50th matching
11728: records)
11729:
11730:
11731: =item *
11732:
11733: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11734: replaces a &store() version of data with a replacement set of data
11735: for a particular resource in a namespace passed in the $storehash hash
11736: reference
11737:
11738: =item *
11739:
11740: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11741: works very similar to store/cstore, but all data is stored in a
11742: temporary location and can be reset using tmpreset, $storehash should
11743: be a hash reference, returns nothing on success
11744:
11745: =item *
11746:
11747: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11748: similar to restore, but all data is stored in a temporary location and
11749: can be reset using tmpreset. Returns a hash of values on success,
11750: error string otherwise.
11751:
11752: =item *
11753:
11754: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11755: deltes all keys for $symb form the temporary storage hash.
11756:
11757: =item *
11758:
11759: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11760: reference filled in from namesp ($udom and $uname are optional)
11761:
11762: =item *
11763:
11764: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11765: namesp ($udom and $uname are optional)
11766:
11767: =item *
11768:
11769: dump($namespace,$udom,$uname,$regexp,$range) :
11770: dumps the complete (or key matching regexp) namespace into a hash
11771: ($udom, $uname, $regexp, $range are optional)
11772:
11773: $range should be either an integer '100' (give me the first 100
11774: matching records)
11775: or be two integers sperated by a - with no spaces
11776: '30-50' (give me the 30th through the 50th matching
11777: records)
11778: =item *
11779:
11780: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11781: $store can be a scalar, an array reference, or if the amount to be
11782: incremented is > 1, a hash reference.
11783:
11784: ($udom and $uname are optional)
11785:
11786: =item *
11787:
11788: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11789: ($udom and $uname are optional)
11790:
11791: =item *
11792:
11793: cput($namespace,$storehash,$udom,$uname) : critical put
11794: ($udom and $uname are optional)
11795:
11796: =item *
11797:
11798: newput($namespace,$storehash,$udom,$uname) :
11799:
11800: Attempts to store the items in the $storehash, but only if they don't
11801: currently exist, if this succeeds you can be certain that you have
11802: successfully created a new key value pair in the $namespace db.
11803:
11804:
11805: Args:
11806: $namespace: name of database to store values to
11807: $storehash: hashref to store to the db
11808: $udom: (optional) domain of user containing the db
11809: $uname: (optional) name of user caontaining the db
11810:
11811: Returns:
11812: 'ok' -> succeeded in storing all keys of $storehash
11813: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11814: least <key> already existed in the db (other
11815: requested keys may also already exist)
11816: 'error: <msg>' -> unable to tie the DB or other error occurred
11817: 'con_lost' -> unable to contact request server
11818: 'refused' -> action was not allowed by remote machine
11819:
11820:
11821: =item *
11822:
11823: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11824: reference filled in from namesp (encrypts the return communication)
11825: ($udom and $uname are optional)
11826:
11827: =item *
11828:
11829: log($udom,$name,$home,$message) : write to permanent log for user; use
11830: critical subroutine
11831:
11832: =item *
11833:
11834: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11835: array reference filled in from namespace found in domain level on either
11836: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11837:
11838: =item *
11839:
11840: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11841: domain level either on specified domain server ($uhome) or primary domain
11842: server ($udom and $uhome are optional)
11843:
11844: =item *
11845:
11846: get_domain_defaults($target_domain) : returns hash with defaults for
11847: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11848: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11849: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11850: Values are retrieved from cache (if current), or from domain's configuration.db
11851: (if available), or lastly from values in lonTabs/dns_domain,tab,
11852: or lonTabs/domain.tab.
11853:
11854: %domdefaults = &get_auth_defaults($target_domain);
11855:
11856: =back
11857:
11858: =head2 Network Status Functions
11859:
11860: =over 4
11861:
11862: =item *
11863:
11864: dirlist() : return directory list based on URI (first arg).
11865:
11866: Inputs: 1 required, 5 optional.
11867:
11868: =over
11869:
11870: =item
11871: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
11872:
11873: =item
11874: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
11875:
11876: =item
11877: $username - username of user/course to be listed. Extracted from $uri if absent.
11878:
11879: =item
11880: $getpropath - boolean: 1 if prepend path using &propath().
11881:
11882: =item
11883: $getuserdir - boolean: 1 if prepend path for "userfiles".
11884:
11885: =item
11886: $alternateRoot - path to prepend in place of path from $uri.
11887:
11888: =back
11889:
11890: Returns: Array of up to two items.
11891:
11892: =over
11893:
11894: a reference to an array of files/subdirectories
11895:
11896: =over
11897:
11898: Each element in the array of files/subdirectories is a & separated list of
11899: item name and the result of running stat on the item. If dirlist was requested
11900: for a file instead of a directory, the item name will be ''. For a directory
11901: listing, if the item is a metadata file, the element will end &N&M
11902: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
11903: default copyright set (1).
11904:
11905: =back
11906:
11907: a scalar containing error condition (if encountered).
11908:
11909: =over
11910:
11911: =item
11912: no_host (no homeserver identified for $username:$domain).
11913:
11914: =item
11915: no_such_host (server contacted for listing not identified as valid host).
11916:
11917: =item
11918: con_lost (connection to remote server failed).
11919:
11920: =item
11921: refused (invalid $username:$domain received on lond side).
11922:
11923: =item
11924: no_such_dir (directory at specified path on lond side does not exist).
11925:
11926: =item
11927: empty (directory at specified path on lond side is empty).
11928:
11929: =over
11930:
11931: This is currently not encountered because the &ls3, &ls2,
11932: &ls (_handler) routines on the lond side do not filter out
11933: . and .. from a directory listing.
11934:
11935: =back
11936:
11937: =back
11938:
11939: =back
11940:
11941: =item *
11942:
11943: spareserver() : find server with least workload from spare.tab
11944:
11945:
11946: =item *
11947:
11948: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11949: if there is no corresponding loncapa host.
11950:
11951: =back
11952:
11953:
11954: =head2 Apache Request
11955:
11956: =over 4
11957:
11958: =item *
11959:
11960: ssi($url,%hash) : server side include, does a complete request cycle on url to
11961: localhost, posts hash
11962:
11963: =back
11964:
11965: =head2 Data to String to Data
11966:
11967: =over 4
11968:
11969: =item *
11970:
11971: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11972: and '&' separators, supports elements that are arrayrefs and hashrefs
11973:
11974: =item *
11975:
11976: hashref2str($hashref) : convert a hashref into a string complete with
11977: escaping and '=' and '&' separators, supports elements that are
11978: arrayrefs and hashrefs
11979:
11980: =item *
11981:
11982: arrayref2str($arrayref) : convert an arrayref into a string complete
11983: with escaping and '&' separators, supports elements that are arrayrefs
11984: and hashrefs
11985:
11986: =item *
11987:
11988: str2hash($string) : convert string to hash using unescaping and
11989: splitting on '=' and '&', supports elements that are arrayrefs and
11990: hashrefs
11991:
11992: =item *
11993:
11994: str2array($string) : convert string to hash using unescaping and
11995: splitting on '&', supports elements that are arrayrefs and hashrefs
11996:
11997: =back
11998:
11999: =head2 Logging Routines
12000:
12001:
12002: These routines allow one to make log messages in the lonnet.log and
12003: lonnet.perm logfiles.
12004:
12005: =over 4
12006:
12007: =item *
12008:
12009: logtouch() : make sure the logfile, lonnet.log, exists
12010:
12011: =item *
12012:
12013: logthis() : append message to the normal lonnet.log file, it gets
12014: preiodically rolled over and deleted.
12015:
12016: =item *
12017:
12018: logperm() : append a permanent message to lonnet.perm.log, this log
12019: file never gets deleted by any automated portion of the system, only
12020: messages of critical importance should go in here.
12021:
12022:
12023: =back
12024:
12025: =head2 General File Helper Routines
12026:
12027: =over 4
12028:
12029: =item *
12030:
12031: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12032: (a) files in /uploaded
12033: (i) If a local copy of the file exists -
12034: compares modification date of local copy with last-modified date for
12035: definitive version stored on home server for course. If local copy is
12036: stale, requests a new version from the home server and stores it.
12037: If the original has been removed from the home server, then local copy
12038: is unlinked.
12039: (ii) If local copy does not exist -
12040: requests the file from the home server and stores it.
12041:
12042: If $caller is 'uploadrep':
12043: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12044: for request for files originally uploaded via DOCS.
12045: - returns 'ok' if fresh local copy now available, -1 otherwise.
12046:
12047: Otherwise:
12048: This indicates a call from the content generation phase of the request.
12049: - returns the entire contents of the file or -1.
12050:
12051: (b) files in /res
12052: - returns the entire contents of a file or -1;
12053: it properly subscribes to and replicates the file if neccessary.
12054:
12055:
12056: =item *
12057:
12058: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12059: reference
12060:
12061: returns either a stat() list of data about the file or an empty list
12062: if the file doesn't exist or couldn't find out about it (connection
12063: problems or user unknown)
12064:
12065: =item *
12066:
12067: filelocation($dir,$file) : returns file system location of a file
12068: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12069: directory that relative $file lookups are to looked in ($dir of /a/dir
12070: and a file of ../bob will become /a/bob)
12071:
12072: =item *
12073:
12074: hreflocation($dir,$file) : returns file system location or a URL; same as
12075: filelocation except for hrefs
12076:
12077: =item *
12078:
12079: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12080:
12081: =back
12082:
12083: =head2 Usererfile file routines (/uploaded*)
12084:
12085: =over 4
12086:
12087: =item *
12088:
12089: userfileupload(): main rotine for putting a file in a user or course's
12090: filespace, arguments are,
12091:
12092: formname - required - this is the name of the element in $env where the
12093: filename, and the contents of the file to create/modifed exist
12094: the filename is in $env{'form.'.$formname.'.filename'} and the
12095: contents of the file is located in $env{'form.'.$formname}
12096: context - if coursedoc, store the file in the course of the active role
12097: of the current user;
12098: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12099: if 'canceloverwrite': delete file in tmp/overwrites directory
12100: subdir - required - subdirectory to put the file in under ../userfiles/
12101: if undefined, it will be placed in "unknown"
12102:
12103: (This routine calls clean_filename() to remove any dangerous
12104: characters from the filename, and then calls finuserfileupload() to
12105: complete the transaction)
12106:
12107: returns either the url of the uploaded file (/uploaded/....) if successful
12108: and /adm/notfound.html if unsuccessful
12109:
12110: =item *
12111:
12112: clean_filename(): routine for cleaing a filename up for storage in
12113: userfile space, argument is:
12114:
12115: filename - proposed filename
12116:
12117: returns: the new clean filename
12118:
12119: =item *
12120:
12121: finishuserfileupload(): routine that creates and sends the file to
12122: userspace, probably shouldn't be called directly
12123:
12124: docuname: username or courseid of destination for the file
12125: docudom: domain of user/course of destination for the file
12126: formname: same as for userfileupload()
12127: fname: filename (including subdirectories) for the file
12128: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12129: allfiles: reference to hash used to store objects found by parser
12130: codebase: reference to hash used for codebases of java objects found by parser
12131: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12132: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12133: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12134: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12135: context: if 'overwrite', will move the uploaded file from its temporary location to
12136: userfiles to facilitate overwriting a previously uploaded file with same name.
12137: mimetype: reference to scalar to accommodate mime type determined
12138: from File::MMagic if $parser = parse.
12139:
12140: returns either the url of the uploaded file (/uploaded/....) if successful
12141: and /adm/notfound.html if unsuccessful (or an error message if context
12142: was 'overwrite').
12143:
12144:
12145: =item *
12146:
12147: renameuserfile(): renames an existing userfile to a new name
12148:
12149: Args:
12150: docuname: username or courseid of destination for the file
12151: docudom: domain of user/course of destination for the file
12152: old: current file name (including any subdirs under userfiles)
12153: new: desired file name (including any subdirs under userfiles)
12154:
12155: =item *
12156:
12157: mkdiruserfile(): creates a directory is a userfiles dir
12158:
12159: Args:
12160: docuname: username or courseid of destination for the file
12161: docudom: domain of user/course of destination for the file
12162: dir: dir to create (including any subdirs under userfiles)
12163:
12164: =item *
12165:
12166: removeuserfile(): removes a file that exists in userfiles
12167:
12168: Args:
12169: docuname: username or courseid of destination for the file
12170: docudom: domain of user/course of destination for the file
12171: fname: filname to delete (including any subdirs under userfiles)
12172:
12173: =item *
12174:
12175: removeuploadedurl(): convience function for removeuserfile()
12176:
12177: Args:
12178: url: a full /uploaded/... url to delete
12179:
12180: =item *
12181:
12182: get_portfile_permissions():
12183: Args:
12184: domain: domain of user or course contain the portfolio files
12185: user: name of user or num of course contain the portfolio files
12186: Returns:
12187: hashref of a dump of the proper file_permissions.db
12188:
12189:
12190: =item *
12191:
12192: get_access_controls():
12193:
12194: Args:
12195: current_permissions: the hash ref returned from get_portfile_permissions()
12196: group: (optional) the group you want the files associated with
12197: file: (optional) the file you want access info on
12198:
12199: Returns:
12200: a hash (keys are file names) of hashes containing
12201: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12202: values are XML containing access control settings (see below)
12203:
12204: Internal notes:
12205:
12206: access controls are stored in file_permissions.db as key=value pairs.
12207: key -> path to file/file_name\0uniqueID:scope_end_start
12208: where scope -> public,guest,course,group,domains or users.
12209: end -> UNIX time for end of access (0 -> no end date)
12210: start -> UNIX time for start of access
12211:
12212: value -> XML description of access control
12213: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12214: <start></start>
12215: <end></end>
12216:
12217: <password></password> for scope type = guest
12218:
12219: <domain></domain> for scope type = course or group
12220: <number></number>
12221: <roles id="">
12222: <role></role>
12223: <access></access>
12224: <section></section>
12225: <group></group>
12226: </roles>
12227:
12228: <dom></dom> for scope type = domains
12229:
12230: <users> for scope type = users
12231: <user>
12232: <uname></uname>
12233: <udom></udom>
12234: </user>
12235: </users>
12236: </scope>
12237:
12238: Access data is also aggregated for each file in an additional key=value pair:
12239: key -> path to file/file_name\0accesscontrol
12240: value -> reference to hash
12241: hash contains key = value pairs
12242: where key = uniqueID:scope_end_start
12243: value = UNIX time record was last updated
12244:
12245: Used to improve speed of look-ups of access controls for each file.
12246:
12247: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12248:
12249: modify_access_controls():
12250:
12251: Modifies access controls for a portfolio file
12252: Args
12253: 1. file name
12254: 2. reference to hash of required changes,
12255: 3. domain
12256: 4. username
12257: where domain,username are the domain of the portfolio owner
12258: (either a user or a course)
12259:
12260: Returns:
12261: 1. result of additions or updates ('ok' or 'error', with error message).
12262: 2. result of deletions ('ok' or 'error', with error message).
12263: 3. reference to hash of any new or updated access controls.
12264: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12265: key = integer (inbound ID)
12266: value = uniqueID
12267:
12268: =back
12269:
12270: =head2 HTTP Helper Routines
12271:
12272: =over 4
12273:
12274: =item *
12275:
12276: escape() : unpack non-word characters into CGI-compatible hex codes
12277:
12278: =item *
12279:
12280: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12281:
12282: =back
12283:
12284: =head1 PRIVATE SUBROUTINES
12285:
12286: =head2 Underlying communication routines (Shouldn't call)
12287:
12288: =over 4
12289:
12290: =item *
12291:
12292: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12293:
12294: =item *
12295:
12296: reply() : uses subreply to send a message to remote machine, logs all failures
12297:
12298: =item *
12299:
12300: critical() : passes a critical message to another server; if cannot
12301: get through then place message in connection buffer directory and
12302: returns con_delayed, if incapable of saving message, returns
12303: con_failed
12304:
12305: =item *
12306:
12307: reconlonc() : tries to reconnect lonc client processes.
12308:
12309: =back
12310:
12311: =head2 Resource Access Logging
12312:
12313: =over 4
12314:
12315: =item *
12316:
12317: flushcourselogs() : flush (save) buffer logs and access logs
12318:
12319: =item *
12320:
12321: courselog($what) : save message for course in hash
12322:
12323: =item *
12324:
12325: courseacclog($what) : save message for course using &courselog(). Perform
12326: special processing for specific resource types (problems, exams, quizzes, etc).
12327:
12328: =item *
12329:
12330: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12331: as a PerlChildExitHandler
12332:
12333: =back
12334:
12335: =head2 Other
12336:
12337: =over 4
12338:
12339: =item *
12340:
12341: symblist($mapname,%newhash) : update symbolic storage links
12342:
12343: =back
12344:
12345: =cut
12346:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>