File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1136:
download - view:
text,
annotated -
select for diffs
Mon Oct 17 12:41:39 2011 UTC (12 years, 9 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Change to way lonnet::dirlist() reports an error condition (i.e., no_host,
con_lost, no_such_dir, empty etc.) when retrieving directory list information
with ls3, ls2 or ls.
- error is passed as second item in a pair of return values.
- first item in return values is a reference to an array of actual files.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1136 2011/10/17 12:41:39 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
84: %courseownerbuf, %coursetypebuf,$locknum);
85:
86: use IO::Socket;
87: use GDBM_File;
88: use HTML::LCParser;
89: use Fcntl qw(:flock);
90: use Storable qw(thaw nfreeze);
91: use Time::HiRes qw( gettimeofday tv_interval );
92: use Cache::Memcached;
93: use Digest::MD5;
94: use Math::Random;
95: use File::MMagic;
96: use LONCAPA qw(:DEFAULT :match);
97: use LONCAPA::Configuration;
98:
99: use File::Copy;
100:
101: my $readit;
102: my $max_connection_retries = 10; # Or some such value.
103:
104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
109:
110: # --------------------------------------------------------------------- Logging
111: {
112: my $logid;
113: sub instructor_log {
114: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
115: if (($cnum eq '') || ($cdom eq '')) {
116: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
117: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
118: }
119: $logid++;
120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
122: return &Apache::lonnet::put('nohist_'.$hash_name,
123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
126: 'exe_time' => $now,
127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
133: },$cdom,$cnum);
134: }
135: }
136:
137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
153: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
154: print $fh $logstring;
155: close($fh);
156: }
157: return 1;
158: }
159:
160: sub logperm {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
165: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
166: print $fh "$now:$message:$local\n";
167: close($fh);
168: }
169: return 1;
170: }
171:
172: sub create_connection {
173: my ($hostname,$lonid) = @_;
174: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
175: Type => SOCK_STREAM,
176: Timeout => 10);
177: return 0 if (!$client);
178: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
179: my $result = <$client>;
180: chomp($result);
181: return 1 if ($result eq 'done');
182: return 0;
183: }
184:
185: sub get_server_timezone {
186: my ($cnum,$cdom) = @_;
187: my $home=&homeserver($cnum,$cdom);
188: if ($home ne 'no_host') {
189: my $cachetime = 24*3600;
190: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
191: if (defined($cached)) {
192: return $timezone;
193: } else {
194: my $timezone = &reply('servertimezone',$home);
195: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
196: }
197: }
198: }
199:
200: sub get_server_distarch {
201: my ($lonhost,$ignore_cache) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: return;
205: }
206: my $cachetime = 12*3600;
207: if (!$ignore_cache) {
208: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
209: if (defined($cached)) {
210: return $distarch;
211: }
212: }
213: my $rep = &reply('serverdistarch',$lonhost);
214: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
215: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
216: $rep eq '') {
217: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
218: }
219: }
220: return;
221: }
222:
223: sub get_server_loncaparev {
224: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
225: if (defined($lonhost)) {
226: if (!defined(&hostname($lonhost))) {
227: undef($lonhost);
228: }
229: }
230: if (!defined($lonhost)) {
231: if (defined(&domain($dom,'primary'))) {
232: $lonhost=&domain($dom,'primary');
233: if ($lonhost eq 'no_host') {
234: undef($lonhost);
235: }
236: }
237: }
238: if (defined($lonhost)) {
239: my $cachetime = 12*3600;
240: if (!$ignore_cache) {
241: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
242: if (defined($cached)) {
243: return $loncaparev;
244: }
245: }
246: my ($answer,$loncaparev);
247: my @ids=¤t_machine_ids();
248: if (grep(/^\Q$lonhost\E$/,@ids)) {
249: $answer = $perlvar{'lonVersion'};
250: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
251: $loncaparev = $1;
252: }
253: } else {
254: $answer = &reply('serverloncaparev',$lonhost);
255: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
256: if ($caller eq 'loncron') {
257: my $ua=new LWP::UserAgent;
258: $ua->timeout(4);
259: my $protocol = $protocol{$lonhost};
260: $protocol = 'http' if ($protocol ne 'https');
261: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
262: my $request=new HTTP::Request('GET',$url);
263: my $response=$ua->request($request);
264: unless ($response->is_error()) {
265: my $content = $response->content;
266: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
267: $loncaparev = $1;
268: }
269: }
270: } else {
271: $loncaparev = $loncaparevs{$lonhost};
272: }
273: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
274: $loncaparev = $1;
275: }
276: }
277: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
278: }
279: }
280:
281: sub get_server_homeID {
282: my ($hostname,$ignore_cache,$caller) = @_;
283: unless ($ignore_cache) {
284: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
285: if (defined($cached)) {
286: return $serverhomeID;
287: }
288: }
289: my $cachetime = 12*3600;
290: my $serverhomeID;
291: if ($caller eq 'loncron') {
292: my @machine_ids = &machine_ids($hostname);
293: foreach my $id (@machine_ids) {
294: my $response = &reply('serverhomeID',$id);
295: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
296: $serverhomeID = $response;
297: last;
298: }
299: }
300: if ($serverhomeID eq '') {
301: $serverhomeID = $machine_ids[-1];
302: }
303: } else {
304: $serverhomeID = $serverhomeIDs{$hostname};
305: }
306: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
307: }
308:
309: sub get_remote_globals {
310: my ($lonhost,$whathash,$ignore_cache) = @_;
311: my ($result,%returnhash,%whatneeded);
312: if (ref($whathash) eq 'HASH') {
313: foreach my $what (sort(keys(%{$whathash}))) {
314: my $hashid = $lonhost.'-'.$what;
315: my ($response,$cached);
316: unless ($ignore_cache) {
317: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
318: }
319: if (defined($cached)) {
320: $returnhash{$what} = $response;
321: } else {
322: $whatneeded{$what} = 1;
323: }
324: }
325: if (keys(%whatneeded) == 0) {
326: $result = 'ok';
327: } else {
328: my $requested = &freeze_escape(\%whatneeded);
329: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
330: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
331: ($rep eq 'unknown_cmd')) {
332: $result = $rep;
333: } else {
334: $result = 'ok';
335: my @pairs=split(/\&/,$rep);
336: foreach my $item (@pairs) {
337: my ($key,$value)=split(/=/,$item,2);
338: my $what = &unescape($key);
339: my $hashid = $lonhost.'-'.$what;
340: $returnhash{$what}=&thaw_unescape($value);
341: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
342: }
343: }
344: }
345: }
346: return ($result,\%returnhash);
347: }
348:
349: sub remote_devalidate_cache {
350: my ($lonhost,$name,$id) = @_;
351: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
352: return $response;
353: }
354:
355: # -------------------------------------------------- Non-critical communication
356: sub subreply {
357: my ($cmd,$server)=@_;
358: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
359: #
360: # With loncnew process trimming, there's a timing hole between lonc server
361: # process exit and the master server picking up the listen on the AF_UNIX
362: # socket. In that time interval, a lock file will exist:
363:
364: my $lockfile=$peerfile.".lock";
365: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
366: sleep(1);
367: }
368: # At this point, either a loncnew parent is listening or an old lonc
369: # or loncnew child is listening so we can connect or everything's dead.
370: #
371: # We'll give the connection a few tries before abandoning it. If
372: # connection is not possible, we'll con_lost back to the client.
373: #
374: my $client;
375: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
376: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
377: Type => SOCK_STREAM,
378: Timeout => 10);
379: if ($client) {
380: last; # Connected!
381: } else {
382: &create_connection(&hostname($server),$server);
383: }
384: sleep(1); # Try again later if failed connection.
385: }
386: my $answer;
387: if ($client) {
388: print $client "sethost:$server:$cmd\n";
389: $answer=<$client>;
390: if (!$answer) { $answer="con_lost"; }
391: chomp($answer);
392: } else {
393: $answer = 'con_lost'; # Failed connection.
394: }
395: return $answer;
396: }
397:
398: sub reply {
399: my ($cmd,$server)=@_;
400: unless (defined(&hostname($server))) { return 'no_such_host'; }
401: my $answer=subreply($cmd,$server);
402: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
403: &logthis("<font color=\"blue\">WARNING:".
404: " $cmd to $server returned $answer</font>");
405: }
406: return $answer;
407: }
408:
409: # ----------------------------------------------------------- Send USR1 to lonc
410:
411: sub reconlonc {
412: my ($lonid) = @_;
413: my $hostname = &hostname($lonid);
414: if ($lonid) {
415: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
416: if ($hostname && -e $peerfile) {
417: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
418: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
419: Type => SOCK_STREAM,
420: Timeout => 10);
421: if ($client) {
422: print $client ("reset_retries\n");
423: my $answer=<$client>;
424: #reset just this one.
425: }
426: }
427: return;
428: }
429:
430: &logthis("Trying to reconnect lonc");
431: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
432: if (open(my $fh,"<$loncfile")) {
433: my $loncpid=<$fh>;
434: chomp($loncpid);
435: if (kill 0 => $loncpid) {
436: &logthis("lonc at pid $loncpid responding, sending USR1");
437: kill USR1 => $loncpid;
438: sleep 1;
439: } else {
440: &logthis(
441: "<font color=\"blue\">WARNING:".
442: " lonc at pid $loncpid not responding, giving up</font>");
443: }
444: } else {
445: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
446: }
447: }
448:
449: # ------------------------------------------------------ Critical communication
450:
451: sub critical {
452: my ($cmd,$server)=@_;
453: unless (&hostname($server)) {
454: &logthis("<font color=\"blue\">WARNING:".
455: " Critical message to unknown server ($server)</font>");
456: return 'no_such_host';
457: }
458: my $answer=reply($cmd,$server);
459: if ($answer eq 'con_lost') {
460: &reconlonc("$perlvar{'lonSockDir'}/$server");
461: my $answer=reply($cmd,$server);
462: if ($answer eq 'con_lost') {
463: my $now=time;
464: my $middlename=$cmd;
465: $middlename=substr($middlename,0,16);
466: $middlename=~s/\W//g;
467: my $dfilename=
468: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
469: $dumpcount++;
470: {
471: my $dfh;
472: if (open($dfh,">$dfilename")) {
473: print $dfh "$cmd\n";
474: close($dfh);
475: }
476: }
477: sleep 2;
478: my $wcmd='';
479: {
480: my $dfh;
481: if (open($dfh,"<$dfilename")) {
482: $wcmd=<$dfh>;
483: close($dfh);
484: }
485: }
486: chomp($wcmd);
487: if ($wcmd eq $cmd) {
488: &logthis("<font color=\"blue\">WARNING: ".
489: "Connection buffer $dfilename: $cmd</font>");
490: &logperm("D:$server:$cmd");
491: return 'con_delayed';
492: } else {
493: &logthis("<font color=\"red\">CRITICAL:"
494: ." Critical connection failed: $server $cmd</font>");
495: &logperm("F:$server:$cmd");
496: return 'con_failed';
497: }
498: }
499: }
500: return $answer;
501: }
502:
503: # ------------------------------------------- check if return value is an error
504:
505: sub error {
506: my ($result) = @_;
507: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
508: if ($2 == 2) { return undef; }
509: return $1;
510: }
511: return undef;
512: }
513:
514: sub convert_and_load_session_env {
515: my ($lonidsdir,$handle)=@_;
516: my @profile;
517: {
518: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
519: if (!$opened) {
520: return 0;
521: }
522: flock($idf,LOCK_SH);
523: @profile=<$idf>;
524: close($idf);
525: }
526: my %temp_env;
527: foreach my $line (@profile) {
528: if ($line !~ m/=/) {
529: return 0;
530: }
531: chomp($line);
532: my ($envname,$envvalue)=split(/=/,$line,2);
533: $temp_env{&unescape($envname)} = &unescape($envvalue);
534: }
535: unlink("$lonidsdir/$handle.id");
536: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
537: 0640)) {
538: %disk_env = %temp_env;
539: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
540: untie(%disk_env);
541: }
542: return 1;
543: }
544:
545: # ------------------------------------------- Transfer profile into environment
546: my $env_loaded;
547: sub transfer_profile_to_env {
548: my ($lonidsdir,$handle,$force_transfer) = @_;
549: if (!$force_transfer && $env_loaded) { return; }
550:
551: if (!defined($lonidsdir)) {
552: $lonidsdir = $perlvar{'lonIDsDir'};
553: }
554: if (!defined($handle)) {
555: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
556: }
557:
558: my $convert;
559: {
560: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
561: if (!$opened) {
562: return;
563: }
564: flock($idf,LOCK_SH);
565: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
566: &GDBM_READER(),0640)) {
567: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
568: untie(%disk_env);
569: } else {
570: $convert = 1;
571: }
572: }
573: if ($convert) {
574: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
575: &logthis("Failed to load session, or convert session.");
576: }
577: }
578:
579: my %remove;
580: while ( my $envname = each(%env) ) {
581: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
582: if ($time < time-300) {
583: $remove{$key}++;
584: }
585: }
586: }
587:
588: $env{'user.environment'} = "$lonidsdir/$handle.id";
589: $env_loaded=1;
590: foreach my $expired_key (keys(%remove)) {
591: &delenv($expired_key);
592: }
593: }
594:
595: # ---------------------------------------------------- Check for valid session
596: sub check_for_valid_session {
597: my ($r) = @_;
598: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
599: my $lonid=$cookies{'lonID'};
600: return undef if (!$lonid);
601:
602: my $handle=&LONCAPA::clean_handle($lonid->value);
603: my $lonidsdir=$r->dir_config('lonIDsDir');
604: return undef if (!-e "$lonidsdir/$handle.id");
605:
606: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
607: return undef if (!$opened);
608:
609: flock($idf,LOCK_SH);
610: my %disk_env;
611: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
612: &GDBM_READER(),0640)) {
613: return undef;
614: }
615:
616: if (!defined($disk_env{'user.name'})
617: || !defined($disk_env{'user.domain'})) {
618: return undef;
619: }
620: return $handle;
621: }
622:
623: sub timed_flock {
624: my ($file,$lock_type) = @_;
625: my $failed=0;
626: eval {
627: local $SIG{__DIE__}='DEFAULT';
628: local $SIG{ALRM}=sub {
629: $failed=1;
630: die("failed lock");
631: };
632: alarm(13);
633: flock($file,$lock_type);
634: alarm(0);
635: };
636: if ($failed) {
637: return undef;
638: } else {
639: return 1;
640: }
641: }
642:
643: # ---------------------------------------------------------- Append Environment
644:
645: sub appenv {
646: my ($newenv,$roles) = @_;
647: if (ref($newenv) eq 'HASH') {
648: foreach my $key (keys(%{$newenv})) {
649: my $refused = 0;
650: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
651: $refused = 1;
652: if (ref($roles) eq 'ARRAY') {
653: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
654: if (grep(/^\Q$role\E$/,@{$roles})) {
655: $refused = 0;
656: }
657: }
658: }
659: if ($refused) {
660: &logthis("<font color=\"blue\">WARNING: ".
661: "Attempt to modify environment ".$key." to ".$newenv->{$key}
662: .'</font>');
663: delete($newenv->{$key});
664: } else {
665: $env{$key}=$newenv->{$key};
666: }
667: }
668: my $opened = open(my $env_file,'+<',$env{'user.environment'});
669: if ($opened
670: && &timed_flock($env_file,LOCK_EX)
671: &&
672: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
673: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
674: while (my ($key,$value) = each(%{$newenv})) {
675: $disk_env{$key} = $value;
676: }
677: untie(%disk_env);
678: }
679: }
680: return 'ok';
681: }
682: # ----------------------------------------------------- Delete from Environment
683:
684: sub delenv {
685: my ($delthis,$regexp,$roles) = @_;
686: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
687: my $refused = 1;
688: if (ref($roles) eq 'ARRAY') {
689: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
690: if (grep(/^\Q$role\E$/,@{$roles})) {
691: $refused = 0;
692: }
693: }
694: if ($refused) {
695: &logthis("<font color=\"blue\">WARNING: ".
696: "Attempt to delete from environment ".$delthis);
697: return 'error';
698: }
699: }
700: my $opened = open(my $env_file,'+<',$env{'user.environment'});
701: if ($opened
702: && &timed_flock($env_file,LOCK_EX)
703: &&
704: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
706: foreach my $key (keys(%disk_env)) {
707: if ($regexp) {
708: if ($key=~/^$delthis/) {
709: delete($env{$key});
710: delete($disk_env{$key});
711: }
712: } else {
713: if ($key=~/^\Q$delthis\E/) {
714: delete($env{$key});
715: delete($disk_env{$key});
716: }
717: }
718: }
719: untie(%disk_env);
720: }
721: return 'ok';
722: }
723:
724: sub get_env_multiple {
725: my ($name) = @_;
726: my @values;
727: if (defined($env{$name})) {
728: # exists is it an array
729: if (ref($env{$name})) {
730: @values=@{ $env{$name} };
731: } else {
732: $values[0]=$env{$name};
733: }
734: }
735: return(@values);
736: }
737:
738: # ------------------------------------------------------------------- Locking
739:
740: sub set_lock {
741: my ($text)=@_;
742: $locknum++;
743: my $id=$$.'-'.$locknum;
744: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
745: 'session.lock.'.$id => $text});
746: return $id;
747: }
748:
749: sub get_locks {
750: my $num=0;
751: my %texts=();
752: foreach my $lock (split(/\,/,$env{'session.locks'})) {
753: if ($lock=~/\w/) {
754: $num++;
755: $texts{$lock}=$env{'session.lock.'.$lock};
756: }
757: }
758: return ($num,%texts);
759: }
760:
761: sub remove_lock {
762: my ($id)=@_;
763: my $newlocks='';
764: foreach my $lock (split(/\,/,$env{'session.locks'})) {
765: if (($lock=~/\w/) && ($lock ne $id)) {
766: $newlocks.=','.$lock;
767: }
768: }
769: &appenv({'session.locks' => $newlocks});
770: &delenv('session.lock.'.$id);
771: }
772:
773: sub remove_all_locks {
774: my $activelocks=$env{'session.locks'};
775: foreach my $lock (split(/\,/,$env{'session.locks'})) {
776: if ($lock=~/\w/) {
777: &remove_lock($lock);
778: }
779: }
780: }
781:
782:
783: # ------------------------------------------ Find out current server userload
784: sub userload {
785: my $numusers=0;
786: {
787: opendir(LONIDS,$perlvar{'lonIDsDir'});
788: my $filename;
789: my $curtime=time;
790: while ($filename=readdir(LONIDS)) {
791: next if ($filename eq '.' || $filename eq '..');
792: next if ($filename =~ /publicuser_\d+\.id/);
793: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
794: if ($curtime-$mtime < 1800) { $numusers++; }
795: }
796: closedir(LONIDS);
797: }
798: my $userloadpercent=0;
799: my $maxuserload=$perlvar{'lonUserLoadLim'};
800: if ($maxuserload) {
801: $userloadpercent=100*$numusers/$maxuserload;
802: }
803: $userloadpercent=sprintf("%.2f",$userloadpercent);
804: return $userloadpercent;
805: }
806:
807: # ------------------------------ Find server with least workload from spare.tab
808:
809: sub spareserver {
810: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
811: my $spare_server;
812: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
813: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
814: : $userloadpercent;
815: my ($uint_dom,$remotesessions);
816: if (($udom ne '') && (&domain($udom) ne '')) {
817: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
818: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
819: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
820: $remotesessions = $udomdefaults{'remotesessions'};
821: }
822: my $spareshash = &this_host_spares($udom);
823: if (ref($spareshash) eq 'HASH') {
824: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
825: foreach my $try_server (@{ $spareshash->{'primary'} }) {
826: if ($uint_dom) {
827: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
828: $try_server));
829: }
830: ($spare_server, $lowest_load) =
831: &compare_server_load($try_server, $spare_server, $lowest_load);
832: }
833: }
834:
835: my $found_server = ($spare_server ne '' && $lowest_load < 100);
836:
837: if (!$found_server) {
838: if (ref($spareshash->{'default'}) eq 'ARRAY') {
839: foreach my $try_server (@{ $spareshash->{'default'} }) {
840: if ($uint_dom) {
841: next unless (&spare_can_host($udom,$uint_dom,
842: $remotesessions,$try_server));
843: }
844: ($spare_server, $lowest_load) =
845: &compare_server_load($try_server, $spare_server, $lowest_load);
846: }
847: }
848: }
849: }
850:
851: if (!$want_server_name) {
852: my $protocol = 'http';
853: if ($protocol{$spare_server} eq 'https') {
854: $protocol = $protocol{$spare_server};
855: }
856: if (defined($spare_server)) {
857: my $hostname = &hostname($spare_server);
858: if (defined($hostname)) {
859: $spare_server = $protocol.'://'.$hostname;
860: }
861: }
862: }
863: return $spare_server;
864: }
865:
866: sub compare_server_load {
867: my ($try_server, $spare_server, $lowest_load) = @_;
868:
869: my $loadans = &reply('load', $try_server);
870: my $userloadans = &reply('userload',$try_server);
871:
872: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
873: return ($spare_server, $lowest_load); #didn't get a number from the server
874: }
875:
876: my $load;
877: if ($loadans =~ /\d/) {
878: if ($userloadans =~ /\d/) {
879: #both are numbers, pick the bigger one
880: $load = ($loadans > $userloadans) ? $loadans
881: : $userloadans;
882: } else {
883: $load = $loadans;
884: }
885: } else {
886: $load = $userloadans;
887: }
888:
889: if (($load =~ /\d/) && ($load < $lowest_load)) {
890: $spare_server = $try_server;
891: $lowest_load = $load;
892: }
893: return ($spare_server,$lowest_load);
894: }
895:
896: # --------------------------- ask offload servers if user already has a session
897: sub find_existing_session {
898: my ($udom,$uname) = @_;
899: my $spareshash = &this_host_spares($udom);
900: if (ref($spareshash) eq 'HASH') {
901: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
902: foreach my $try_server (@{ $spareshash->{'primary'} }) {
903: return $try_server if (&has_user_session($try_server, $udom, $uname));
904: }
905: }
906: if (ref($spareshash->{'default'}) eq 'ARRAY') {
907: foreach my $try_server (@{ $spareshash->{'default'} }) {
908: return $try_server if (&has_user_session($try_server, $udom, $uname));
909: }
910: }
911: }
912: return;
913: }
914:
915: # -------------------------------- ask if server already has a session for user
916: sub has_user_session {
917: my ($lonid,$udom,$uname) = @_;
918: my $result = &reply(join(':','userhassession',
919: map {&escape($_)} ($udom,$uname)),$lonid);
920: return 1 if ($result eq 'ok');
921:
922: return 0;
923: }
924:
925: # --------- determine least loaded server in a user's domain which allows login
926:
927: sub choose_server {
928: my ($udom,$checkloginvia) = @_;
929: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
930: my %servers = &get_servers($udom);
931: my $lowest_load = 30000;
932: my ($login_host,$hostname,$portal_path);
933: foreach my $lonhost (keys(%servers)) {
934: my $loginvia;
935: if ($checkloginvia) {
936: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
937: if ($loginvia) {
938: my ($server,$path) = split(/:/,$loginvia);
939: ($login_host, $lowest_load) =
940: &compare_server_load($server, $login_host, $lowest_load);
941: if ($login_host eq $server) {
942: $portal_path = $path;
943: }
944: } else {
945: ($login_host, $lowest_load) =
946: &compare_server_load($lonhost, $login_host, $lowest_load);
947: if ($login_host eq $lonhost) {
948: $portal_path = '';
949: }
950: }
951: } else {
952: ($login_host, $lowest_load) =
953: &compare_server_load($lonhost, $login_host, $lowest_load);
954: }
955: }
956: if ($login_host ne '') {
957: $hostname = &hostname($login_host);
958: }
959: return ($login_host,$hostname,$portal_path);
960: }
961:
962: # --------------------------------------------- Try to change a user's password
963:
964: sub changepass {
965: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
966: $currentpass = &escape($currentpass);
967: $newpass = &escape($newpass);
968: my $lonhost = $perlvar{'lonHostID'};
969: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
970: $server);
971: if (! $answer) {
972: &logthis("No reply on password change request to $server ".
973: "by $uname in domain $udom.");
974: } elsif ($answer =~ "^ok") {
975: &logthis("$uname in $udom successfully changed their password ".
976: "on $server.");
977: } elsif ($answer =~ "^pwchange_failure") {
978: &logthis("$uname in $udom was unable to change their password ".
979: "on $server. The action was blocked by either lcpasswd ".
980: "or pwchange");
981: } elsif ($answer =~ "^non_authorized") {
982: &logthis("$uname in $udom did not get their password correct when ".
983: "attempting to change it on $server.");
984: } elsif ($answer =~ "^auth_mode_error") {
985: &logthis("$uname in $udom attempted to change their password despite ".
986: "not being locally or internally authenticated on $server.");
987: } elsif ($answer =~ "^unknown_user") {
988: &logthis("$uname in $udom attempted to change their password ".
989: "on $server but were unable to because $server is not ".
990: "their home server.");
991: } elsif ($answer =~ "^refused") {
992: &logthis("$server refused to change $uname in $udom password because ".
993: "it was sent an unencrypted request to change the password.");
994: } elsif ($answer =~ "invalid_client") {
995: &logthis("$server refused to change $uname in $udom password because ".
996: "it was a reset by e-mail originating from an invalid server.");
997: }
998: return $answer;
999: }
1000:
1001: # ----------------------- Try to determine user's current authentication scheme
1002:
1003: sub queryauthenticate {
1004: my ($uname,$udom)=@_;
1005: my $uhome=&homeserver($uname,$udom);
1006: if (!$uhome) {
1007: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1008: return 'no_host';
1009: }
1010: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1011: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1012: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1013: }
1014: return $answer;
1015: }
1016:
1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1018:
1019: sub authenticate {
1020: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1021: $upass=&escape($upass);
1022: $uname= &LONCAPA::clean_username($uname);
1023: my $uhome=&homeserver($uname,$udom,1);
1024: my $newhome;
1025: if ((!$uhome) || ($uhome eq 'no_host')) {
1026: # Maybe the machine was offline and only re-appeared again recently?
1027: &reconlonc();
1028: # One more
1029: $uhome=&homeserver($uname,$udom,1);
1030: if (($uhome eq 'no_host') && $checkdefauth) {
1031: if (defined(&domain($udom,'primary'))) {
1032: $newhome=&domain($udom,'primary');
1033: }
1034: if ($newhome ne '') {
1035: $uhome = $newhome;
1036: }
1037: }
1038: if ((!$uhome) || ($uhome eq 'no_host')) {
1039: &logthis("User $uname at $udom is unknown in authenticate");
1040: return 'no_host';
1041: }
1042: }
1043: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1044: if ($answer eq 'authorized') {
1045: if ($newhome) {
1046: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1047: return 'no_account_on_host';
1048: } else {
1049: &logthis("User $uname at $udom authorized by $uhome");
1050: return $uhome;
1051: }
1052: }
1053: if ($answer eq 'non_authorized') {
1054: &logthis("User $uname at $udom rejected by $uhome");
1055: return 'no_host';
1056: }
1057: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1058: return 'no_host';
1059: }
1060:
1061: sub can_host_session {
1062: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1063: my $canhost = 1;
1064: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1065: if (ref($remotesessions) eq 'HASH') {
1066: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1067: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1068: $canhost = 0;
1069: } else {
1070: $canhost = 1;
1071: }
1072: }
1073: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1074: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1075: $canhost = 1;
1076: } else {
1077: $canhost = 0;
1078: }
1079: }
1080: if ($canhost) {
1081: if ($remotesessions->{'version'} ne '') {
1082: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1083: if ($reqmajor ne '' && $reqminor ne '') {
1084: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1085: my $major = $1;
1086: my $minor = $2;
1087: if (($major < $reqmajor ) ||
1088: (($major == $reqmajor) && ($minor < $reqminor))) {
1089: $canhost = 0;
1090: }
1091: } else {
1092: $canhost = 0;
1093: }
1094: }
1095: }
1096: }
1097: }
1098: if ($canhost) {
1099: if (ref($hostedsessions) eq 'HASH') {
1100: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1101: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1102: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1103: if (($uint_dom ne '') &&
1104: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1105: $canhost = 0;
1106: } else {
1107: $canhost = 1;
1108: }
1109: }
1110: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1111: if (($uint_dom ne '') &&
1112: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1113: $canhost = 1;
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: }
1119: }
1120: return $canhost;
1121: }
1122:
1123: sub spare_can_host {
1124: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1125: my $canhost=1;
1126: my @intdoms;
1127: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1128: if (ref($internet_names) eq 'ARRAY') {
1129: @intdoms = @{$internet_names};
1130: }
1131: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1132: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1133: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1134: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1135: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1136: $canhost = &can_host_session($udom,$try_server,$remoterev,
1137: $remotesessions,
1138: $defdomdefaults{'hostedsessions'});
1139: }
1140: return $canhost;
1141: }
1142:
1143: sub this_host_spares {
1144: my ($dom) = @_;
1145: my ($dom_in_use,$lonhost_in_use,$result);
1146: my @hosts = ¤t_machine_ids();
1147: foreach my $lonhost (@hosts) {
1148: if (&host_domain($lonhost) eq $dom) {
1149: $dom_in_use = $dom;
1150: $lonhost_in_use = $lonhost;
1151: last;
1152: }
1153: }
1154: if ($dom_in_use ne '') {
1155: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1156: }
1157: if (ref($result) ne 'HASH') {
1158: $lonhost_in_use = $perlvar{'lonHostID'};
1159: $dom_in_use = &host_domain($lonhost_in_use);
1160: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1161: if (ref($result) ne 'HASH') {
1162: $result = \%spareid;
1163: }
1164: }
1165: return $result;
1166: }
1167:
1168: sub spares_for_offload {
1169: my ($dom_in_use,$lonhost_in_use) = @_;
1170: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1171: if (defined($cached)) {
1172: return $result;
1173: } else {
1174: my $cachetime = 60*60*24;
1175: my %domconfig =
1176: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1177: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1178: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1179: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1180: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1181: }
1182: }
1183: }
1184: }
1185: return;
1186: }
1187:
1188: sub get_lonbalancer_config {
1189: my ($servers) = @_;
1190: my ($currbalancer,$currtargets);
1191: if (ref($servers) eq 'HASH') {
1192: foreach my $server (keys(%{$servers})) {
1193: my %what = (
1194: spareid => 1,
1195: perlvar => 1,
1196: );
1197: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1198: if ($result eq 'ok') {
1199: if (ref($returnhash) eq 'HASH') {
1200: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1201: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1202: $currbalancer = $server;
1203: $currtargets = {};
1204: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1205: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1206: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1207: }
1208: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1209: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1210: }
1211: }
1212: last;
1213: }
1214: }
1215: }
1216: }
1217: }
1218: }
1219: return ($currbalancer,$currtargets);
1220: }
1221:
1222: sub check_loadbalancing {
1223: my ($uname,$udom) = @_;
1224: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1225: $offloadto,$otherserver);
1226: my $lonhost = $perlvar{'lonHostID'};
1227: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1228: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1229: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1230: my $serverhomedom = &host_domain($lonhost);
1231:
1232: my $cachetime = 60*60*24;
1233:
1234: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1235: $dom_in_use = $udom;
1236: $homeintdom = 1;
1237: } else {
1238: $dom_in_use = $serverhomedom;
1239: }
1240: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1241: unless (defined($cached)) {
1242: my %domconfig =
1243: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1244: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1245: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1246: }
1247: }
1248: if (ref($result) eq 'HASH') {
1249: my $currbalancer = $result->{'lonhost'};
1250: my $currtargets = $result->{'targets'};
1251: my $currrules = $result->{'rules'};
1252: if ($currbalancer ne '') {
1253: my @hosts = ¤t_machine_ids();
1254: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1255: $is_balancer = 1;
1256: }
1257: }
1258: if ($is_balancer) {
1259: if (ref($currrules) eq 'HASH') {
1260: if ($homeintdom) {
1261: if ($uname ne '') {
1262: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1263: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1264: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1265: $rule_in_effect = $currrules->{'_LC_author'};
1266: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1267: $rule_in_effect = $currrules->{'_LC_adv'}
1268: }
1269: }
1270: if ($rule_in_effect eq '') {
1271: my %userenv = &userenvironment($udom,$uname,'inststatus');
1272: if ($userenv{'inststatus'} ne '') {
1273: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1274: my ($othertitle,$usertypes,$types) =
1275: &Apache::loncommon::sorted_inst_types($udom);
1276: if (ref($types) eq 'ARRAY') {
1277: foreach my $type (@{$types}) {
1278: if (grep(/^\Q$type\E$/,@statuses)) {
1279: if (exists($currrules->{$type})) {
1280: $rule_in_effect = $currrules->{$type};
1281: }
1282: }
1283: }
1284: }
1285: } else {
1286: if (exists($currrules->{'default'})) {
1287: $rule_in_effect = $currrules->{'default'};
1288: }
1289: }
1290: }
1291: } else {
1292: if (exists($currrules->{'default'})) {
1293: $rule_in_effect = $currrules->{'default'};
1294: }
1295: }
1296: } else {
1297: if ($currrules->{'_LC_external'} ne '') {
1298: $rule_in_effect = $currrules->{'_LC_external'};
1299: }
1300: }
1301: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1302: $uname,$udom);
1303: }
1304: }
1305: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1306: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1307: unless (defined($cached)) {
1308: my %domconfig =
1309: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1310: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1311: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1312: }
1313: }
1314: if (ref($result) eq 'HASH') {
1315: my $currbalancer = $result->{'lonhost'};
1316: my $currtargets = $result->{'targets'};
1317: my $currrules = $result->{'rules'};
1318:
1319: if ($currbalancer eq $lonhost) {
1320: $is_balancer = 1;
1321: if (ref($currrules) eq 'HASH') {
1322: if ($currrules->{'_LC_internetdom'} ne '') {
1323: $rule_in_effect = $currrules->{'_LC_internetdom'};
1324: }
1325: }
1326: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1327: $uname,$udom);
1328: }
1329: } else {
1330: if ($perlvar{'lonBalancer'} eq 'yes') {
1331: $is_balancer = 1;
1332: $offloadto = &this_host_spares($dom_in_use);
1333: }
1334: }
1335: } else {
1336: if ($perlvar{'lonBalancer'} eq 'yes') {
1337: $is_balancer = 1;
1338: $offloadto = &this_host_spares($dom_in_use);
1339: }
1340: }
1341: my $lowest_load = 30000;
1342: if (ref($offloadto) eq 'HASH') {
1343: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1344: foreach my $try_server (@{$offloadto->{'primary'}}) {
1345: ($otherserver,$lowest_load) =
1346: &compare_server_load($try_server,$otherserver,$lowest_load);
1347: }
1348: }
1349: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1350:
1351: if (!$found_server) {
1352: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1353: foreach my $try_server (@{$offloadto->{'default'}}) {
1354: ($otherserver,$lowest_load) =
1355: &compare_server_load($try_server,$otherserver,$lowest_load);
1356: }
1357: }
1358: }
1359: } elsif (ref($offloadto) eq 'ARRAY') {
1360: if (@{$offloadto} == 1) {
1361: $otherserver = $offloadto->[0];
1362: } elsif (@{$offloadto} > 1) {
1363: foreach my $try_server (@{$offloadto}) {
1364: ($otherserver,$lowest_load) =
1365: &compare_server_load($try_server,$otherserver,$lowest_load);
1366: }
1367: }
1368: }
1369: return ($is_balancer,$otherserver);
1370: }
1371:
1372: sub get_loadbalancer_targets {
1373: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1374: my $offloadto;
1375: if ($rule_in_effect eq '') {
1376: $offloadto = $currtargets;
1377: } else {
1378: if ($rule_in_effect eq 'homeserver') {
1379: my $homeserver = &homeserver($uname,$udom);
1380: if ($homeserver ne 'no_host') {
1381: $offloadto = [$homeserver];
1382: }
1383: } elsif ($rule_in_effect eq 'externalbalancer') {
1384: my %domconfig =
1385: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1386: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1387: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1388: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1389: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1390: }
1391: }
1392: } else {
1393: my %servers = &dom_servers($udom);
1394: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1395: if (&hostname($remotebalancer) ne '') {
1396: $offloadto = [$remotebalancer];
1397: }
1398: }
1399: } elsif (&hostname($rule_in_effect) ne '') {
1400: $offloadto = [$rule_in_effect];
1401: }
1402: }
1403: return $offloadto;
1404: }
1405:
1406: sub internet_dom_servers {
1407: my ($dom) = @_;
1408: my (%uniqservers,%servers);
1409: my $primaryserver = &hostname(&domain($dom,'primary'));
1410: my @machinedoms = &machine_domains($primaryserver);
1411: foreach my $mdom (@machinedoms) {
1412: my %currservers = %servers;
1413: my %server = &get_servers($mdom);
1414: %servers = (%currservers,%server);
1415: }
1416: my %by_hostname;
1417: foreach my $id (keys(%servers)) {
1418: push(@{$by_hostname{$servers{$id}}},$id);
1419: }
1420: foreach my $hostname (sort(keys(%by_hostname))) {
1421: if (@{$by_hostname{$hostname}} > 1) {
1422: my $match = 0;
1423: foreach my $id (@{$by_hostname{$hostname}}) {
1424: if (&host_domain($id) eq $dom) {
1425: $uniqservers{$id} = $hostname;
1426: $match = 1;
1427: }
1428: }
1429: unless ($match) {
1430: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1431: }
1432: } else {
1433: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1434: }
1435: }
1436: return %uniqservers;
1437: }
1438:
1439: # ---------------------- Find the homebase for a user from domain's lib servers
1440:
1441: my %homecache;
1442: sub homeserver {
1443: my ($uname,$udom,$ignoreBadCache)=@_;
1444: my $index="$uname:$udom";
1445:
1446: if (exists($homecache{$index})) { return $homecache{$index}; }
1447:
1448: my %servers = &get_servers($udom,'library');
1449: foreach my $tryserver (keys(%servers)) {
1450: next if ($ignoreBadCache ne 'true' &&
1451: exists($badServerCache{$tryserver}));
1452:
1453: my $answer=reply("home:$udom:$uname",$tryserver);
1454: if ($answer eq 'found') {
1455: delete($badServerCache{$tryserver});
1456: return $homecache{$index}=$tryserver;
1457: } elsif ($answer eq 'no_host') {
1458: $badServerCache{$tryserver}=1;
1459: }
1460: }
1461: return 'no_host';
1462: }
1463:
1464: # ------------------------------------- Find the usernames behind a list of IDs
1465:
1466: sub idget {
1467: my ($udom,@ids)=@_;
1468: my %returnhash=();
1469:
1470: my %servers = &get_servers($udom,'library');
1471: foreach my $tryserver (keys(%servers)) {
1472: my $idlist=join('&',@ids);
1473: $idlist=~tr/A-Z/a-z/;
1474: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1475: my @answer=();
1476: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1477: @answer=split(/\&/,$reply);
1478: } ;
1479: my $i;
1480: for ($i=0;$i<=$#ids;$i++) {
1481: if ($answer[$i]) {
1482: $returnhash{$ids[$i]}=$answer[$i];
1483: }
1484: }
1485: }
1486: return %returnhash;
1487: }
1488:
1489: # ------------------------------------- Find the IDs behind a list of usernames
1490:
1491: sub idrget {
1492: my ($udom,@unames)=@_;
1493: my %returnhash=();
1494: foreach my $uname (@unames) {
1495: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1496: }
1497: return %returnhash;
1498: }
1499:
1500: # ------------------------------- Store away a list of names and associated IDs
1501:
1502: sub idput {
1503: my ($udom,%ids)=@_;
1504: my %servers=();
1505: foreach my $uname (keys(%ids)) {
1506: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1507: my $uhom=&homeserver($uname,$udom);
1508: if ($uhom ne 'no_host') {
1509: my $id=&escape($ids{$uname});
1510: $id=~tr/A-Z/a-z/;
1511: my $esc_unam=&escape($uname);
1512: if ($servers{$uhom}) {
1513: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1514: } else {
1515: $servers{$uhom}=$id.'='.$esc_unam;
1516: }
1517: }
1518: }
1519: foreach my $server (keys(%servers)) {
1520: &critical('idput:'.$udom.':'.$servers{$server},$server);
1521: }
1522: }
1523:
1524: # ------------------------------dump from db file owned by domainconfig user
1525: sub dump_dom {
1526: my ($namespace,$udom,$regexp,$range)=@_;
1527: if (!$udom) {
1528: $udom=$env{'user.domain'};
1529: }
1530: my %returnhash;
1531: if ($udom) {
1532: my $uname = &get_domainconfiguser($udom);
1533: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1534: }
1535: return %returnhash;
1536: }
1537:
1538: # ------------------------------------------ get items from domain db files
1539:
1540: sub get_dom {
1541: my ($namespace,$storearr,$udom,$uhome)=@_;
1542: my $items='';
1543: foreach my $item (@$storearr) {
1544: $items.=&escape($item).'&';
1545: }
1546: $items=~s/\&$//;
1547: if (!$udom) {
1548: $udom=$env{'user.domain'};
1549: if (defined(&domain($udom,'primary'))) {
1550: $uhome=&domain($udom,'primary');
1551: } else {
1552: undef($uhome);
1553: }
1554: } else {
1555: if (!$uhome) {
1556: if (defined(&domain($udom,'primary'))) {
1557: $uhome=&domain($udom,'primary');
1558: }
1559: }
1560: }
1561: if ($udom && $uhome && ($uhome ne 'no_host')) {
1562: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1563: my %returnhash;
1564: if ($rep eq '' || $rep =~ /^error: 2 /) {
1565: return %returnhash;
1566: }
1567: my @pairs=split(/\&/,$rep);
1568: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1569: return @pairs;
1570: }
1571: my $i=0;
1572: foreach my $item (@$storearr) {
1573: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1574: $i++;
1575: }
1576: return %returnhash;
1577: } else {
1578: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1579: }
1580: }
1581:
1582: # -------------------------------------------- put items in domain db files
1583:
1584: sub put_dom {
1585: my ($namespace,$storehash,$udom,$uhome)=@_;
1586: if (!$udom) {
1587: $udom=$env{'user.domain'};
1588: if (defined(&domain($udom,'primary'))) {
1589: $uhome=&domain($udom,'primary');
1590: } else {
1591: undef($uhome);
1592: }
1593: } else {
1594: if (!$uhome) {
1595: if (defined(&domain($udom,'primary'))) {
1596: $uhome=&domain($udom,'primary');
1597: }
1598: }
1599: }
1600: if ($udom && $uhome && ($uhome ne 'no_host')) {
1601: my $items='';
1602: foreach my $item (keys(%$storehash)) {
1603: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1604: }
1605: $items=~s/\&$//;
1606: return &reply("putdom:$udom:$namespace:$items",$uhome);
1607: } else {
1608: &logthis("put_dom failed - no homeserver and/or domain");
1609: }
1610: }
1611:
1612: # --------------------- newput for items in db file owned by domainconfig user
1613: sub newput_dom {
1614: my ($namespace,$storehash,$udom) = @_;
1615: my $result;
1616: if (!$udom) {
1617: $udom=$env{'user.domain'};
1618: }
1619: if ($udom) {
1620: my $uname = &get_domainconfiguser($udom);
1621: $result = &newput($namespace,$storehash,$udom,$uname);
1622: }
1623: return $result;
1624: }
1625:
1626: # --------------------- delete for items in db file owned by domainconfig user
1627: sub del_dom {
1628: my ($namespace,$storearr,$udom)=@_;
1629: if (ref($storearr) eq 'ARRAY') {
1630: if (!$udom) {
1631: $udom=$env{'user.domain'};
1632: }
1633: if ($udom) {
1634: my $uname = &get_domainconfiguser($udom);
1635: return &del($namespace,$storearr,$udom,$uname);
1636: }
1637: }
1638: }
1639:
1640: # ----------------------------------construct domainconfig user for a domain
1641: sub get_domainconfiguser {
1642: my ($udom) = @_;
1643: return $udom.'-domainconfig';
1644: }
1645:
1646: sub retrieve_inst_usertypes {
1647: my ($udom) = @_;
1648: my (%returnhash,@order);
1649: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1650: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1651: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1652: %returnhash = %{$domdefs{'inststatustypes'}};
1653: @order = @{$domdefs{'inststatusorder'}};
1654: } else {
1655: if (defined(&domain($udom,'primary'))) {
1656: my $uhome=&domain($udom,'primary');
1657: my $rep=&reply("inst_usertypes:$udom",$uhome);
1658: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1659: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1660: return (\%returnhash,\@order);
1661: }
1662: my ($hashitems,$orderitems) = split(/:/,$rep);
1663: my @pairs=split(/\&/,$hashitems);
1664: foreach my $item (@pairs) {
1665: my ($key,$value)=split(/=/,$item,2);
1666: $key = &unescape($key);
1667: next if ($key =~ /^error: 2 /);
1668: $returnhash{$key}=&thaw_unescape($value);
1669: }
1670: my @esc_order = split(/\&/,$orderitems);
1671: foreach my $item (@esc_order) {
1672: push(@order,&unescape($item));
1673: }
1674: } else {
1675: &logthis("get_dom failed - no primary domain server for $udom");
1676: }
1677: }
1678: return (\%returnhash,\@order);
1679: }
1680:
1681: sub is_domainimage {
1682: my ($url) = @_;
1683: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1684: if (&domain($1) ne '') {
1685: return '1';
1686: }
1687: }
1688: return;
1689: }
1690:
1691: sub inst_directory_query {
1692: my ($srch) = @_;
1693: my $udom = $srch->{'srchdomain'};
1694: my %results;
1695: my $homeserver = &domain($udom,'primary');
1696: my $outcome;
1697: if ($homeserver ne '') {
1698: my $queryid=&reply("querysend:instdirsearch:".
1699: &escape($srch->{'srchby'}).':'.
1700: &escape($srch->{'srchterm'}).':'.
1701: &escape($srch->{'srchtype'}),$homeserver);
1702: my $host=&hostname($homeserver);
1703: if ($queryid !~/^\Q$host\E\_/) {
1704: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1705: return;
1706: }
1707: my $response = &get_query_reply($queryid);
1708: my $maxtries = 5;
1709: my $tries = 1;
1710: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1711: $response = &get_query_reply($queryid);
1712: $tries ++;
1713: }
1714:
1715: if (!&error($response) && $response ne 'refused') {
1716: if ($response eq 'unavailable') {
1717: $outcome = $response;
1718: } else {
1719: $outcome = 'ok';
1720: my @matches = split(/\n/,$response);
1721: foreach my $match (@matches) {
1722: my ($key,$value) = split(/=/,$match);
1723: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1724: }
1725: }
1726: }
1727: }
1728: return ($outcome,%results);
1729: }
1730:
1731: sub usersearch {
1732: my ($srch) = @_;
1733: my $dom = $srch->{'srchdomain'};
1734: my %results;
1735: my %libserv = &all_library();
1736: my $query = 'usersearch';
1737: foreach my $tryserver (keys(%libserv)) {
1738: if (&host_domain($tryserver) eq $dom) {
1739: my $host=&hostname($tryserver);
1740: my $queryid=
1741: &reply("querysend:".&escape($query).':'.
1742: &escape($srch->{'srchby'}).':'.
1743: &escape($srch->{'srchtype'}).':'.
1744: &escape($srch->{'srchterm'}),$tryserver);
1745: if ($queryid !~/^\Q$host\E\_/) {
1746: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1747: next;
1748: }
1749: my $reply = &get_query_reply($queryid);
1750: my $maxtries = 1;
1751: my $tries = 1;
1752: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1753: $reply = &get_query_reply($queryid);
1754: $tries ++;
1755: }
1756: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1757: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1758: } else {
1759: my @matches;
1760: if ($reply =~ /\n/) {
1761: @matches = split(/\n/,$reply);
1762: } else {
1763: @matches = split(/\&/,$reply);
1764: }
1765: foreach my $match (@matches) {
1766: my ($uname,$udom,%userhash);
1767: foreach my $entry (split(/:/,$match)) {
1768: my ($key,$value) =
1769: map {&unescape($_);} split(/=/,$entry);
1770: $userhash{$key} = $value;
1771: if ($key eq 'username') {
1772: $uname = $value;
1773: } elsif ($key eq 'domain') {
1774: $udom = $value;
1775: }
1776: }
1777: $results{$uname.':'.$udom} = \%userhash;
1778: }
1779: }
1780: }
1781: }
1782: return %results;
1783: }
1784:
1785: sub get_instuser {
1786: my ($udom,$uname,$id) = @_;
1787: my $homeserver = &domain($udom,'primary');
1788: my ($outcome,%results);
1789: if ($homeserver ne '') {
1790: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1791: &escape($id).':'.&escape($udom),$homeserver);
1792: my $host=&hostname($homeserver);
1793: if ($queryid !~/^\Q$host\E\_/) {
1794: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1795: return;
1796: }
1797: my $response = &get_query_reply($queryid);
1798: my $maxtries = 5;
1799: my $tries = 1;
1800: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1801: $response = &get_query_reply($queryid);
1802: $tries ++;
1803: }
1804: if (!&error($response) && $response ne 'refused') {
1805: if ($response eq 'unavailable') {
1806: $outcome = $response;
1807: } else {
1808: $outcome = 'ok';
1809: my @matches = split(/\n/,$response);
1810: foreach my $match (@matches) {
1811: my ($key,$value) = split(/=/,$match);
1812: $results{&unescape($key)} = &thaw_unescape($value);
1813: }
1814: }
1815: }
1816: }
1817: my %userinfo;
1818: if (ref($results{$uname}) eq 'HASH') {
1819: %userinfo = %{$results{$uname}};
1820: }
1821: return ($outcome,%userinfo);
1822: }
1823:
1824: sub inst_rulecheck {
1825: my ($udom,$uname,$id,$item,$rules) = @_;
1826: my %returnhash;
1827: if ($udom ne '') {
1828: if (ref($rules) eq 'ARRAY') {
1829: @{$rules} = map {&escape($_);} (@{$rules});
1830: my $rulestr = join(':',@{$rules});
1831: my $homeserver=&domain($udom,'primary');
1832: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1833: my $response;
1834: if ($item eq 'username') {
1835: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1836: ':'.&escape($uname).':'.$rulestr,
1837: $homeserver));
1838: } elsif ($item eq 'id') {
1839: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1840: ':'.&escape($id).':'.$rulestr,
1841: $homeserver));
1842: } elsif ($item eq 'selfcreate') {
1843: $response=&unescape(&reply('instselfcreatecheck:'.
1844: &escape($udom).':'.&escape($uname).
1845: ':'.$rulestr,$homeserver));
1846: }
1847: if ($response ne 'refused') {
1848: my @pairs=split(/\&/,$response);
1849: foreach my $item (@pairs) {
1850: my ($key,$value)=split(/=/,$item,2);
1851: $key = &unescape($key);
1852: next if ($key =~ /^error: 2 /);
1853: $returnhash{$key}=&thaw_unescape($value);
1854: }
1855: }
1856: }
1857: }
1858: }
1859: return %returnhash;
1860: }
1861:
1862: sub inst_userrules {
1863: my ($udom,$check) = @_;
1864: my (%ruleshash,@ruleorder);
1865: if ($udom ne '') {
1866: my $homeserver=&domain($udom,'primary');
1867: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1868: my $response;
1869: if ($check eq 'id') {
1870: $response=&reply('instidrules:'.&escape($udom),
1871: $homeserver);
1872: } elsif ($check eq 'email') {
1873: $response=&reply('instemailrules:'.&escape($udom),
1874: $homeserver);
1875: } else {
1876: $response=&reply('instuserrules:'.&escape($udom),
1877: $homeserver);
1878: }
1879: if (($response ne 'refused') && ($response ne 'error') &&
1880: ($response ne 'unknown_cmd') &&
1881: ($response ne 'no_such_host')) {
1882: my ($hashitems,$orderitems) = split(/:/,$response);
1883: my @pairs=split(/\&/,$hashitems);
1884: foreach my $item (@pairs) {
1885: my ($key,$value)=split(/=/,$item,2);
1886: $key = &unescape($key);
1887: next if ($key =~ /^error: 2 /);
1888: $ruleshash{$key}=&thaw_unescape($value);
1889: }
1890: my @esc_order = split(/\&/,$orderitems);
1891: foreach my $item (@esc_order) {
1892: push(@ruleorder,&unescape($item));
1893: }
1894: }
1895: }
1896: }
1897: return (\%ruleshash,\@ruleorder);
1898: }
1899:
1900: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1901:
1902: sub get_domain_defaults {
1903: my ($domain) = @_;
1904: my $cachetime = 60*60*24;
1905: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1906: if (defined($cached)) {
1907: if (ref($result) eq 'HASH') {
1908: return %{$result};
1909: }
1910: }
1911: my %domdefaults;
1912: my %domconfig =
1913: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1914: 'requestcourses','inststatus',
1915: 'coursedefaults','usersessions'],$domain);
1916: if (ref($domconfig{'defaults'}) eq 'HASH') {
1917: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1918: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1919: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1920: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1921: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1922: } else {
1923: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1924: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1925: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1926: }
1927: if (ref($domconfig{'quotas'}) eq 'HASH') {
1928: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1929: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1930: } else {
1931: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1932: }
1933: my @usertools = ('aboutme','blog','portfolio');
1934: foreach my $item (@usertools) {
1935: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1936: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1937: }
1938: }
1939: }
1940: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1941: foreach my $item ('official','unofficial','community') {
1942: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1943: }
1944: }
1945: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1946: foreach my $item ('inststatustypes','inststatusorder') {
1947: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1948: }
1949: }
1950: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1951: foreach my $item ('canuse_pdfforms') {
1952: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1953: }
1954: }
1955: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1956: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1957: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1958: }
1959: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1960: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1961: }
1962: }
1963: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1964: $cachetime);
1965: return %domdefaults;
1966: }
1967:
1968: # --------------------------------------------------- Assign a key to a student
1969:
1970: sub assign_access_key {
1971: #
1972: # a valid key looks like uname:udom#comments
1973: # comments are being appended
1974: #
1975: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1976: $kdom=
1977: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1978: $knum=
1979: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1980: $cdom=
1981: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1982: $cnum=
1983: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1984: $udom=$env{'user.name'} unless (defined($udom));
1985: $uname=$env{'user.domain'} unless (defined($uname));
1986: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1987: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1988: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1989: # assigned to this person
1990: # - this should not happen,
1991: # unless something went wrong
1992: # the first time around
1993: # ready to assign
1994: $logentry=$1.'; '.$logentry;
1995: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1996: $kdom,$knum) eq 'ok') {
1997: # key now belongs to user
1998: my $envkey='key.'.$cdom.'_'.$cnum;
1999: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2000: &appenv({'environment.'.$envkey => $ckey});
2001: return 'ok';
2002: } else {
2003: return
2004: 'error: Count not permanently assign key, will need to be re-entered later.';
2005: }
2006: } else {
2007: return 'error: Could not assign key, try again later.';
2008: }
2009: } elsif (!$existing{$ckey}) {
2010: # the key does not exist
2011: return 'error: The key does not exist';
2012: } else {
2013: # the key is somebody else's
2014: return 'error: The key is already in use';
2015: }
2016: }
2017:
2018: # ------------------------------------------ put an additional comment on a key
2019:
2020: sub comment_access_key {
2021: #
2022: # a valid key looks like uname:udom#comments
2023: # comments are being appended
2024: #
2025: my ($ckey,$cdom,$cnum,$logentry)=@_;
2026: $cdom=
2027: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2028: $cnum=
2029: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2030: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2031: if ($existing{$ckey}) {
2032: $existing{$ckey}.='; '.$logentry;
2033: # ready to assign
2034: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2035: $cdom,$cnum) eq 'ok') {
2036: return 'ok';
2037: } else {
2038: return 'error: Count not store comment.';
2039: }
2040: } else {
2041: # the key does not exist
2042: return 'error: The key does not exist';
2043: }
2044: }
2045:
2046: # ------------------------------------------------------ Generate a set of keys
2047:
2048: sub generate_access_keys {
2049: my ($number,$cdom,$cnum,$logentry)=@_;
2050: $cdom=
2051: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2052: $cnum=
2053: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2054: unless (&allowed('mky',$cdom)) { return 0; }
2055: unless (($cdom) && ($cnum)) { return 0; }
2056: if ($number>10000) { return 0; }
2057: sleep(2); # make sure don't get same seed twice
2058: srand(time()^($$+($$<<15))); # from "Programming Perl"
2059: my $total=0;
2060: for (my $i=1;$i<=$number;$i++) {
2061: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2062: sprintf("%lx",int(100000*rand)).'-'.
2063: sprintf("%lx",int(100000*rand));
2064: $newkey=~s/1/g/g; # folks mix up 1 and l
2065: $newkey=~s/0/h/g; # and also 0 and O
2066: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2067: if ($existing{$newkey}) {
2068: $i--;
2069: } else {
2070: if (&put('accesskeys',
2071: { $newkey => '# generated '.localtime().
2072: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2073: '; '.$logentry },
2074: $cdom,$cnum) eq 'ok') {
2075: $total++;
2076: }
2077: }
2078: }
2079: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2080: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2081: return $total;
2082: }
2083:
2084: # ------------------------------------------------------- Validate an accesskey
2085:
2086: sub validate_access_key {
2087: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2088: $cdom=
2089: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2090: $cnum=
2091: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2092: $udom=$env{'user.domain'} unless (defined($udom));
2093: $uname=$env{'user.name'} unless (defined($uname));
2094: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2095: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2096: }
2097:
2098: # ------------------------------------- Find the section of student in a course
2099: sub devalidate_getsection_cache {
2100: my ($udom,$unam,$courseid)=@_;
2101: my $hashid="$udom:$unam:$courseid";
2102: &devalidate_cache_new('getsection',$hashid);
2103: }
2104:
2105: sub courseid_to_courseurl {
2106: my ($courseid) = @_;
2107: #already url style courseid
2108: return $courseid if ($courseid =~ m{^/});
2109:
2110: if (exists($env{'course.'.$courseid.'.num'})) {
2111: my $cnum = $env{'course.'.$courseid.'.num'};
2112: my $cdom = $env{'course.'.$courseid.'.domain'};
2113: return "/$cdom/$cnum";
2114: }
2115:
2116: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2117: if (exists($courseinfo{'num'})) {
2118: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2119: }
2120:
2121: return undef;
2122: }
2123:
2124: sub getsection {
2125: my ($udom,$unam,$courseid)=@_;
2126: my $cachetime=1800;
2127:
2128: my $hashid="$udom:$unam:$courseid";
2129: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2130: if (defined($cached)) { return $result; }
2131:
2132: my %Pending;
2133: my %Expired;
2134: #
2135: # Each role can either have not started yet (pending), be active,
2136: # or have expired.
2137: #
2138: # If there is an active role, we are done.
2139: #
2140: # If there is more than one role which has not started yet,
2141: # choose the one which will start sooner
2142: # If there is one role which has not started yet, return it.
2143: #
2144: # If there is more than one expired role, choose the one which ended last.
2145: # If there is a role which has expired, return it.
2146: #
2147: $courseid = &courseid_to_courseurl($courseid);
2148: my $extra = &freeze_escape({'skipcheck' => 1});
2149: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
2150: foreach my $key (keys(%roleshash)) {
2151: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2152: my $section=$1;
2153: if ($key eq $courseid.'_st') { $section=''; }
2154: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2155: my $now=time;
2156: if (defined($end) && $end && ($now > $end)) {
2157: $Expired{$end}=$section;
2158: next;
2159: }
2160: if (defined($start) && $start && ($now < $start)) {
2161: $Pending{$start}=$section;
2162: next;
2163: }
2164: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2165: }
2166: #
2167: # Presumedly there will be few matching roles from the above
2168: # loop and the sorting time will be negligible.
2169: if (scalar(keys(%Pending))) {
2170: my ($time) = sort {$a <=> $b} keys(%Pending);
2171: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2172: }
2173: if (scalar(keys(%Expired))) {
2174: my @sorted = sort {$a <=> $b} keys(%Expired);
2175: my $time = pop(@sorted);
2176: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2177: }
2178: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2179: }
2180:
2181: sub save_cache {
2182: &purge_remembered();
2183: #&Apache::loncommon::validate_page();
2184: undef(%env);
2185: undef($env_loaded);
2186: }
2187:
2188: my $to_remember=-1;
2189: my %remembered;
2190: my %accessed;
2191: my $kicks=0;
2192: my $hits=0;
2193: sub make_key {
2194: my ($name,$id) = @_;
2195: if (length($id) > 65
2196: && length(&escape($id)) > 200) {
2197: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2198: }
2199: return &escape($name.':'.$id);
2200: }
2201:
2202: sub devalidate_cache_new {
2203: my ($name,$id,$debug) = @_;
2204: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2205: $id=&make_key($name,$id);
2206: $memcache->delete($id);
2207: delete($remembered{$id});
2208: delete($accessed{$id});
2209: }
2210:
2211: sub is_cached_new {
2212: my ($name,$id,$debug) = @_;
2213: $id=&make_key($name,$id);
2214: if (exists($remembered{$id})) {
2215: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2216: $accessed{$id}=[&gettimeofday()];
2217: $hits++;
2218: return ($remembered{$id},1);
2219: }
2220: my $value = $memcache->get($id);
2221: if (!(defined($value))) {
2222: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2223: return (undef,undef);
2224: }
2225: if ($value eq '__undef__') {
2226: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2227: $value=undef;
2228: }
2229: &make_room($id,$value,$debug);
2230: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2231: return ($value,1);
2232: }
2233:
2234: sub do_cache_new {
2235: my ($name,$id,$value,$time,$debug) = @_;
2236: $id=&make_key($name,$id);
2237: my $setvalue=$value;
2238: if (!defined($setvalue)) {
2239: $setvalue='__undef__';
2240: }
2241: if (!defined($time) ) {
2242: $time=600;
2243: }
2244: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2245: my $result = $memcache->set($id,$setvalue,$time);
2246: if (! $result) {
2247: &logthis("caching of id -> $id failed");
2248: $memcache->disconnect_all();
2249: }
2250: # need to make a copy of $value
2251: &make_room($id,$value,$debug);
2252: return $value;
2253: }
2254:
2255: sub make_room {
2256: my ($id,$value,$debug)=@_;
2257:
2258: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2259: : $value;
2260: if ($to_remember<0) { return; }
2261: $accessed{$id}=[&gettimeofday()];
2262: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2263: my $to_kick;
2264: my $max_time=0;
2265: foreach my $other (keys(%accessed)) {
2266: if (&tv_interval($accessed{$other}) > $max_time) {
2267: $to_kick=$other;
2268: $max_time=&tv_interval($accessed{$other});
2269: }
2270: }
2271: delete($remembered{$to_kick});
2272: delete($accessed{$to_kick});
2273: $kicks++;
2274: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2275: return;
2276: }
2277:
2278: sub purge_remembered {
2279: #&logthis("Tossing ".scalar(keys(%remembered)));
2280: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2281: undef(%remembered);
2282: undef(%accessed);
2283: }
2284: # ------------------------------------- Read an entry from a user's environment
2285:
2286: sub userenvironment {
2287: my ($udom,$unam,@what)=@_;
2288: my $items;
2289: foreach my $item (@what) {
2290: $items.=&escape($item).'&';
2291: }
2292: $items=~s/\&$//;
2293: my %returnhash=();
2294: my $uhome = &homeserver($unam,$udom);
2295: unless ($uhome eq 'no_host') {
2296: my @answer=split(/\&/,
2297: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2298: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2299: return %returnhash;
2300: }
2301: my $i;
2302: for ($i=0;$i<=$#what;$i++) {
2303: $returnhash{$what[$i]}=&unescape($answer[$i]);
2304: }
2305: }
2306: return %returnhash;
2307: }
2308:
2309: # ---------------------------------------------------------- Get a studentphoto
2310: sub studentphoto {
2311: my ($udom,$unam,$ext) = @_;
2312: my $home=&Apache::lonnet::homeserver($unam,$udom);
2313: if (defined($env{'request.course.id'})) {
2314: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2315: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2316: return(&retrievestudentphoto($udom,$unam,$ext));
2317: } else {
2318: my ($result,$perm_reqd)=
2319: &Apache::lonnet::auto_photo_permission($unam,$udom);
2320: if ($result eq 'ok') {
2321: if (!($perm_reqd eq 'yes')) {
2322: return(&retrievestudentphoto($udom,$unam,$ext));
2323: }
2324: }
2325: }
2326: }
2327: } else {
2328: my ($result,$perm_reqd) =
2329: &Apache::lonnet::auto_photo_permission($unam,$udom);
2330: if ($result eq 'ok') {
2331: if (!($perm_reqd eq 'yes')) {
2332: return(&retrievestudentphoto($udom,$unam,$ext));
2333: }
2334: }
2335: }
2336: return '/adm/lonKaputt/lonlogo_broken.gif';
2337: }
2338:
2339: sub retrievestudentphoto {
2340: my ($udom,$unam,$ext,$type) = @_;
2341: my $home=&Apache::lonnet::homeserver($unam,$udom);
2342: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2343: if ($ret eq 'ok') {
2344: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2345: if ($type eq 'thumbnail') {
2346: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2347: }
2348: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2349: return $tokenurl;
2350: } else {
2351: if ($type eq 'thumbnail') {
2352: return '/adm/lonKaputt/genericstudent_tn.gif';
2353: } else {
2354: return '/adm/lonKaputt/lonlogo_broken.gif';
2355: }
2356: }
2357: }
2358:
2359: # -------------------------------------------------------------------- New chat
2360:
2361: sub chatsend {
2362: my ($newentry,$anon,$group)=@_;
2363: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2364: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2365: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2366: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2367: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2368: &escape($newentry)).':'.$group,$chome);
2369: }
2370:
2371: # ------------------------------------------ Find current version of a resource
2372:
2373: sub getversion {
2374: my $fname=&clutter(shift);
2375: unless ($fname=~/^\/res\//) { return -1; }
2376: return ¤tversion(&filelocation('',$fname));
2377: }
2378:
2379: sub currentversion {
2380: my $fname=shift;
2381: my $author=$fname;
2382: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2383: my ($udom,$uname)=split(/\//,$author);
2384: my $home=&homeserver($uname,$udom);
2385: if ($home eq 'no_host') {
2386: return -1;
2387: }
2388: my $answer=&reply("currentversion:$fname",$home);
2389: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2390: return -1;
2391: }
2392: return $answer;
2393: }
2394:
2395: #
2396: # Return special version number of resource if set by override, empty otherwise
2397: #
2398: sub usedversion {
2399: my $fname=shift;
2400: unless ($fname) { $fname=$env{'request.uri'}; }
2401: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2402: if ($urlversion) { return $urlversion; }
2403: return '';
2404: }
2405:
2406: # ----------------------------- Subscribe to a resource, return URL if possible
2407:
2408: sub subscribe {
2409: my $fname=shift;
2410: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2411: $fname=~s/[\n\r]//g;
2412: my $author=$fname;
2413: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2414: my ($udom,$uname)=split(/\//,$author);
2415: my $home=homeserver($uname,$udom);
2416: if ($home eq 'no_host') {
2417: return 'not_found';
2418: }
2419: my $answer=reply("sub:$fname",$home);
2420: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2421: $answer.=' by '.$home;
2422: }
2423: return $answer;
2424: }
2425:
2426: # -------------------------------------------------------------- Replicate file
2427:
2428: sub repcopy {
2429: my $filename=shift;
2430: $filename=~s/\/+/\//g;
2431: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2432: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
2433: if ($filename=~m|^/home/httpd/html/userfiles/| or
2434: $filename=~m -^/*(uploaded|editupload)/-) {
2435: return &repcopy_userfile($filename);
2436: }
2437: $filename=~s/[\n\r]//g;
2438: my $transname="$filename.in.transfer";
2439: # FIXME: this should flock
2440: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2441: my $remoteurl=subscribe($filename);
2442: if ($remoteurl =~ /^con_lost by/) {
2443: &logthis("Subscribe returned $remoteurl: $filename");
2444: return 'unavailable';
2445: } elsif ($remoteurl eq 'not_found') {
2446: #&logthis("Subscribe returned not_found: $filename");
2447: return 'not_found';
2448: } elsif ($remoteurl =~ /^rejected by/) {
2449: &logthis("Subscribe returned $remoteurl: $filename");
2450: return 'forbidden';
2451: } elsif ($remoteurl eq 'directory') {
2452: return 'ok';
2453: } else {
2454: my $author=$filename;
2455: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2456: my ($udom,$uname)=split(/\//,$author);
2457: my $home=homeserver($uname,$udom);
2458: unless ($home eq $perlvar{'lonHostID'}) {
2459: my @parts=split(/\//,$filename);
2460: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2461: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2462: &logthis("Malconfiguration for replication: $filename");
2463: return 'bad_request';
2464: }
2465: my $count;
2466: for ($count=5;$count<$#parts;$count++) {
2467: $path.="/$parts[$count]";
2468: if ((-e $path)!=1) {
2469: mkdir($path,0777);
2470: }
2471: }
2472: my $ua=new LWP::UserAgent;
2473: my $request=new HTTP::Request('GET',"$remoteurl");
2474: my $response=$ua->request($request,$transname);
2475: if ($response->is_error()) {
2476: unlink($transname);
2477: my $message=$response->status_line;
2478: &logthis("<font color=\"blue\">WARNING:"
2479: ." LWP get: $message: $filename</font>");
2480: return 'unavailable';
2481: } else {
2482: if ($remoteurl!~/\.meta$/) {
2483: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2484: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2485: if ($mresponse->is_error()) {
2486: unlink($filename.'.meta');
2487: &logthis(
2488: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2489: }
2490: }
2491: rename($transname,$filename);
2492: return 'ok';
2493: }
2494: }
2495: }
2496: }
2497:
2498: # ------------------------------------------------ Get server side include body
2499: sub ssi_body {
2500: my ($filelink,%form)=@_;
2501: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2502: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2503: }
2504: my $output='';
2505: my $response;
2506: if ($filelink=~/^https?\:/) {
2507: ($output,$response)=&externalssi($filelink);
2508: } else {
2509: $filelink .= $filelink=~/\?/ ? '&' : '?';
2510: $filelink .= 'inhibitmenu=yes';
2511: ($output,$response)=&ssi($filelink,%form);
2512: }
2513: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2514: $output=~s/^.*?\<body[^\>]*\>//si;
2515: $output=~s/\<\/body\s*\>.*?$//si;
2516: if (wantarray) {
2517: return ($output, $response);
2518: } else {
2519: return $output;
2520: }
2521: }
2522:
2523: # --------------------------------------------------------- Server Side Include
2524:
2525: sub absolute_url {
2526: my ($host_name) = @_;
2527: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2528: if ($host_name eq '') {
2529: $host_name = $ENV{'SERVER_NAME'};
2530: }
2531: return $protocol.$host_name;
2532: }
2533:
2534: #
2535: # Server side include.
2536: # Parameters:
2537: # fn Possibly encrypted resource name/id.
2538: # form Hash that describes how the rendering should be done
2539: # and other things.
2540: # Returns:
2541: # Scalar context: The content of the response.
2542: # Array context: 2 element list of the content and the full response object.
2543: #
2544: sub ssi {
2545:
2546: my ($fn,%form)=@_;
2547: my $ua=new LWP::UserAgent;
2548: my $request;
2549:
2550: $form{'no_update_last_known'}=1;
2551: &Apache::lonenc::check_encrypt(\$fn);
2552: if (%form) {
2553: $request=new HTTP::Request('POST',&absolute_url().$fn);
2554: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2555: } else {
2556: $request=new HTTP::Request('GET',&absolute_url().$fn);
2557: }
2558:
2559: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2560: my $response=$ua->request($request);
2561:
2562: if (wantarray) {
2563: return ($response->content, $response);
2564: } else {
2565: return $response->content;
2566: }
2567: }
2568:
2569: sub externalssi {
2570: my ($url)=@_;
2571: my $ua=new LWP::UserAgent;
2572: my $request=new HTTP::Request('GET',$url);
2573: my $response=$ua->request($request);
2574: if (wantarray) {
2575: return ($response->content, $response);
2576: } else {
2577: return $response->content;
2578: }
2579: }
2580:
2581: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2582:
2583: sub allowuploaded {
2584: my ($srcurl,$url)=@_;
2585: $url=&clutter(&declutter($url));
2586: my $dir=$url;
2587: $dir=~s/\/[^\/]+$//;
2588: my %httpref=();
2589: my $httpurl=&hreflocation('',$url);
2590: $httpref{'httpref.'.$httpurl}=$srcurl;
2591: &Apache::lonnet::appenv(\%httpref);
2592: }
2593:
2594: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2595: # input: action, courseID, current domain, intended
2596: # path to file, source of file, instruction to parse file for objects,
2597: # ref to hash for embedded objects,
2598: # ref to hash for codebase of java objects.
2599: # reference to scalar to accommodate mime type determined
2600: # from File::MMagic if $parser = parse.
2601: #
2602: # output: url to file (if action was uploaddoc),
2603: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2604: #
2605: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2606: # course.
2607: #
2608: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2609: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2610: # course's home server.
2611: #
2612: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2613: # be copied from $source (current location) to
2614: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2615: # and will then be copied to
2616: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2617: # course's home server.
2618: #
2619: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2620: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2621: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2622: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2623: # in course's home server.
2624: #
2625:
2626: sub process_coursefile {
2627: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2628: $mimetype)=@_;
2629: my $fetchresult;
2630: my $home=&homeserver($docuname,$docudom);
2631: if ($action eq 'propagate') {
2632: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2633: $home);
2634: } else {
2635: my $fpath = '';
2636: my $fname = $file;
2637: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2638: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2639: my $filepath = &build_filepath($fpath);
2640: if ($action eq 'copy') {
2641: if ($source eq '') {
2642: $fetchresult = 'no source file';
2643: return $fetchresult;
2644: } else {
2645: my $destination = $filepath.'/'.$fname;
2646: rename($source,$destination);
2647: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2648: $home);
2649: }
2650: } elsif ($action eq 'uploaddoc') {
2651: open(my $fh,'>'.$filepath.'/'.$fname);
2652: print $fh $env{'form.'.$source};
2653: close($fh);
2654: if ($parser eq 'parse') {
2655: my $mm = new File::MMagic;
2656: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2657: if ($type eq 'text/html') {
2658: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2659: unless ($parse_result eq 'ok') {
2660: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2661: }
2662: }
2663: if (ref($mimetype)) {
2664: $$mimetype = $type;
2665: }
2666: }
2667: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2668: $home);
2669: if ($fetchresult eq 'ok') {
2670: return '/uploaded/'.$fpath.'/'.$fname;
2671: } else {
2672: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2673: ' to host '.$home.': '.$fetchresult);
2674: return '/adm/notfound.html';
2675: }
2676: }
2677: }
2678: unless ( $fetchresult eq 'ok') {
2679: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2680: ' to host '.$home.': '.$fetchresult);
2681: }
2682: return $fetchresult;
2683: }
2684:
2685: sub build_filepath {
2686: my ($fpath) = @_;
2687: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2688: unless ($fpath eq '') {
2689: my @parts=split('/',$fpath);
2690: foreach my $part (@parts) {
2691: $filepath.= '/'.$part;
2692: if ((-e $filepath)!=1) {
2693: mkdir($filepath,0777);
2694: }
2695: }
2696: }
2697: return $filepath;
2698: }
2699:
2700: sub store_edited_file {
2701: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2702: my $file = $primary_url;
2703: $file =~ s#^/uploaded/$docudom/$docuname/##;
2704: my $fpath = '';
2705: my $fname = $file;
2706: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2707: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2708: my $filepath = &build_filepath($fpath);
2709: open(my $fh,'>'.$filepath.'/'.$fname);
2710: print $fh $content;
2711: close($fh);
2712: my $home=&homeserver($docuname,$docudom);
2713: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2714: $home);
2715: if ($$fetchresult eq 'ok') {
2716: return '/uploaded/'.$fpath.'/'.$fname;
2717: } else {
2718: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2719: ' to host '.$home.': '.$$fetchresult);
2720: return '/adm/notfound.html';
2721: }
2722: }
2723:
2724: sub clean_filename {
2725: my ($fname,$args)=@_;
2726: # Replace Windows backslashes by forward slashes
2727: $fname=~s/\\/\//g;
2728: if (!$args->{'keep_path'}) {
2729: # Get rid of everything but the actual filename
2730: $fname=~s/^.*\/([^\/]+)$/$1/;
2731: }
2732: # Replace spaces by underscores
2733: $fname=~s/\s+/\_/g;
2734: # Replace all other weird characters by nothing
2735: $fname=~s{[^/\w\.\-]}{}g;
2736: # Replace all .\d. sequences with _\d. so they no longer look like version
2737: # numbers
2738: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2739: return $fname;
2740: }
2741: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2742: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2743: # image with the same aspect ratio as the original, but with dimensions which do
2744: # not exceed $resizewidth and $resizeheight.
2745:
2746: sub resizeImage {
2747: my ($img_path,$resizewidth,$resizeheight) = @_;
2748: my $ima = Image::Magick->new;
2749: my $resized;
2750: if (-e $img_path) {
2751: $ima->Read($img_path);
2752: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2753: my $width = $ima->Get('width');
2754: my $height = $ima->Get('height');
2755: if ($width > $resizewidth) {
2756: my $factor = $width/$resizewidth;
2757: my $newheight = $height/$factor;
2758: $ima->Scale(width=>$resizewidth,height=>$newheight);
2759: $resized = 1;
2760: }
2761: }
2762: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2763: my $width = $ima->Get('width');
2764: my $height = $ima->Get('height');
2765: if ($height > $resizeheight) {
2766: my $factor = $height/$resizeheight;
2767: my $newwidth = $width/$factor;
2768: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2769: $resized = 1;
2770: }
2771: }
2772: if ($resized) {
2773: $ima->Write($img_path);
2774: }
2775: }
2776: return;
2777: }
2778:
2779: # --------------- Take an uploaded file and put it into the userfiles directory
2780: # input: $formname - the contents of the file are in $env{"form.$formname"}
2781: # the desired filename is in $env{"form.$formname.filename"}
2782: # $context - possible values: coursedoc, existingfile, overwrite,
2783: # canceloverwrite, or ''.
2784: # if 'coursedoc': upload to the current course
2785: # if 'existingfile': write file to tmp/overwrites directory
2786: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2787: # $context is passed as argument to &finishuserfileupload
2788: # $subdir - directory in userfile to store the file into
2789: # $parser - instruction to parse file for objects ($parser = parse)
2790: # $allfiles - reference to hash for embedded objects
2791: # $codebase - reference to hash for codebase of java objects
2792: # $desuname - username for permanent storage of uploaded file
2793: # $dsetudom - domain for permanaent storage of uploaded file
2794: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2795: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2796: # $resizewidth - width (pixels) to which to resize uploaded image
2797: # $resizeheight - height (pixels) to which to resize uploaded image
2798: # $mimetype - reference to scalar to accommodate mime type determined
2799: # from File::MMagic if $parser = parse.
2800: #
2801: # output: url of file in userspace, or error: <message>
2802: # or /adm/notfound.html if failure to upload occurse
2803:
2804: sub userfileupload {
2805: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2806: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2807: if (!defined($subdir)) { $subdir='unknown'; }
2808: my $fname=$env{'form.'.$formname.'.filename'};
2809: $fname=&clean_filename($fname);
2810: # See if there is anything left
2811: unless ($fname) { return 'error: no uploaded file'; }
2812: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2813: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2814: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2815: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2816: my $now = time;
2817: my $filepath;
2818: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2819: $filepath = 'tmp/helprequests/'.$now;
2820: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2821: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2822: '_'.$env{'user.domain'}.'/pending';
2823: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2824: my ($docuname,$docudom);
2825: if ($destudom) {
2826: $docudom = $destudom;
2827: } else {
2828: $docudom = $env{'user.domain'};
2829: }
2830: if ($destuname) {
2831: $docuname = $destuname;
2832: } else {
2833: $docuname = $env{'user.name'};
2834: }
2835: if (exists($env{'form.group'})) {
2836: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2837: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2838: }
2839: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2840: if ($context eq 'canceloverwrite') {
2841: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2842: if (-e $tempfile) {
2843: my @info = stat($tempfile);
2844: if ($info[9] eq $env{'form.timestamp'}) {
2845: unlink($tempfile);
2846: }
2847: }
2848: return;
2849: }
2850: }
2851: # Create the directory if not present
2852: my @parts=split(/\//,$filepath);
2853: my $fullpath = $perlvar{'lonDaemons'};
2854: for (my $i=0;$i<@parts;$i++) {
2855: $fullpath .= '/'.$parts[$i];
2856: if ((-e $fullpath)!=1) {
2857: mkdir($fullpath,0777);
2858: }
2859: }
2860: open(my $fh,'>'.$fullpath.'/'.$fname);
2861: print $fh $env{'form.'.$formname};
2862: close($fh);
2863: if ($context eq 'existingfile') {
2864: my @info = stat($fullpath.'/'.$fname);
2865: return ($fullpath.'/'.$fname,$info[9]);
2866: } else {
2867: return $fullpath.'/'.$fname;
2868: }
2869: }
2870: if ($subdir eq 'scantron') {
2871: $fname = 'scantron_orig_'.$fname;
2872: } else {
2873: $fname="$subdir/$fname";
2874: }
2875: if ($context eq 'coursedoc') {
2876: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2877: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2878: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2879: return &finishuserfileupload($docuname,$docudom,
2880: $formname,$fname,$parser,$allfiles,
2881: $codebase,$thumbwidth,$thumbheight,
2882: $resizewidth,$resizeheight,$context,$mimetype);
2883: } else {
2884: $fname=$env{'form.folder'}.'/'.$fname;
2885: return &process_coursefile('uploaddoc',$docuname,$docudom,
2886: $fname,$formname,$parser,
2887: $allfiles,$codebase,$mimetype);
2888: }
2889: } elsif (defined($destuname)) {
2890: my $docuname=$destuname;
2891: my $docudom=$destudom;
2892: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2893: $parser,$allfiles,$codebase,
2894: $thumbwidth,$thumbheight,
2895: $resizewidth,$resizeheight,$context,$mimetype);
2896: } else {
2897: my $docuname=$env{'user.name'};
2898: my $docudom=$env{'user.domain'};
2899: if (exists($env{'form.group'})) {
2900: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2901: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2902: }
2903: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2904: $parser,$allfiles,$codebase,
2905: $thumbwidth,$thumbheight,
2906: $resizewidth,$resizeheight,$context,$mimetype);
2907: }
2908: }
2909:
2910: sub finishuserfileupload {
2911: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2912: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2913: my $path=$docudom.'/'.$docuname.'/';
2914: my $filepath=$perlvar{'lonDocRoot'};
2915:
2916: my ($fnamepath,$file,$fetchthumb);
2917: $file=$fname;
2918: if ($fname=~m|/|) {
2919: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2920: $path.=$fnamepath.'/';
2921: }
2922: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2923: my $count;
2924: for ($count=4;$count<=$#parts;$count++) {
2925: $filepath.="/$parts[$count]";
2926: if ((-e $filepath)!=1) {
2927: mkdir($filepath,0777);
2928: }
2929: }
2930:
2931: # Save the file
2932: {
2933: if (!open(FH,'>'.$filepath.'/'.$file)) {
2934: &logthis('Failed to create '.$filepath.'/'.$file);
2935: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2936: return '/adm/notfound.html';
2937: }
2938: if ($context eq 'overwrite') {
2939: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2940: my $target = $filepath.'/'.$file;
2941: if (-e $source) {
2942: my @info = stat($source);
2943: if ($info[9] eq $env{'form.timestamp'}) {
2944: unless (&File::Copy::move($source,$target)) {
2945: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2946: return "Moving from $source failed";
2947: }
2948: } else {
2949: return "Temporary file: $source had unexpected date/time for last modification";
2950: }
2951: } else {
2952: return "Temporary file: $source missing";
2953: }
2954: } elsif (!print FH ($env{'form.'.$formname})) {
2955: &logthis('Failed to write to '.$filepath.'/'.$file);
2956: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2957: return '/adm/notfound.html';
2958: }
2959: close(FH);
2960: if ($resizewidth && $resizeheight) {
2961: my $mm = new File::MMagic;
2962: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2963: if ($mime_type =~ m{^image/}) {
2964: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2965: }
2966: }
2967: }
2968: if ($parser eq 'parse') {
2969: my $mm = new File::MMagic;
2970: my $type = $mm->checktype_filename($filepath.'/'.$file);
2971: if ($type eq 'text/html') {
2972: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2973: $allfiles,$codebase);
2974: unless ($parse_result eq 'ok') {
2975: &logthis('Failed to parse '.$filepath.$file.
2976: ' for embedded media: '.$parse_result);
2977: }
2978: }
2979: if (ref($mimetype)) {
2980: $$mimetype = $type;
2981: }
2982: }
2983: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2984: my $input = $filepath.'/'.$file;
2985: my $output = $filepath.'/'.'tn-'.$file;
2986: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2987: system("convert -sample $thumbsize $input $output");
2988: if (-e $filepath.'/'.'tn-'.$file) {
2989: $fetchthumb = 1;
2990: }
2991: }
2992:
2993: # Notify homeserver to grep it
2994: #
2995: my $docuhome=&homeserver($docuname,$docudom);
2996: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2997: if ($fetchresult eq 'ok') {
2998: if ($fetchthumb) {
2999: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3000: if ($thumbresult ne 'ok') {
3001: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3002: $docuhome.': '.$thumbresult);
3003: }
3004: }
3005: #
3006: # Return the URL to it
3007: return '/uploaded/'.$path.$file;
3008: } else {
3009: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3010: ': '.$fetchresult);
3011: return '/adm/notfound.html';
3012: }
3013: }
3014:
3015: sub extract_embedded_items {
3016: my ($fullpath,$allfiles,$codebase,$content) = @_;
3017: my @state = ();
3018: my %javafiles = (
3019: codebase => '',
3020: code => '',
3021: archive => ''
3022: );
3023: my %mediafiles = (
3024: src => '',
3025: movie => '',
3026: );
3027: my $p;
3028: if ($content) {
3029: $p = HTML::LCParser->new($content);
3030: } else {
3031: $p = HTML::LCParser->new($fullpath);
3032: }
3033: while (my $t=$p->get_token()) {
3034: if ($t->[0] eq 'S') {
3035: my ($tagname, $attr) = ($t->[1],$t->[2]);
3036: push(@state, $tagname);
3037: if (lc($tagname) eq 'allow') {
3038: &add_filetype($allfiles,$attr->{'src'},'src');
3039: }
3040: if (lc($tagname) eq 'img') {
3041: &add_filetype($allfiles,$attr->{'src'},'src');
3042: }
3043: if (lc($tagname) eq 'a') {
3044: &add_filetype($allfiles,$attr->{'href'},'href');
3045: }
3046: if (lc($tagname) eq 'script') {
3047: if ($attr->{'archive'} =~ /\.jar$/i) {
3048: &add_filetype($allfiles,$attr->{'archive'},'archive');
3049: } else {
3050: &add_filetype($allfiles,$attr->{'src'},'src');
3051: }
3052: }
3053: if (lc($tagname) eq 'link') {
3054: if (lc($attr->{'rel'}) eq 'stylesheet') {
3055: &add_filetype($allfiles,$attr->{'href'},'href');
3056: }
3057: }
3058: if (lc($tagname) eq 'object' ||
3059: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3060: foreach my $item (keys(%javafiles)) {
3061: $javafiles{$item} = '';
3062: }
3063: }
3064: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3065: my $name = lc($attr->{'name'});
3066: foreach my $item (keys(%javafiles)) {
3067: if ($name eq $item) {
3068: $javafiles{$item} = $attr->{'value'};
3069: last;
3070: }
3071: }
3072: foreach my $item (keys(%mediafiles)) {
3073: if ($name eq $item) {
3074: &add_filetype($allfiles, $attr->{'value'}, 'value');
3075: last;
3076: }
3077: }
3078: }
3079: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3080: foreach my $item (keys(%javafiles)) {
3081: if ($attr->{$item}) {
3082: $javafiles{$item} = $attr->{$item};
3083: last;
3084: }
3085: }
3086: foreach my $item (keys(%mediafiles)) {
3087: if ($attr->{$item}) {
3088: &add_filetype($allfiles,$attr->{$item},$item);
3089: last;
3090: }
3091: }
3092: }
3093: } elsif ($t->[0] eq 'E') {
3094: my ($tagname) = ($t->[1]);
3095: if ($javafiles{'codebase'} ne '') {
3096: $javafiles{'codebase'} .= '/';
3097: }
3098: if (lc($tagname) eq 'applet' ||
3099: lc($tagname) eq 'object' ||
3100: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3101: ) {
3102: foreach my $item (keys(%javafiles)) {
3103: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3104: my $file=$javafiles{'codebase'}.$javafiles{$item};
3105: &add_filetype($allfiles,$file,$item);
3106: }
3107: }
3108: }
3109: pop @state;
3110: }
3111: }
3112: return 'ok';
3113: }
3114:
3115: sub add_filetype {
3116: my ($allfiles,$file,$type)=@_;
3117: if (exists($allfiles->{$file})) {
3118: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3119: push(@{$allfiles->{$file}}, &escape($type));
3120: }
3121: } else {
3122: @{$allfiles->{$file}} = (&escape($type));
3123: }
3124: }
3125:
3126: sub removeuploadedurl {
3127: my ($url)=@_;
3128: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3129: return &removeuserfile($uname,$udom,$fname);
3130: }
3131:
3132: sub removeuserfile {
3133: my ($docuname,$docudom,$fname)=@_;
3134: my $home=&homeserver($docuname,$docudom);
3135: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3136: if ($result eq 'ok') {
3137: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3138: my $metafile = $fname.'.meta';
3139: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3140: my $url = "/uploaded/$docudom/$docuname/$fname";
3141: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3142: my $sqlresult =
3143: &update_portfolio_table($docuname,$docudom,$file,
3144: 'portfolio_metadata',$group,
3145: 'delete');
3146: }
3147: }
3148: return $result;
3149: }
3150:
3151: sub mkdiruserfile {
3152: my ($docuname,$docudom,$dir)=@_;
3153: my $home=&homeserver($docuname,$docudom);
3154: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3155: }
3156:
3157: sub renameuserfile {
3158: my ($docuname,$docudom,$old,$new)=@_;
3159: my $home=&homeserver($docuname,$docudom);
3160: my $result = &reply("renameuserfile:$docudom:$docuname:".
3161: &escape("$old").':'.&escape("$new"),$home);
3162: if ($result eq 'ok') {
3163: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3164: my $oldmeta = $old.'.meta';
3165: my $newmeta = $new.'.meta';
3166: my $metaresult =
3167: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3168: my $url = "/uploaded/$docudom/$docuname/$old";
3169: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3170: my $sqlresult =
3171: &update_portfolio_table($docuname,$docudom,$file,
3172: 'portfolio_metadata',$group,
3173: 'delete');
3174: }
3175: }
3176: return $result;
3177: }
3178:
3179: # ------------------------------------------------------------------------- Log
3180:
3181: sub log {
3182: my ($dom,$nam,$hom,$what)=@_;
3183: return critical("log:$dom:$nam:$what",$hom);
3184: }
3185:
3186: # ------------------------------------------------------------------ Course Log
3187: #
3188: # This routine flushes several buffers of non-mission-critical nature
3189: #
3190:
3191: sub flushcourselogs {
3192: &logthis('Flushing log buffers');
3193: #
3194: # course logs
3195: # This is a log of all transactions in a course, which can be used
3196: # for data mining purposes
3197: #
3198: # It also collects the courseid database, which lists last transaction
3199: # times and course titles for all courseids
3200: #
3201: my %courseidbuffer=();
3202: foreach my $crsid (keys(%courselogs)) {
3203: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3204: &escape($courselogs{$crsid}),
3205: $coursehombuf{$crsid}) eq 'ok') {
3206: delete $courselogs{$crsid};
3207: } else {
3208: &logthis('Failed to flush log buffer for '.$crsid);
3209: if (length($courselogs{$crsid})>40000) {
3210: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3211: " exceeded maximum size, deleting.</font>");
3212: delete $courselogs{$crsid};
3213: }
3214: }
3215: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3216: 'description' => $coursedescrbuf{$crsid},
3217: 'inst_code' => $courseinstcodebuf{$crsid},
3218: 'type' => $coursetypebuf{$crsid},
3219: 'owner' => $courseownerbuf{$crsid},
3220: };
3221: }
3222: #
3223: # Write course id database (reverse lookup) to homeserver of courses
3224: # Is used in pickcourse
3225: #
3226: foreach my $crs_home (keys(%courseidbuffer)) {
3227: my $response = &courseidput(&host_domain($crs_home),
3228: $courseidbuffer{$crs_home},
3229: $crs_home,'timeonly');
3230: }
3231: #
3232: # File accesses
3233: # Writes to the dynamic metadata of resources to get hit counts, etc.
3234: #
3235: foreach my $entry (keys(%accesshash)) {
3236: if ($entry =~ /___count$/) {
3237: my ($dom,$name);
3238: ($dom,$name,undef)=
3239: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3240: if (! defined($dom) || $dom eq '' ||
3241: ! defined($name) || $name eq '') {
3242: my $cid = $env{'request.course.id'};
3243: $dom = $env{'request.'.$cid.'.domain'};
3244: $name = $env{'request.'.$cid.'.num'};
3245: }
3246: my $value = $accesshash{$entry};
3247: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3248: my %temphash=($url => $value);
3249: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3250: if ($result eq 'ok') {
3251: delete $accesshash{$entry};
3252: } elsif ($result eq 'unknown_cmd') {
3253: # Target server has old code running on it.
3254: my %temphash=($entry => $value);
3255: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3256: delete $accesshash{$entry};
3257: }
3258: }
3259: } else {
3260: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3261: my %temphash=($entry => $accesshash{$entry});
3262: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3263: delete $accesshash{$entry};
3264: }
3265: }
3266: }
3267: #
3268: # Roles
3269: # Reverse lookup of user roles for course faculty/staff and co-authorship
3270: #
3271: foreach my $entry (keys(%userrolehash)) {
3272: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3273: split(/\:/,$entry);
3274: if (&Apache::lonnet::put('nohist_userroles',
3275: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3276: $rudom,$runame) eq 'ok') {
3277: delete $userrolehash{$entry};
3278: }
3279: }
3280: #
3281: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3282: #
3283: my %domrolebuffer = ();
3284: foreach my $entry (keys(%domainrolehash)) {
3285: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3286: if ($domrolebuffer{$rudom}) {
3287: $domrolebuffer{$rudom}.='&'.&escape($entry).
3288: '='.&escape($domainrolehash{$entry});
3289: } else {
3290: $domrolebuffer{$rudom}.=&escape($entry).
3291: '='.&escape($domainrolehash{$entry});
3292: }
3293: delete $domainrolehash{$entry};
3294: }
3295: foreach my $dom (keys(%domrolebuffer)) {
3296: my %servers = &get_servers($dom,'library');
3297: foreach my $tryserver (keys(%servers)) {
3298: unless (&reply('domroleput:'.$dom.':'.
3299: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3300: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3301: }
3302: }
3303: }
3304: $dumpcount++;
3305: }
3306:
3307: sub courselog {
3308: my $what=shift;
3309: $what=time.':'.$what;
3310: unless ($env{'request.course.id'}) { return ''; }
3311: $coursedombuf{$env{'request.course.id'}}=
3312: $env{'course.'.$env{'request.course.id'}.'.domain'};
3313: $coursenumbuf{$env{'request.course.id'}}=
3314: $env{'course.'.$env{'request.course.id'}.'.num'};
3315: $coursehombuf{$env{'request.course.id'}}=
3316: $env{'course.'.$env{'request.course.id'}.'.home'};
3317: $coursedescrbuf{$env{'request.course.id'}}=
3318: $env{'course.'.$env{'request.course.id'}.'.description'};
3319: $courseinstcodebuf{$env{'request.course.id'}}=
3320: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3321: $courseownerbuf{$env{'request.course.id'}}=
3322: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3323: $coursetypebuf{$env{'request.course.id'}}=
3324: $env{'course.'.$env{'request.course.id'}.'.type'};
3325: if (defined $courselogs{$env{'request.course.id'}}) {
3326: $courselogs{$env{'request.course.id'}}.='&'.$what;
3327: } else {
3328: $courselogs{$env{'request.course.id'}}.=$what;
3329: }
3330: if (length($courselogs{$env{'request.course.id'}})>4048) {
3331: &flushcourselogs();
3332: }
3333: }
3334:
3335: sub courseacclog {
3336: my $fnsymb=shift;
3337: unless ($env{'request.course.id'}) { return ''; }
3338: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3339: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
3340: $what.=':POST';
3341: # FIXME: Probably ought to escape things....
3342: foreach my $key (keys(%env)) {
3343: if ($key=~/^form\.(.*)/) {
3344: my $formitem = $1;
3345: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3346: $what.=':'.$formitem.'='.$env{$key};
3347: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3348: $what.=':'.$formitem.'='.$env{$key};
3349: }
3350: }
3351: }
3352: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3353: # FIXME: We should not be depending on a form parameter that someone
3354: # editing lonsearchcat.pm might change in the future.
3355: if ($env{'form.phase'} eq 'course_search') {
3356: $what.= ':POST';
3357: # FIXME: Probably ought to escape things....
3358: foreach my $element ('courseexp','crsfulltext','crsrelated',
3359: 'crsdiscuss') {
3360: $what.=':'.$element.'='.$env{'form.'.$element};
3361: }
3362: }
3363: }
3364: &courselog($what);
3365: }
3366:
3367: sub countacc {
3368: my $url=&declutter(shift);
3369: return if (! defined($url) || $url eq '');
3370: unless ($env{'request.course.id'}) { return ''; }
3371: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3372: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3373: $accesshash{$key}++;
3374: }
3375:
3376: sub linklog {
3377: my ($from,$to)=@_;
3378: $from=&declutter($from);
3379: $to=&declutter($to);
3380: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3381: $accesshash{$to.'___'.$from.'___goto'}=1;
3382: }
3383:
3384: sub userrolelog {
3385: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3386: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3387: ($trole=~/^in/) || ($trole=~/^cc/) ||
3388: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3389: ($trole=~/^ta/) || ($trole=~/^co/)) {
3390: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3391: $userrolehash
3392: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3393: =$tend.':'.$tstart;
3394: }
3395: if (($env{'request.role'} =~ /dc\./) &&
3396: (($trole=~/^au/) || ($trole=~/^in/) ||
3397: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3398: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3399: ($trole=~/^co/))) {
3400: $userrolehash
3401: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3402: =$tend.':'.$tstart;
3403: }
3404: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3405: ($trole=~/^li/) || ($trole=~/^li/) ||
3406: ($trole=~/^au/) || ($trole=~/^dg/) ||
3407: ($trole=~/^sc/)) {
3408: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3409: $domainrolehash
3410: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3411: = $tend.':'.$tstart;
3412: }
3413: }
3414:
3415: sub courserolelog {
3416: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3417: if (($trole eq 'cc') || ($trole eq 'in') ||
3418: ($trole eq 'ep') || ($trole eq 'ad') ||
3419: ($trole eq 'ta') || ($trole eq 'st') ||
3420: ($trole=~/^cr/) || ($trole eq 'gr') ||
3421: ($trole eq 'co')) {
3422: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3423: my $cdom = $1;
3424: my $cnum = $2;
3425: my $sec = $3;
3426: my $namespace = 'rolelog';
3427: my %storehash = (
3428: role => $trole,
3429: start => $tstart,
3430: end => $tend,
3431: selfenroll => $selfenroll,
3432: context => $context,
3433: );
3434: if ($trole eq 'gr') {
3435: $namespace = 'groupslog';
3436: $storehash{'group'} = $sec;
3437: } else {
3438: $storehash{'section'} = $sec;
3439: }
3440: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3441: if (($trole ne 'st') || ($sec ne '')) {
3442: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3443: }
3444: }
3445: }
3446: return;
3447: }
3448:
3449: sub get_course_adv_roles {
3450: my ($cid,$codes) = @_;
3451: $cid=$env{'request.course.id'} unless (defined($cid));
3452: my %coursehash=&coursedescription($cid);
3453: my $crstype = &Apache::loncommon::course_type($cid);
3454: my %nothide=();
3455: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3456: if ($user !~ /:/) {
3457: $nothide{join(':',split(/[\@]/,$user))}=1;
3458: } else {
3459: $nothide{$user}=1;
3460: }
3461: }
3462: my %returnhash=();
3463: my %dumphash=
3464: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3465: my $now=time;
3466: my %privileged;
3467: foreach my $entry (keys(%dumphash)) {
3468: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3469: if (($tstart) && ($tstart<0)) { next; }
3470: if (($tend) && ($tend<$now)) { next; }
3471: if (($tstart) && ($now<$tstart)) { next; }
3472: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3473: if ($username eq '' || $domain eq '') { next; }
3474: unless (ref($privileged{$domain}) eq 'HASH') {
3475: my %dompersonnel =
3476: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3477: $privileged{$domain} = {};
3478: foreach my $server (keys(%dompersonnel)) {
3479: if (ref($dompersonnel{$server}) eq 'HASH') {
3480: foreach my $user (keys(%{$dompersonnel{$server}})) {
3481: my ($trole,$uname,$udom) = split(/:/,$user);
3482: $privileged{$udom}{$uname} = 1;
3483: }
3484: }
3485: }
3486: }
3487: if ((exists($privileged{$domain}{$username})) &&
3488: (!$nothide{$username.':'.$domain})) { next; }
3489: if ($role eq 'cr') { next; }
3490: if ($codes) {
3491: if ($section) { $role .= ':'.$section; }
3492: if ($returnhash{$role}) {
3493: $returnhash{$role}.=','.$username.':'.$domain;
3494: } else {
3495: $returnhash{$role}=$username.':'.$domain;
3496: }
3497: } else {
3498: my $key=&plaintext($role,$crstype);
3499: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3500: if ($returnhash{$key}) {
3501: $returnhash{$key}.=','.$username.':'.$domain;
3502: } else {
3503: $returnhash{$key}=$username.':'.$domain;
3504: }
3505: }
3506: }
3507: return %returnhash;
3508: }
3509:
3510: sub get_my_roles {
3511: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3512: unless (defined($uname)) { $uname=$env{'user.name'}; }
3513: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3514: my (%dumphash,%nothide);
3515: if ($context eq 'userroles') {
3516: my $extra = &freeze_escape({'skipcheck' => 1});
3517: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
3518: } else {
3519: %dumphash=
3520: &dump('nohist_userroles',$udom,$uname);
3521: if ($hidepriv) {
3522: my %coursehash=&coursedescription($udom.'_'.$uname);
3523: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3524: if ($user !~ /:/) {
3525: $nothide{join(':',split(/[\@]/,$user))} = 1;
3526: } else {
3527: $nothide{$user} = 1;
3528: }
3529: }
3530: }
3531: }
3532: my %returnhash=();
3533: my $now=time;
3534: my %privileged;
3535: foreach my $entry (keys(%dumphash)) {
3536: my ($role,$tend,$tstart);
3537: if ($context eq 'userroles') {
3538: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3539: } else {
3540: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3541: }
3542: if (($tstart) && ($tstart<0)) { next; }
3543: my $status = 'active';
3544: if (($tend) && ($tend<=$now)) {
3545: $status = 'previous';
3546: }
3547: if (($tstart) && ($now<$tstart)) {
3548: $status = 'future';
3549: }
3550: if (ref($types) eq 'ARRAY') {
3551: if (!grep(/^\Q$status\E$/,@{$types})) {
3552: next;
3553: }
3554: } else {
3555: if ($status ne 'active') {
3556: next;
3557: }
3558: }
3559: my ($rolecode,$username,$domain,$section,$area);
3560: if ($context eq 'userroles') {
3561: ($area,$rolecode) = split(/_/,$entry);
3562: (undef,$domain,$username,$section) = split(/\//,$area);
3563: } else {
3564: ($role,$username,$domain,$section) = split(/\:/,$entry);
3565: }
3566: if (ref($roledoms) eq 'ARRAY') {
3567: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3568: next;
3569: }
3570: }
3571: if (ref($roles) eq 'ARRAY') {
3572: if (!grep(/^\Q$role\E$/,@{$roles})) {
3573: if ($role =~ /^cr\//) {
3574: if (!grep(/^cr$/,@{$roles})) {
3575: next;
3576: }
3577: } elsif ($role =~ /^gr\//) {
3578: if (!grep(/^gr$/,@{$roles})) {
3579: next;
3580: }
3581: } else {
3582: next;
3583: }
3584: }
3585: }
3586: if ($hidepriv) {
3587: if ($context eq 'userroles') {
3588: if ((&privileged($username,$domain)) &&
3589: (!$nothide{$username.':'.$domain})) {
3590: next;
3591: }
3592: } else {
3593: unless (ref($privileged{$domain}) eq 'HASH') {
3594: my %dompersonnel =
3595: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3596: $privileged{$domain} = {};
3597: if (keys(%dompersonnel)) {
3598: foreach my $server (keys(%dompersonnel)) {
3599: if (ref($dompersonnel{$server}) eq 'HASH') {
3600: foreach my $user (keys(%{$dompersonnel{$server}})) {
3601: my ($trole,$uname,$udom) = split(/:/,$user);
3602: $privileged{$udom}{$uname} = $trole;
3603: }
3604: }
3605: }
3606: }
3607: }
3608: if (exists($privileged{$domain}{$username})) {
3609: if (!$nothide{$username.':'.$domain}) {
3610: next;
3611: }
3612: }
3613: }
3614: }
3615: if ($withsec) {
3616: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3617: $tstart.':'.$tend;
3618: } else {
3619: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3620: }
3621: }
3622: return %returnhash;
3623: }
3624:
3625: # ----------------------------------------------------- Frontpage Announcements
3626: #
3627: #
3628:
3629: sub postannounce {
3630: my ($server,$text)=@_;
3631: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3632: unless ($text=~/\w/) { $text=''; }
3633: return &reply('setannounce:'.&escape($text),$server);
3634: }
3635:
3636: sub getannounce {
3637:
3638: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3639: my $announcement='';
3640: while (my $line = <$fh>) { $announcement .= $line; }
3641: close($fh);
3642: if ($announcement=~/\w/) {
3643: return
3644: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3645: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3646: } else {
3647: return '';
3648: }
3649: } else {
3650: return '';
3651: }
3652: }
3653:
3654: # ---------------------------------------------------------- Course ID routines
3655: # Deal with domain's nohist_courseid.db files
3656: #
3657:
3658: sub courseidput {
3659: my ($domain,$storehash,$coursehome,$caller) = @_;
3660: return unless (ref($storehash) eq 'HASH');
3661: my $outcome;
3662: if ($caller eq 'timeonly') {
3663: my $cids = '';
3664: foreach my $item (keys(%$storehash)) {
3665: $cids.=&escape($item).'&';
3666: }
3667: $cids=~s/\&$//;
3668: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3669: $coursehome);
3670: } else {
3671: my $items = '';
3672: foreach my $item (keys(%$storehash)) {
3673: $items.= &escape($item).'='.
3674: &freeze_escape($$storehash{$item}).'&';
3675: }
3676: $items=~s/\&$//;
3677: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3678: $coursehome);
3679: }
3680: if ($outcome eq 'unknown_cmd') {
3681: my $what;
3682: foreach my $cid (keys(%$storehash)) {
3683: $what .= &escape($cid).'=';
3684: foreach my $item ('description','inst_code','owner','type') {
3685: $what .= &escape($storehash->{$cid}{$item}).':';
3686: }
3687: $what =~ s/\:$/&/;
3688: }
3689: $what =~ s/\&$//;
3690: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3691: } else {
3692: return $outcome;
3693: }
3694: }
3695:
3696: sub courseiddump {
3697: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3698: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3699: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3700: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3701: my $as_hash = 1;
3702: my %returnhash;
3703: if (!$domfilter) { $domfilter=''; }
3704: my %libserv = &all_library();
3705: foreach my $tryserver (keys(%libserv)) {
3706: if ( ( $hostidflag == 1
3707: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3708: || (!defined($hostidflag)) ) {
3709:
3710: if (($domfilter eq '') ||
3711: (&host_domain($tryserver) eq $domfilter)) {
3712: my $rep =
3713: &reply('courseiddump:'.&host_domain($tryserver).':'.
3714: $sincefilter.':'.&escape($descfilter).':'.
3715: &escape($instcodefilter).':'.&escape($ownerfilter).
3716: ':'.&escape($coursefilter).':'.&escape($typefilter).
3717: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3718: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3719: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3720: &escape($cc_clone).':'.$cloneonly.':'.
3721: &escape($createdbefore).':'.&escape($createdafter).':'.
3722: &escape($creationcontext).':'.$domcloner,
3723: $tryserver);
3724: my @pairs=split(/\&/,$rep);
3725: foreach my $item (@pairs) {
3726: my ($key,$value)=split(/\=/,$item,2);
3727: $key = &unescape($key);
3728: next if ($key =~ /^error: 2 /);
3729: my $result = &thaw_unescape($value);
3730: if (ref($result) eq 'HASH') {
3731: $returnhash{$key}=$result;
3732: } else {
3733: my @responses = split(/:/,$value);
3734: my @items = ('description','inst_code','owner','type');
3735: for (my $i=0; $i<@responses; $i++) {
3736: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3737: }
3738: }
3739: }
3740: }
3741: }
3742: }
3743: return %returnhash;
3744: }
3745:
3746: sub courselastaccess {
3747: my ($cdom,$cnum,$hostidref) = @_;
3748: my %returnhash;
3749: if ($cdom && $cnum) {
3750: my $chome = &homeserver($cnum,$cdom);
3751: if ($chome ne 'no_host') {
3752: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3753: &extract_lastaccess(\%returnhash,$rep);
3754: }
3755: } else {
3756: if (!$cdom) { $cdom=''; }
3757: my %libserv = &all_library();
3758: foreach my $tryserver (keys(%libserv)) {
3759: if (ref($hostidref) eq 'ARRAY') {
3760: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3761: }
3762: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3763: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3764: &extract_lastaccess(\%returnhash,$rep);
3765: }
3766: }
3767: }
3768: return %returnhash;
3769: }
3770:
3771: sub extract_lastaccess {
3772: my ($returnhash,$rep) = @_;
3773: if (ref($returnhash) eq 'HASH') {
3774: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3775: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3776: $rep eq '') {
3777: my @pairs=split(/\&/,$rep);
3778: foreach my $item (@pairs) {
3779: my ($key,$value)=split(/\=/,$item,2);
3780: $key = &unescape($key);
3781: next if ($key =~ /^error: 2 /);
3782: $returnhash->{$key} = &thaw_unescape($value);
3783: }
3784: }
3785: }
3786: return;
3787: }
3788:
3789: # ---------------------------------------------------------- DC e-mail
3790:
3791: sub dcmailput {
3792: my ($domain,$msgid,$message,$server)=@_;
3793: my $status = &Apache::lonnet::critical(
3794: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3795: &escape($message),$server);
3796: return $status;
3797: }
3798:
3799: sub dcmaildump {
3800: my ($dom,$startdate,$enddate,$senders) = @_;
3801: my %returnhash=();
3802:
3803: if (defined(&domain($dom,'primary'))) {
3804: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3805: &escape($enddate).':';
3806: my @esc_senders=map { &escape($_)} @$senders;
3807: $cmd.=&escape(join('&',@esc_senders));
3808: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3809: my ($key,$value) = split(/\=/,$line,2);
3810: if (($key) && ($value)) {
3811: $returnhash{&unescape($key)} = &unescape($value);
3812: }
3813: }
3814: }
3815: return %returnhash;
3816: }
3817: # ---------------------------------------------------------- Domain roles
3818:
3819: sub get_domain_roles {
3820: my ($dom,$roles,$startdate,$enddate)=@_;
3821: if ((!defined($startdate)) || ($startdate eq '')) {
3822: $startdate = '.';
3823: }
3824: if ((!defined($enddate)) || ($enddate eq '')) {
3825: $enddate = '.';
3826: }
3827: my $rolelist;
3828: if (ref($roles) eq 'ARRAY') {
3829: $rolelist = join(':',@{$roles});
3830: }
3831: my %personnel = ();
3832:
3833: my %servers = &get_servers($dom,'library');
3834: foreach my $tryserver (keys(%servers)) {
3835: %{$personnel{$tryserver}}=();
3836: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3837: &escape($startdate).':'.
3838: &escape($enddate).':'.
3839: &escape($rolelist), $tryserver))) {
3840: my ($key,$value) = split(/\=/,$line,2);
3841: if (($key) && ($value)) {
3842: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3843: }
3844: }
3845: }
3846: return %personnel;
3847: }
3848:
3849: # ----------------------------------------------------------- Interval timing
3850:
3851: sub get_first_access {
3852: my ($type,$argsymb)=@_;
3853: my ($symb,$courseid,$udom,$uname)=&whichuser();
3854: if ($argsymb) { $symb=$argsymb; }
3855: my ($map,$id,$res)=&decode_symb($symb);
3856: if ($type eq 'course') {
3857: $res='course';
3858: } elsif ($type eq 'map') {
3859: $res=&symbread($map);
3860: } else {
3861: $res=$symb;
3862: }
3863: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3864: return $times{"$courseid\0$res"};
3865: }
3866:
3867: sub set_first_access {
3868: my ($type)=@_;
3869: my ($symb,$courseid,$udom,$uname)=&whichuser();
3870: my ($map,$id,$res)=&decode_symb($symb);
3871: if ($type eq 'course') {
3872: $res='course';
3873: } elsif ($type eq 'map') {
3874: $res=&symbread($map);
3875: } else {
3876: $res=$symb;
3877: }
3878: my $firstaccess=&get_first_access($type,$symb);
3879: if (!$firstaccess) {
3880: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3881: }
3882: return 'already_set';
3883: }
3884:
3885: # --------------------------------------------- Set Expire Date for Spreadsheet
3886:
3887: sub expirespread {
3888: my ($uname,$udom,$stype,$usymb)=@_;
3889: my $cid=$env{'request.course.id'};
3890: if ($cid) {
3891: my $now=time;
3892: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3893: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3894: $env{'course.'.$cid.'.num'}.
3895: ':nohist_expirationdates:'.
3896: &escape($key).'='.$now,
3897: $env{'course.'.$cid.'.home'})
3898: }
3899: return 'ok';
3900: }
3901:
3902: # ----------------------------------------------------- Devalidate Spreadsheets
3903:
3904: sub devalidate {
3905: my ($symb,$uname,$udom)=@_;
3906: my $cid=$env{'request.course.id'};
3907: if ($cid) {
3908: # delete the stored spreadsheets for
3909: # - the student level sheet of this user in course's homespace
3910: # - the assessment level sheet for this resource
3911: # for this user in user's homespace
3912: # - current conditional state info
3913: my $key=$uname.':'.$udom.':';
3914: my $status=
3915: &del('nohist_calculatedsheets',
3916: [$key.'studentcalc:'],
3917: $env{'course.'.$cid.'.domain'},
3918: $env{'course.'.$cid.'.num'})
3919: .' '.
3920: &del('nohist_calculatedsheets_'.$cid,
3921: [$key.'assesscalc:'.$symb],$udom,$uname);
3922: unless ($status eq 'ok ok') {
3923: &logthis('Could not devalidate spreadsheet '.
3924: $uname.' at '.$udom.' for '.
3925: $symb.': '.$status);
3926: }
3927: &delenv('user.state.'.$cid);
3928: }
3929: }
3930:
3931: sub get_scalar {
3932: my ($string,$end) = @_;
3933: my $value;
3934: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3935: $value = $1;
3936: } elsif ($$string =~ s/^([^&]*?)&//) {
3937: $value = $1;
3938: }
3939: return &unescape($value);
3940: }
3941:
3942: sub array2str {
3943: my (@array) = @_;
3944: my $result=&arrayref2str(\@array);
3945: $result=~s/^__ARRAY_REF__//;
3946: $result=~s/__END_ARRAY_REF__$//;
3947: return $result;
3948: }
3949:
3950: sub arrayref2str {
3951: my ($arrayref) = @_;
3952: my $result='__ARRAY_REF__';
3953: foreach my $elem (@$arrayref) {
3954: if(ref($elem) eq 'ARRAY') {
3955: $result.=&arrayref2str($elem).'&';
3956: } elsif(ref($elem) eq 'HASH') {
3957: $result.=&hashref2str($elem).'&';
3958: } elsif(ref($elem)) {
3959: #print("Got a ref of ".(ref($elem))." skipping.");
3960: } else {
3961: $result.=&escape($elem).'&';
3962: }
3963: }
3964: $result=~s/\&$//;
3965: $result .= '__END_ARRAY_REF__';
3966: return $result;
3967: }
3968:
3969: sub hash2str {
3970: my (%hash) = @_;
3971: my $result=&hashref2str(\%hash);
3972: $result=~s/^__HASH_REF__//;
3973: $result=~s/__END_HASH_REF__$//;
3974: return $result;
3975: }
3976:
3977: sub hashref2str {
3978: my ($hashref)=@_;
3979: my $result='__HASH_REF__';
3980: foreach my $key (sort(keys(%$hashref))) {
3981: if (ref($key) eq 'ARRAY') {
3982: $result.=&arrayref2str($key).'=';
3983: } elsif (ref($key) eq 'HASH') {
3984: $result.=&hashref2str($key).'=';
3985: } elsif (ref($key)) {
3986: $result.='=';
3987: #print("Got a ref of ".(ref($key))." skipping.");
3988: } else {
3989: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
3990: }
3991:
3992: if(ref($hashref->{$key}) eq 'ARRAY') {
3993: $result.=&arrayref2str($hashref->{$key}).'&';
3994: } elsif(ref($hashref->{$key}) eq 'HASH') {
3995: $result.=&hashref2str($hashref->{$key}).'&';
3996: } elsif(ref($hashref->{$key})) {
3997: $result.='&';
3998: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3999: } else {
4000: $result.=&escape($hashref->{$key}).'&';
4001: }
4002: }
4003: $result=~s/\&$//;
4004: $result .= '__END_HASH_REF__';
4005: return $result;
4006: }
4007:
4008: sub str2hash {
4009: my ($string)=@_;
4010: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4011: return %$hash;
4012: }
4013:
4014: sub str2hashref {
4015: my ($string) = @_;
4016:
4017: my %hash;
4018:
4019: if($string !~ /^__HASH_REF__/) {
4020: if (! ($string eq '' || !defined($string))) {
4021: $hash{'error'}='Not hash reference';
4022: }
4023: return (\%hash, $string);
4024: }
4025:
4026: $string =~ s/^__HASH_REF__//;
4027:
4028: while($string !~ /^__END_HASH_REF__/) {
4029: #key
4030: my $key='';
4031: if($string =~ /^__HASH_REF__/) {
4032: ($key, $string)=&str2hashref($string);
4033: if(defined($key->{'error'})) {
4034: $hash{'error'}='Bad data';
4035: return (\%hash, $string);
4036: }
4037: } elsif($string =~ /^__ARRAY_REF__/) {
4038: ($key, $string)=&str2arrayref($string);
4039: if($key->[0] eq 'Array reference error') {
4040: $hash{'error'}='Bad data';
4041: return (\%hash, $string);
4042: }
4043: } else {
4044: $string =~ s/^(.*?)=//;
4045: $key=&unescape($1);
4046: }
4047: $string =~ s/^=//;
4048:
4049: #value
4050: my $value='';
4051: if($string =~ /^__HASH_REF__/) {
4052: ($value, $string)=&str2hashref($string);
4053: if(defined($value->{'error'})) {
4054: $hash{'error'}='Bad data';
4055: return (\%hash, $string);
4056: }
4057: } elsif($string =~ /^__ARRAY_REF__/) {
4058: ($value, $string)=&str2arrayref($string);
4059: if($value->[0] eq 'Array reference error') {
4060: $hash{'error'}='Bad data';
4061: return (\%hash, $string);
4062: }
4063: } else {
4064: $value=&get_scalar(\$string,'__END_HASH_REF__');
4065: }
4066: $string =~ s/^&//;
4067:
4068: $hash{$key}=$value;
4069: }
4070:
4071: $string =~ s/^__END_HASH_REF__//;
4072:
4073: return (\%hash, $string);
4074: }
4075:
4076: sub str2array {
4077: my ($string)=@_;
4078: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4079: return @$array;
4080: }
4081:
4082: sub str2arrayref {
4083: my ($string) = @_;
4084: my @array;
4085:
4086: if($string !~ /^__ARRAY_REF__/) {
4087: if (! ($string eq '' || !defined($string))) {
4088: $array[0]='Array reference error';
4089: }
4090: return (\@array, $string);
4091: }
4092:
4093: $string =~ s/^__ARRAY_REF__//;
4094:
4095: while($string !~ /^__END_ARRAY_REF__/) {
4096: my $value='';
4097: if($string =~ /^__HASH_REF__/) {
4098: ($value, $string)=&str2hashref($string);
4099: if(defined($value->{'error'})) {
4100: $array[0] ='Array reference error';
4101: return (\@array, $string);
4102: }
4103: } elsif($string =~ /^__ARRAY_REF__/) {
4104: ($value, $string)=&str2arrayref($string);
4105: if($value->[0] eq 'Array reference error') {
4106: $array[0] ='Array reference error';
4107: return (\@array, $string);
4108: }
4109: } else {
4110: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4111: }
4112: $string =~ s/^&//;
4113:
4114: push(@array, $value);
4115: }
4116:
4117: $string =~ s/^__END_ARRAY_REF__//;
4118:
4119: return (\@array, $string);
4120: }
4121:
4122: # -------------------------------------------------------------------Temp Store
4123:
4124: sub tmpreset {
4125: my ($symb,$namespace,$domain,$stuname) = @_;
4126: if (!$symb) {
4127: $symb=&symbread();
4128: if (!$symb) { $symb= $env{'request.url'}; }
4129: }
4130: $symb=escape($symb);
4131:
4132: if (!$namespace) { $namespace=$env{'request.state'}; }
4133: $namespace=~s/\//\_/g;
4134: $namespace=~s/\W//g;
4135:
4136: if (!$domain) { $domain=$env{'user.domain'}; }
4137: if (!$stuname) { $stuname=$env{'user.name'}; }
4138: if ($domain eq 'public' && $stuname eq 'public') {
4139: $stuname=$ENV{'REMOTE_ADDR'};
4140: }
4141: my $path=LONCAPA::tempdir();
4142: my %hash;
4143: if (tie(%hash,'GDBM_File',
4144: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4145: &GDBM_WRCREAT(),0640)) {
4146: foreach my $key (keys(%hash)) {
4147: if ($key=~ /:$symb/) {
4148: delete($hash{$key});
4149: }
4150: }
4151: }
4152: }
4153:
4154: sub tmpstore {
4155: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4156:
4157: if (!$symb) {
4158: $symb=&symbread();
4159: if (!$symb) { $symb= $env{'request.url'}; }
4160: }
4161: $symb=escape($symb);
4162:
4163: if (!$namespace) {
4164: # I don't think we would ever want to store this for a course.
4165: # it seems this will only be used if we don't have a course.
4166: #$namespace=$env{'request.course.id'};
4167: #if (!$namespace) {
4168: $namespace=$env{'request.state'};
4169: #}
4170: }
4171: $namespace=~s/\//\_/g;
4172: $namespace=~s/\W//g;
4173: if (!$domain) { $domain=$env{'user.domain'}; }
4174: if (!$stuname) { $stuname=$env{'user.name'}; }
4175: if ($domain eq 'public' && $stuname eq 'public') {
4176: $stuname=$ENV{'REMOTE_ADDR'};
4177: }
4178: my $now=time;
4179: my %hash;
4180: my $path=LONCAPA::tempdir();
4181: if (tie(%hash,'GDBM_File',
4182: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4183: &GDBM_WRCREAT(),0640)) {
4184: $hash{"version:$symb"}++;
4185: my $version=$hash{"version:$symb"};
4186: my $allkeys='';
4187: foreach my $key (keys(%$storehash)) {
4188: $allkeys.=$key.':';
4189: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4190: }
4191: $hash{"$version:$symb:timestamp"}=$now;
4192: $allkeys.='timestamp';
4193: $hash{"$version:keys:$symb"}=$allkeys;
4194: if (untie(%hash)) {
4195: return 'ok';
4196: } else {
4197: return "error:$!";
4198: }
4199: } else {
4200: return "error:$!";
4201: }
4202: }
4203:
4204: # -----------------------------------------------------------------Temp Restore
4205:
4206: sub tmprestore {
4207: my ($symb,$namespace,$domain,$stuname) = @_;
4208:
4209: if (!$symb) {
4210: $symb=&symbread();
4211: if (!$symb) { $symb= $env{'request.url'}; }
4212: }
4213: $symb=escape($symb);
4214:
4215: if (!$namespace) { $namespace=$env{'request.state'}; }
4216:
4217: if (!$domain) { $domain=$env{'user.domain'}; }
4218: if (!$stuname) { $stuname=$env{'user.name'}; }
4219: if ($domain eq 'public' && $stuname eq 'public') {
4220: $stuname=$ENV{'REMOTE_ADDR'};
4221: }
4222: my %returnhash;
4223: $namespace=~s/\//\_/g;
4224: $namespace=~s/\W//g;
4225: my %hash;
4226: my $path=LONCAPA::tempdir();
4227: if (tie(%hash,'GDBM_File',
4228: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4229: &GDBM_READER(),0640)) {
4230: my $version=$hash{"version:$symb"};
4231: $returnhash{'version'}=$version;
4232: my $scope;
4233: for ($scope=1;$scope<=$version;$scope++) {
4234: my $vkeys=$hash{"$scope:keys:$symb"};
4235: my @keys=split(/:/,$vkeys);
4236: my $key;
4237: $returnhash{"$scope:keys"}=$vkeys;
4238: foreach $key (@keys) {
4239: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4240: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4241: }
4242: }
4243: if (!(untie(%hash))) {
4244: return "error:$!";
4245: }
4246: } else {
4247: return "error:$!";
4248: }
4249: return %returnhash;
4250: }
4251:
4252: # ----------------------------------------------------------------------- Store
4253:
4254: sub store {
4255: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4256: my $home='';
4257:
4258: if ($stuname) { $home=&homeserver($stuname,$domain); }
4259:
4260: $symb=&symbclean($symb);
4261: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4262:
4263: if (!$domain) { $domain=$env{'user.domain'}; }
4264: if (!$stuname) { $stuname=$env{'user.name'}; }
4265:
4266: &devalidate($symb,$stuname,$domain);
4267:
4268: $symb=escape($symb);
4269: if (!$namespace) {
4270: unless ($namespace=$env{'request.course.id'}) {
4271: return '';
4272: }
4273: }
4274: if (!$home) { $home=$env{'user.home'}; }
4275:
4276: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4277: $$storehash{'host'}=$perlvar{'lonHostID'};
4278:
4279: my $namevalue='';
4280: foreach my $key (keys(%$storehash)) {
4281: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4282: }
4283: $namevalue=~s/\&$//;
4284: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4285: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4286: }
4287:
4288: # -------------------------------------------------------------- Critical Store
4289:
4290: sub cstore {
4291: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4292: my $home='';
4293:
4294: if ($stuname) { $home=&homeserver($stuname,$domain); }
4295:
4296: $symb=&symbclean($symb);
4297: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4298:
4299: if (!$domain) { $domain=$env{'user.domain'}; }
4300: if (!$stuname) { $stuname=$env{'user.name'}; }
4301:
4302: &devalidate($symb,$stuname,$domain);
4303:
4304: $symb=escape($symb);
4305: if (!$namespace) {
4306: unless ($namespace=$env{'request.course.id'}) {
4307: return '';
4308: }
4309: }
4310: if (!$home) { $home=$env{'user.home'}; }
4311:
4312: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4313: $$storehash{'host'}=$perlvar{'lonHostID'};
4314:
4315: my $namevalue='';
4316: foreach my $key (keys(%$storehash)) {
4317: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4318: }
4319: $namevalue=~s/\&$//;
4320: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4321: return critical
4322: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4323: }
4324:
4325: # --------------------------------------------------------------------- Restore
4326:
4327: sub restore {
4328: my ($symb,$namespace,$domain,$stuname) = @_;
4329: my $home='';
4330:
4331: if ($stuname) { $home=&homeserver($stuname,$domain); }
4332:
4333: if (!$symb) {
4334: unless ($symb=escape(&symbread())) { return ''; }
4335: } else {
4336: $symb=&escape(&symbclean($symb));
4337: }
4338: if (!$namespace) {
4339: unless ($namespace=$env{'request.course.id'}) {
4340: return '';
4341: }
4342: }
4343: if (!$domain) { $domain=$env{'user.domain'}; }
4344: if (!$stuname) { $stuname=$env{'user.name'}; }
4345: if (!$home) { $home=$env{'user.home'}; }
4346: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4347:
4348: my %returnhash=();
4349: foreach my $line (split(/\&/,$answer)) {
4350: my ($name,$value)=split(/\=/,$line);
4351: $returnhash{&unescape($name)}=&thaw_unescape($value);
4352: }
4353: my $version;
4354: for ($version=1;$version<=$returnhash{'version'};$version++) {
4355: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4356: $returnhash{$item}=$returnhash{$version.':'.$item};
4357: }
4358: }
4359: return %returnhash;
4360: }
4361:
4362: # ---------------------------------------------------------- Course Description
4363: #
4364: #
4365:
4366: sub coursedescription {
4367: my ($courseid,$args)=@_;
4368: $courseid=~s/^\///;
4369: $courseid=~s/\_/\//g;
4370: my ($cdomain,$cnum)=split(/\//,$courseid);
4371: my $chome=&homeserver($cnum,$cdomain);
4372: my $normalid=$cdomain.'_'.$cnum;
4373: # need to always cache even if we get errors otherwise we keep
4374: # trying and trying and trying to get the course description.
4375: my %envhash=();
4376: my %returnhash=();
4377:
4378: my $expiretime=600;
4379: if ($env{'request.course.id'} eq $normalid) {
4380: $expiretime=120;
4381: }
4382:
4383: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4384: if (!$args->{'freshen_cache'}
4385: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4386: foreach my $key (keys(%env)) {
4387: next if ($key !~ /^\Q$prefix\E(.*)/);
4388: my ($setting) = $1;
4389: $returnhash{$setting} = $env{$key};
4390: }
4391: return %returnhash;
4392: }
4393:
4394: # get the data again
4395:
4396: if (!$args->{'one_time'}) {
4397: $envhash{'course.'.$normalid.'.last_cache'}=time;
4398: }
4399:
4400: if ($chome ne 'no_host') {
4401: %returnhash=&dump('environment',$cdomain,$cnum);
4402: if (!exists($returnhash{'con_lost'})) {
4403: my $username = $env{'user.name'}; # Defult username
4404: if(defined $args->{'user'}) {
4405: $username = $args->{'user'};
4406: }
4407: $returnhash{'home'}= $chome;
4408: $returnhash{'domain'} = $cdomain;
4409: $returnhash{'num'} = $cnum;
4410: if (!defined($returnhash{'type'})) {
4411: $returnhash{'type'} = 'Course';
4412: }
4413: while (my ($name,$value) = each %returnhash) {
4414: $envhash{'course.'.$normalid.'.'.$name}=$value;
4415: }
4416: $returnhash{'url'}=&clutter($returnhash{'url'});
4417: $returnhash{'fn'}=LONCAPA::tempdir() .
4418: $username.'_'.$cdomain.'_'.$cnum;
4419: $envhash{'course.'.$normalid.'.home'}=$chome;
4420: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4421: $envhash{'course.'.$normalid.'.num'}=$cnum;
4422: }
4423: }
4424: if (!$args->{'one_time'}) {
4425: &appenv(\%envhash);
4426: }
4427: return %returnhash;
4428: }
4429:
4430: sub update_released_required {
4431: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4432: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4433: $cid = $env{'request.course.id'};
4434: $cdom = $env{'course.'.$cid.'.domain'};
4435: $cnum = $env{'course.'.$cid.'.num'};
4436: $chome = $env{'course.'.$cid.'.home'};
4437: }
4438: if ($needsrelease) {
4439: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4440: my $needsupdate;
4441: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4442: $needsupdate = 1;
4443: } else {
4444: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4445: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4446: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4447: $needsupdate = 1;
4448: }
4449: }
4450: if ($needsupdate) {
4451: my %needshash = (
4452: 'internal.releaserequired' => $needsrelease,
4453: );
4454: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4455: if ($putresult eq 'ok') {
4456: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4457: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4458: if (ref($crsinfo{$cid}) eq 'HASH') {
4459: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4460: &courseidput($cdom,\%crsinfo,$chome,'notime');
4461: }
4462: }
4463: }
4464: }
4465: return;
4466: }
4467:
4468: # -------------------------------------------------See if a user is privileged
4469:
4470: sub privileged {
4471: my ($username,$domain)=@_;
4472: my $rolesdump=&reply("dump:$domain:$username:roles",
4473: &homeserver($username,$domain));
4474: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4475: ($rolesdump =~ /^error:/)) {
4476: return 0;
4477: }
4478: my $now=time;
4479: if ($rolesdump ne '') {
4480: foreach my $entry (split(/&/,$rolesdump)) {
4481: if ($entry!~/^rolesdef_/) {
4482: my ($area,$role)=split(/=/,$entry);
4483: $area=~s/\_\w\w$//;
4484: my ($trole,$tend,$tstart)=split(/_/,$role);
4485: if (($trole eq 'dc') || ($trole eq 'su')) {
4486: my $active=1;
4487: if ($tend) {
4488: if ($tend<$now) { $active=0; }
4489: }
4490: if ($tstart) {
4491: if ($tstart>$now) { $active=0; }
4492: }
4493: if ($active) { return 1; }
4494: }
4495: }
4496: }
4497: }
4498: return 0;
4499: }
4500:
4501: # -------------------------------------------------------- Get user privileges
4502:
4503: sub rolesinit {
4504: my ($domain,$username,$authhost)=@_;
4505: my $now=time;
4506: my %userroles = ('user.login.time' => $now);
4507: my $extra = &freeze_escape({'skipcheck' => 1});
4508: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
4509: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4510: ($rolesdump =~ /^error:/)) {
4511: return \%userroles;
4512: }
4513: my %allroles=();
4514: my %allgroups=();
4515:
4516: if ($rolesdump ne '') {
4517: foreach my $entry (split(/&/,$rolesdump)) {
4518: if ($entry!~/^rolesdef_/) {
4519: my ($area,$role)=split(/=/,$entry);
4520: $area=~s/\_\w\w$//;
4521: my ($trole,$tend,$tstart,$group_privs);
4522: if ($role=~/^cr/) {
4523: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4524: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4525: ($tend,$tstart)=split('_',$trest);
4526: } else {
4527: $trole=$role;
4528: }
4529: } elsif ($role =~ m|^gr/|) {
4530: ($trole,$tend,$tstart) = split(/_/,$role);
4531: next if ($tstart eq '-1');
4532: ($trole,$group_privs) = split(/\//,$trole);
4533: $group_privs = &unescape($group_privs);
4534: } else {
4535: ($trole,$tend,$tstart)=split(/_/,$role);
4536: }
4537: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4538: $username);
4539: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4540: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4541: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4542: if (($area ne '') && ($trole ne '')) {
4543: my $spec=$trole.'.'.$area;
4544: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4545: if ($trole =~ /^cr\//) {
4546: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4547: } elsif ($trole eq 'gr') {
4548: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4549: } else {
4550: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4551: }
4552: }
4553: }
4554: }
4555: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4556: $userroles{'user.adv'} = $adv;
4557: $userroles{'user.author'} = $author;
4558: $env{'user.adv'}=$adv;
4559: }
4560: return \%userroles;
4561: }
4562:
4563: sub set_arearole {
4564: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4565: # log the associated role with the area
4566: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4567: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4568: }
4569:
4570: sub custom_roleprivs {
4571: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4572: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4573: my $homsvr=homeserver($rauthor,$rdomain);
4574: if (&hostname($homsvr) ne '') {
4575: my ($rdummy,$roledef)=
4576: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4577: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4578: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4579: if (defined($syspriv)) {
4580: if ($trest =~ /^$match_community$/) {
4581: $syspriv =~ s/bre\&S//;
4582: }
4583: $$allroles{'cm./'}.=':'.$syspriv;
4584: $$allroles{$spec.'./'}.=':'.$syspriv;
4585: }
4586: if ($tdomain ne '') {
4587: if (defined($dompriv)) {
4588: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4589: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4590: }
4591: if (($trest ne '') && (defined($coursepriv))) {
4592: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4593: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4594: }
4595: }
4596: }
4597: }
4598: }
4599:
4600: sub group_roleprivs {
4601: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4602: my $access = 1;
4603: my $now = time;
4604: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4605: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4606: if ($access) {
4607: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4608: $$allgroups{$course}{$group} .=':'.$group_privs;
4609: }
4610: }
4611:
4612: sub standard_roleprivs {
4613: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4614: if (defined($pr{$trole.':s'})) {
4615: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4616: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4617: }
4618: if ($tdomain ne '') {
4619: if (defined($pr{$trole.':d'})) {
4620: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4621: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4622: }
4623: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4624: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4625: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4626: }
4627: }
4628: }
4629:
4630: sub set_userprivs {
4631: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4632: my $author=0;
4633: my $adv=0;
4634: my %grouproles = ();
4635: if (keys(%{$allgroups}) > 0) {
4636: my @groupkeys;
4637: foreach my $role (keys(%{$allroles})) {
4638: push(@groupkeys,$role);
4639: }
4640: if (ref($groups_roles) eq 'HASH') {
4641: foreach my $key (keys(%{$groups_roles})) {
4642: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4643: push(@groupkeys,$key);
4644: }
4645: }
4646: }
4647: if (@groupkeys > 0) {
4648: foreach my $role (@groupkeys) {
4649: my ($trole,$area,$sec,$extendedarea);
4650: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4651: $trole = $1;
4652: $area = $2;
4653: $sec = $3;
4654: $extendedarea = $area.$sec;
4655: if (exists($$allgroups{$area})) {
4656: foreach my $group (keys(%{$$allgroups{$area}})) {
4657: my $spec = $trole.'.'.$extendedarea;
4658: $grouproles{$spec.'.'.$area.'/'.$group} =
4659: $$allgroups{$area}{$group};
4660: }
4661: }
4662: }
4663: }
4664: }
4665: }
4666: foreach my $group (keys(%grouproles)) {
4667: $$allroles{$group} = $grouproles{$group};
4668: }
4669: foreach my $role (keys(%{$allroles})) {
4670: my %thesepriv;
4671: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4672: foreach my $item (split(/:/,$$allroles{$role})) {
4673: if ($item ne '') {
4674: my ($privilege,$restrictions)=split(/&/,$item);
4675: if ($restrictions eq '') {
4676: $thesepriv{$privilege}='F';
4677: } elsif ($thesepriv{$privilege} ne 'F') {
4678: $thesepriv{$privilege}.=$restrictions;
4679: }
4680: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4681: }
4682: }
4683: my $thesestr='';
4684: foreach my $priv (sort(keys(%thesepriv))) {
4685: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4686: }
4687: $userroles->{'user.priv.'.$role} = $thesestr;
4688: }
4689: return ($author,$adv);
4690: }
4691:
4692: sub role_status {
4693: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4694: my @pwhere = ();
4695: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4696: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4697: unless (!defined($$role) || $$role eq '') {
4698: $$where=join('.',@pwhere);
4699: $$trolecode=$$role.'.'.$$where;
4700: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4701: $$tstatus='is';
4702: if ($$tstart && $$tstart>$update) {
4703: $$tstatus='future';
4704: if ($$tstart<$now) {
4705: if ($$tstart && $$tstart>$refresh) {
4706: if (($$where ne '') && ($$role ne '')) {
4707: my (%allroles,%allgroups,$group_privs,
4708: %groups_roles,@rolecodes);
4709: my %userroles = (
4710: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4711: );
4712: @rolecodes = ('cm');
4713: my $spec=$$role.'.'.$$where;
4714: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4715: if ($$role =~ /^cr\//) {
4716: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4717: push(@rolecodes,'cr');
4718: } elsif ($$role eq 'gr') {
4719: push(@rolecodes,$$role);
4720: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4721: $env{'user.name'});
4722: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4723: (undef,my $group_privs) = split(/\//,$trole);
4724: $group_privs = &unescape($group_privs);
4725: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4726: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4727: &get_groups_roles($tdomain,$trest,
4728: \%course_roles,\@rolecodes,
4729: \%groups_roles);
4730: } else {
4731: push(@rolecodes,$$role);
4732: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4733: }
4734: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4735: &appenv(\%userroles,\@rolecodes);
4736: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4737: }
4738: }
4739: $$tstatus = 'is';
4740: }
4741: }
4742: if ($$tend) {
4743: if ($$tend<$update) {
4744: $$tstatus='expired';
4745: } elsif ($$tend<$now) {
4746: $$tstatus='will_not';
4747: }
4748: }
4749: }
4750: }
4751: }
4752:
4753: sub get_groups_roles {
4754: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4755: return unless((ref($cdom_courseroles) eq 'HASH') &&
4756: (ref($rolecodes) eq 'ARRAY') &&
4757: (ref($groups_roles) eq 'HASH'));
4758: if (keys(%{$cdom_courseroles}) > 0) {
4759: my ($cnum) = ($rest =~ /^($match_courseid)/);
4760: if ($cdom ne '' && $cnum ne '') {
4761: foreach my $key (keys(%{$cdom_courseroles})) {
4762: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4763: my $crsrole = $1;
4764: my $crssec = $2;
4765: if ($crsrole =~ /^cr/) {
4766: unless (grep(/^cr$/,@{$rolecodes})) {
4767: push(@{$rolecodes},'cr');
4768: }
4769: } else {
4770: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4771: push(@{$rolecodes},$crsrole);
4772: }
4773: }
4774: my $rolekey = "$crsrole./$cdom/$cnum";
4775: if ($crssec ne '') {
4776: $rolekey .= "/$crssec";
4777: }
4778: $rolekey .= './';
4779: $groups_roles->{$rolekey} = $rolecodes;
4780: }
4781: }
4782: }
4783: }
4784: return;
4785: }
4786:
4787: sub delete_env_groupprivs {
4788: my ($where,$courseroles,$possroles) = @_;
4789: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4790: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4791: unless (ref($courseroles->{$udom}) eq 'HASH') {
4792: %{$courseroles->{$udom}} =
4793: &get_my_roles('','','userroles',['active'],
4794: $possroles,[$udom],1);
4795: }
4796: if (ref($courseroles->{$udom}) eq 'HASH') {
4797: foreach my $item (keys(%{$courseroles->{$udom}})) {
4798: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4799: my $area = '/'.$cdom.'/'.$cnum;
4800: my $privkey = "user.priv.$crsrole.$area";
4801: if ($crssec ne '') {
4802: $privkey .= '/'.$crssec;
4803: }
4804: $privkey .= ".$area/$group";
4805: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4806: }
4807: }
4808: return;
4809: }
4810:
4811: sub check_adhoc_privs {
4812: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4813: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4814: if ($env{$cckey}) {
4815: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4816: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4817: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4818: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4819: }
4820: } else {
4821: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4822: }
4823: }
4824:
4825: sub set_adhoc_privileges {
4826: # role can be cc or ca
4827: my ($dcdom,$pickedcourse,$role,$caller) = @_;
4828: my $area = '/'.$dcdom.'/'.$pickedcourse;
4829: my $spec = $role.'.'.$area;
4830: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4831: $env{'user.name'});
4832: my %ccrole = ();
4833: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4834: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4835: &appenv(\%userroles,[$role,'cm']);
4836: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4837: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4838: &appenv( {'request.role' => $spec,
4839: 'request.role.domain' => $dcdom,
4840: 'request.course.sec' => ''
4841: }
4842: );
4843: my $tadv=0;
4844: if (&allowed('adv') eq 'F') { $tadv=1; }
4845: &appenv({'request.role.adv' => $tadv});
4846: }
4847: }
4848:
4849: # --------------------------------------------------------------- get interface
4850:
4851: sub get {
4852: my ($namespace,$storearr,$udomain,$uname)=@_;
4853: my $items='';
4854: foreach my $item (@$storearr) {
4855: $items.=&escape($item).'&';
4856: }
4857: $items=~s/\&$//;
4858: if (!$udomain) { $udomain=$env{'user.domain'}; }
4859: if (!$uname) { $uname=$env{'user.name'}; }
4860: my $uhome=&homeserver($uname,$udomain);
4861:
4862: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4863: my @pairs=split(/\&/,$rep);
4864: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4865: return @pairs;
4866: }
4867: my %returnhash=();
4868: my $i=0;
4869: foreach my $item (@$storearr) {
4870: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4871: $i++;
4872: }
4873: return %returnhash;
4874: }
4875:
4876: # --------------------------------------------------------------- del interface
4877:
4878: sub del {
4879: my ($namespace,$storearr,$udomain,$uname)=@_;
4880: my $items='';
4881: foreach my $item (@$storearr) {
4882: $items.=&escape($item).'&';
4883: }
4884:
4885: $items=~s/\&$//;
4886: if (!$udomain) { $udomain=$env{'user.domain'}; }
4887: if (!$uname) { $uname=$env{'user.name'}; }
4888: my $uhome=&homeserver($uname,$udomain);
4889: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4890: }
4891:
4892: # -------------------------------------------------------------- dump interface
4893:
4894: sub dump {
4895: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
4896: if (!$udomain) { $udomain=$env{'user.domain'}; }
4897: if (!$uname) { $uname=$env{'user.name'}; }
4898: my $uhome=&homeserver($uname,$udomain);
4899: if ($regexp) {
4900: $regexp=&escape($regexp);
4901: } else {
4902: $regexp='.';
4903: }
4904: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
4905: my @pairs=split(/\&/,$rep);
4906: my %returnhash=();
4907: if (!($rep =~ /^error/ )) {
4908: foreach my $item (@pairs) {
4909: my ($key,$value)=split(/=/,$item,2);
4910: $key = &unescape($key);
4911: next if ($key =~ /^error: 2 /);
4912: $returnhash{$key}=&thaw_unescape($value);
4913: }
4914: }
4915: return %returnhash;
4916: }
4917:
4918:
4919: # --------------------------------------------------------- dumpstore interface
4920:
4921: sub dumpstore {
4922: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4923: if (!$udomain) { $udomain=$env{'user.domain'}; }
4924: if (!$uname) { $uname=$env{'user.name'}; }
4925: my $uhome=&homeserver($uname,$udomain);
4926: if ($regexp) {
4927: $regexp=&escape($regexp);
4928: } else {
4929: $regexp='.';
4930: }
4931: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4932: my @pairs=split(/\&/,$rep);
4933: my %returnhash=();
4934: foreach my $item (@pairs) {
4935: my ($key,$value)=split(/=/,$item,2);
4936: next if ($key =~ /^error: 2 /);
4937: $returnhash{$key}=&thaw_unescape($value);
4938: }
4939: return %returnhash;
4940: }
4941:
4942: # -------------------------------------------------------------- keys interface
4943:
4944: sub getkeys {
4945: my ($namespace,$udomain,$uname)=@_;
4946: if (!$udomain) { $udomain=$env{'user.domain'}; }
4947: if (!$uname) { $uname=$env{'user.name'}; }
4948: my $uhome=&homeserver($uname,$udomain);
4949: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4950: my @keyarray=();
4951: foreach my $key (split(/\&/,$rep)) {
4952: next if ($key =~ /^error: 2 /);
4953: push(@keyarray,&unescape($key));
4954: }
4955: return @keyarray;
4956: }
4957:
4958: # --------------------------------------------------------------- currentdump
4959: sub currentdump {
4960: my ($courseid,$sdom,$sname)=@_;
4961: $courseid = $env{'request.course.id'} if (! defined($courseid));
4962: $sdom = $env{'user.domain'} if (! defined($sdom));
4963: $sname = $env{'user.name'} if (! defined($sname));
4964: my $uhome = &homeserver($sname,$sdom);
4965: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4966: return if ($rep =~ /^(error:|no_such_host)/);
4967: #
4968: my %returnhash=();
4969: #
4970: if ($rep eq "unknown_cmd") {
4971: # an old lond will not know currentdump
4972: # Do a dump and make it look like a currentdump
4973: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4974: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4975: my %hash = @tmp;
4976: @tmp=();
4977: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4978: } else {
4979: my @pairs=split(/\&/,$rep);
4980: foreach my $pair (@pairs) {
4981: my ($key,$value)=split(/=/,$pair,2);
4982: my ($symb,$param) = split(/:/,$key);
4983: $returnhash{&unescape($symb)}->{&unescape($param)} =
4984: &thaw_unescape($value);
4985: }
4986: }
4987: return %returnhash;
4988: }
4989:
4990: sub convert_dump_to_currentdump{
4991: my %hash = %{shift()};
4992: my %returnhash;
4993: # Code ripped from lond, essentially. The only difference
4994: # here is the unescaping done by lonnet::dump(). Conceivably
4995: # we might run in to problems with parameter names =~ /^v\./
4996: while (my ($key,$value) = each(%hash)) {
4997: my ($v,$symb,$param) = split(/:/,$key);
4998: $symb = &unescape($symb);
4999: $param = &unescape($param);
5000: next if ($v eq 'version' || $symb eq 'keys');
5001: next if (exists($returnhash{$symb}) &&
5002: exists($returnhash{$symb}->{$param}) &&
5003: $returnhash{$symb}->{'v.'.$param} > $v);
5004: $returnhash{$symb}->{$param}=$value;
5005: $returnhash{$symb}->{'v.'.$param}=$v;
5006: }
5007: #
5008: # Remove all of the keys in the hashes which keep track of
5009: # the version of the parameter.
5010: while (my ($symb,$param_hash) = each(%returnhash)) {
5011: # use a foreach because we are going to delete from the hash.
5012: foreach my $key (keys(%$param_hash)) {
5013: delete($param_hash->{$key}) if ($key =~ /^v\./);
5014: }
5015: }
5016: return \%returnhash;
5017: }
5018:
5019: # ------------------------------------------------------ critical inc interface
5020:
5021: sub cinc {
5022: return &inc(@_,'critical');
5023: }
5024:
5025: # --------------------------------------------------------------- inc interface
5026:
5027: sub inc {
5028: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5029: if (!$udomain) { $udomain=$env{'user.domain'}; }
5030: if (!$uname) { $uname=$env{'user.name'}; }
5031: my $uhome=&homeserver($uname,$udomain);
5032: my $items='';
5033: if (! ref($store)) {
5034: # got a single value, so use that instead
5035: $items = &escape($store).'=&';
5036: } elsif (ref($store) eq 'SCALAR') {
5037: $items = &escape($$store).'=&';
5038: } elsif (ref($store) eq 'ARRAY') {
5039: $items = join('=&',map {&escape($_);} @{$store});
5040: } elsif (ref($store) eq 'HASH') {
5041: while (my($key,$value) = each(%{$store})) {
5042: $items.= &escape($key).'='.&escape($value).'&';
5043: }
5044: }
5045: $items=~s/\&$//;
5046: if ($critical) {
5047: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5048: } else {
5049: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5050: }
5051: }
5052:
5053: # --------------------------------------------------------------- put interface
5054:
5055: sub put {
5056: my ($namespace,$storehash,$udomain,$uname)=@_;
5057: if (!$udomain) { $udomain=$env{'user.domain'}; }
5058: if (!$uname) { $uname=$env{'user.name'}; }
5059: my $uhome=&homeserver($uname,$udomain);
5060: my $items='';
5061: foreach my $item (keys(%$storehash)) {
5062: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5063: }
5064: $items=~s/\&$//;
5065: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5066: }
5067:
5068: # ------------------------------------------------------------ newput interface
5069:
5070: sub newput {
5071: my ($namespace,$storehash,$udomain,$uname)=@_;
5072: if (!$udomain) { $udomain=$env{'user.domain'}; }
5073: if (!$uname) { $uname=$env{'user.name'}; }
5074: my $uhome=&homeserver($uname,$udomain);
5075: my $items='';
5076: foreach my $key (keys(%$storehash)) {
5077: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5078: }
5079: $items=~s/\&$//;
5080: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5081: }
5082:
5083: # --------------------------------------------------------- putstore interface
5084:
5085: sub putstore {
5086: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5087: if (!$udomain) { $udomain=$env{'user.domain'}; }
5088: if (!$uname) { $uname=$env{'user.name'}; }
5089: my $uhome=&homeserver($uname,$udomain);
5090: my $items='';
5091: foreach my $key (keys(%$storehash)) {
5092: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5093: }
5094: $items=~s/\&$//;
5095: my $esc_symb=&escape($symb);
5096: my $esc_v=&escape($version);
5097: my $reply =
5098: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5099: $uhome);
5100: if ($reply eq 'unknown_cmd') {
5101: # gfall back to way things use to be done
5102: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5103: $uname);
5104: }
5105: return $reply;
5106: }
5107:
5108: sub old_putstore {
5109: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5110: if (!$udomain) { $udomain=$env{'user.domain'}; }
5111: if (!$uname) { $uname=$env{'user.name'}; }
5112: my $uhome=&homeserver($uname,$udomain);
5113: my %newstorehash;
5114: foreach my $item (keys(%$storehash)) {
5115: my $key = $version.':'.&escape($symb).':'.$item;
5116: $newstorehash{$key} = $storehash->{$item};
5117: }
5118: my $items='';
5119: my %allitems = ();
5120: foreach my $item (keys(%newstorehash)) {
5121: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5122: my $key = $1.':keys:'.$2;
5123: $allitems{$key} .= $3.':';
5124: }
5125: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5126: }
5127: foreach my $item (keys(%allitems)) {
5128: $allitems{$item} =~ s/\:$//;
5129: $items.= $item.'='.$allitems{$item}.'&';
5130: }
5131: $items=~s/\&$//;
5132: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5133: }
5134:
5135: # ------------------------------------------------------ critical put interface
5136:
5137: sub cput {
5138: my ($namespace,$storehash,$udomain,$uname)=@_;
5139: if (!$udomain) { $udomain=$env{'user.domain'}; }
5140: if (!$uname) { $uname=$env{'user.name'}; }
5141: my $uhome=&homeserver($uname,$udomain);
5142: my $items='';
5143: foreach my $item (keys(%$storehash)) {
5144: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5145: }
5146: $items=~s/\&$//;
5147: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5148: }
5149:
5150: # -------------------------------------------------------------- eget interface
5151:
5152: sub eget {
5153: my ($namespace,$storearr,$udomain,$uname)=@_;
5154: my $items='';
5155: foreach my $item (@$storearr) {
5156: $items.=&escape($item).'&';
5157: }
5158: $items=~s/\&$//;
5159: if (!$udomain) { $udomain=$env{'user.domain'}; }
5160: if (!$uname) { $uname=$env{'user.name'}; }
5161: my $uhome=&homeserver($uname,$udomain);
5162: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5163: my @pairs=split(/\&/,$rep);
5164: my %returnhash=();
5165: my $i=0;
5166: foreach my $item (@$storearr) {
5167: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5168: $i++;
5169: }
5170: return %returnhash;
5171: }
5172:
5173: # ------------------------------------------------------------ tmpput interface
5174: sub tmpput {
5175: my ($storehash,$server,$context)=@_;
5176: my $items='';
5177: foreach my $item (keys(%$storehash)) {
5178: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5179: }
5180: $items=~s/\&$//;
5181: if (defined($context)) {
5182: $items .= ':'.&escape($context);
5183: }
5184: return &reply("tmpput:$items",$server);
5185: }
5186:
5187: # ------------------------------------------------------------ tmpget interface
5188: sub tmpget {
5189: my ($token,$server)=@_;
5190: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5191: my $rep=&reply("tmpget:$token",$server);
5192: my %returnhash;
5193: foreach my $item (split(/\&/,$rep)) {
5194: my ($key,$value)=split(/=/,$item);
5195: next if ($key =~ /^error: 2 /);
5196: $returnhash{&unescape($key)}=&thaw_unescape($value);
5197: }
5198: return %returnhash;
5199: }
5200:
5201: # ------------------------------------------------------------ tmpdel interface
5202: sub tmpdel {
5203: my ($token,$server)=@_;
5204: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5205: return &reply("tmpdel:$token",$server);
5206: }
5207:
5208: # -------------------------------------------------- portfolio access checking
5209:
5210: sub portfolio_access {
5211: my ($requrl) = @_;
5212: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5213: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5214: if ($result) {
5215: my %setters;
5216: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5217: my ($startblock,$endblock) =
5218: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5219: if ($startblock && $endblock) {
5220: return 'B';
5221: }
5222: } else {
5223: my ($startblock,$endblock) =
5224: &Apache::loncommon::blockcheck(\%setters,'port');
5225: if ($startblock && $endblock) {
5226: return 'B';
5227: }
5228: }
5229: }
5230: if ($result eq 'ok') {
5231: return 'F';
5232: } elsif ($result =~ /^[^:]+:guest_/) {
5233: return 'A';
5234: }
5235: return '';
5236: }
5237:
5238: sub get_portfolio_access {
5239: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5240:
5241: if (!ref($access_hash)) {
5242: my $current_perms = &get_portfile_permissions($udom,$unum);
5243: my %access_controls = &get_access_controls($current_perms,$group,
5244: $file_name);
5245: $access_hash = $access_controls{$file_name};
5246: }
5247:
5248: my ($public,$guest,@domains,@users,@courses,@groups);
5249: my $now = time;
5250: if (ref($access_hash) eq 'HASH') {
5251: foreach my $key (keys(%{$access_hash})) {
5252: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5253: if ($start > $now) {
5254: next;
5255: }
5256: if ($end && $end<$now) {
5257: next;
5258: }
5259: if ($scope eq 'public') {
5260: $public = $key;
5261: last;
5262: } elsif ($scope eq 'guest') {
5263: $guest = $key;
5264: } elsif ($scope eq 'domains') {
5265: push(@domains,$key);
5266: } elsif ($scope eq 'users') {
5267: push(@users,$key);
5268: } elsif ($scope eq 'course') {
5269: push(@courses,$key);
5270: } elsif ($scope eq 'group') {
5271: push(@groups,$key);
5272: }
5273: }
5274: if ($public) {
5275: return 'ok';
5276: }
5277: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5278: if ($guest) {
5279: return $guest;
5280: }
5281: } else {
5282: if (@domains > 0) {
5283: foreach my $domkey (@domains) {
5284: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5285: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5286: return 'ok';
5287: }
5288: }
5289: }
5290: }
5291: if (@users > 0) {
5292: foreach my $userkey (@users) {
5293: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5294: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5295: if (ref($item) eq 'HASH') {
5296: if (($item->{'uname'} eq $env{'user.name'}) &&
5297: ($item->{'udom'} eq $env{'user.domain'})) {
5298: return 'ok';
5299: }
5300: }
5301: }
5302: }
5303: }
5304: }
5305: my %roleshash;
5306: my @courses_and_groups = @courses;
5307: push(@courses_and_groups,@groups);
5308: if (@courses_and_groups > 0) {
5309: my (%allgroups,%allroles);
5310: my ($start,$end,$role,$sec,$group);
5311: foreach my $envkey (%env) {
5312: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5313: my $cid = $2.'_'.$3;
5314: if ($1 eq 'gr') {
5315: $group = $4;
5316: $allgroups{$cid}{$group} = $env{$envkey};
5317: } else {
5318: if ($4 eq '') {
5319: $sec = 'none';
5320: } else {
5321: $sec = $4;
5322: }
5323: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5324: }
5325: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5326: my $cid = $2.'_'.$3;
5327: if ($4 eq '') {
5328: $sec = 'none';
5329: } else {
5330: $sec = $4;
5331: }
5332: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5333: }
5334: }
5335: if (keys(%allroles) == 0) {
5336: return;
5337: }
5338: foreach my $key (@courses_and_groups) {
5339: my %content = %{$$access_hash{$key}};
5340: my $cnum = $content{'number'};
5341: my $cdom = $content{'domain'};
5342: my $cid = $cdom.'_'.$cnum;
5343: if (!exists($allroles{$cid})) {
5344: next;
5345: }
5346: foreach my $role_id (keys(%{$content{'roles'}})) {
5347: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5348: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5349: my @status = @{$content{'roles'}{$role_id}{'access'}};
5350: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5351: foreach my $role (keys(%{$allroles{$cid}})) {
5352: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5353: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5354: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5355: if (grep/^all$/,@sections) {
5356: return 'ok';
5357: } else {
5358: if (grep/^$sec$/,@sections) {
5359: return 'ok';
5360: }
5361: }
5362: }
5363: }
5364: if (keys(%{$allgroups{$cid}}) == 0) {
5365: if (grep/^none$/,@groups) {
5366: return 'ok';
5367: }
5368: } else {
5369: if (grep/^all$/,@groups) {
5370: return 'ok';
5371: }
5372: foreach my $group (keys(%{$allgroups{$cid}})) {
5373: if (grep/^$group$/,@groups) {
5374: return 'ok';
5375: }
5376: }
5377: }
5378: }
5379: }
5380: }
5381: }
5382: }
5383: if ($guest) {
5384: return $guest;
5385: }
5386: }
5387: }
5388: return;
5389: }
5390:
5391: sub course_group_datechecker {
5392: my ($dates,$now,$status) = @_;
5393: my ($start,$end) = split(/\./,$dates);
5394: if (!$start && !$end) {
5395: return 'ok';
5396: }
5397: if (grep/^active$/,@{$status}) {
5398: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5399: return 'ok';
5400: }
5401: }
5402: if (grep/^previous$/,@{$status}) {
5403: if ($end > $now ) {
5404: return 'ok';
5405: }
5406: }
5407: if (grep/^future$/,@{$status}) {
5408: if ($start > $now) {
5409: return 'ok';
5410: }
5411: }
5412: return;
5413: }
5414:
5415: sub parse_portfolio_url {
5416: my ($url) = @_;
5417:
5418: my ($type,$udom,$unum,$group,$file_name);
5419:
5420: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5421: $type = 1;
5422: $udom = $1;
5423: $unum = $2;
5424: $file_name = $3;
5425: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5426: $type = 2;
5427: $udom = $1;
5428: $unum = $2;
5429: $group = $3;
5430: $file_name = $3.'/'.$4;
5431: }
5432: if (wantarray) {
5433: return ($type,$udom,$unum,$file_name,$group);
5434: }
5435: return $type;
5436: }
5437:
5438: sub is_portfolio_url {
5439: my ($url) = @_;
5440: return scalar(&parse_portfolio_url($url));
5441: }
5442:
5443: sub is_portfolio_file {
5444: my ($file) = @_;
5445: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5446: return 1;
5447: }
5448: return;
5449: }
5450:
5451: sub usertools_access {
5452: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5453: my ($access,%tools);
5454: if ($context eq '') {
5455: $context = 'tools';
5456: }
5457: if ($context eq 'requestcourses') {
5458: %tools = (
5459: official => 1,
5460: unofficial => 1,
5461: community => 1,
5462: );
5463: } else {
5464: %tools = (
5465: aboutme => 1,
5466: blog => 1,
5467: portfolio => 1,
5468: );
5469: }
5470: return if (!defined($tools{$tool}));
5471:
5472: if ((!defined($udom)) || (!defined($uname))) {
5473: $udom = $env{'user.domain'};
5474: $uname = $env{'user.name'};
5475: }
5476:
5477: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5478: if ($action ne 'reload') {
5479: if ($context eq 'requestcourses') {
5480: return $env{'environment.canrequest.'.$tool};
5481: } else {
5482: return $env{'environment.availabletools.'.$tool};
5483: }
5484: }
5485: }
5486:
5487: my ($toolstatus,$inststatus);
5488:
5489: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5490: ($action ne 'reload')) {
5491: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5492: $inststatus = $env{'environment.inststatus'};
5493: } else {
5494: if (ref($userenvref) eq 'HASH') {
5495: $toolstatus = $userenvref->{$context.'.'.$tool};
5496: $inststatus = $userenvref->{'inststatus'};
5497: } else {
5498: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5499: $toolstatus = $userenv{$context.'.'.$tool};
5500: $inststatus = $userenv{'inststatus'};
5501: }
5502: }
5503:
5504: if ($toolstatus ne '') {
5505: if ($toolstatus) {
5506: $access = 1;
5507: } else {
5508: $access = 0;
5509: }
5510: return $access;
5511: }
5512:
5513: my ($is_adv,%domdef);
5514: if (ref($is_advref) eq 'HASH') {
5515: $is_adv = $is_advref->{'is_adv'};
5516: } else {
5517: $is_adv = &is_advanced_user($udom,$uname);
5518: }
5519: if (ref($domdefref) eq 'HASH') {
5520: %domdef = %{$domdefref};
5521: } else {
5522: %domdef = &get_domain_defaults($udom);
5523: }
5524: if (ref($domdef{$tool}) eq 'HASH') {
5525: if ($is_adv) {
5526: if ($domdef{$tool}{'_LC_adv'} ne '') {
5527: if ($domdef{$tool}{'_LC_adv'}) {
5528: $access = 1;
5529: } else {
5530: $access = 0;
5531: }
5532: return $access;
5533: }
5534: }
5535: if ($inststatus ne '') {
5536: my ($hasaccess,$hasnoaccess);
5537: foreach my $affiliation (split(/:/,$inststatus)) {
5538: if ($domdef{$tool}{$affiliation} ne '') {
5539: if ($domdef{$tool}{$affiliation}) {
5540: $hasaccess = 1;
5541: } else {
5542: $hasnoaccess = 1;
5543: }
5544: }
5545: }
5546: if ($hasaccess || $hasnoaccess) {
5547: if ($hasaccess) {
5548: $access = 1;
5549: } elsif ($hasnoaccess) {
5550: $access = 0;
5551: }
5552: return $access;
5553: }
5554: } else {
5555: if ($domdef{$tool}{'default'} ne '') {
5556: if ($domdef{$tool}{'default'}) {
5557: $access = 1;
5558: } elsif ($domdef{$tool}{'default'} == 0) {
5559: $access = 0;
5560: }
5561: return $access;
5562: }
5563: }
5564: } else {
5565: if ($context eq 'tools') {
5566: $access = 1;
5567: } else {
5568: $access = 0;
5569: }
5570: return $access;
5571: }
5572: }
5573:
5574: sub is_course_owner {
5575: my ($cdom,$cnum,$udom,$uname) = @_;
5576: if (($udom eq '') || ($uname eq '')) {
5577: $udom = $env{'user.domain'};
5578: $uname = $env{'user.name'};
5579: }
5580: unless (($udom eq '') || ($uname eq '')) {
5581: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5582: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5583: return 1;
5584: } else {
5585: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5586: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5587: return 1;
5588: }
5589: }
5590: }
5591: }
5592: return;
5593: }
5594:
5595: sub is_advanced_user {
5596: my ($udom,$uname) = @_;
5597: if ($udom ne '' && $uname ne '') {
5598: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5599: if (wantarray) {
5600: return ($env{'user.adv'},$env{'user.author'});
5601: } else {
5602: return $env{'user.adv'};
5603: }
5604: }
5605: }
5606: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5607: my %allroles;
5608: my ($is_adv,$is_author);
5609: foreach my $role (keys(%roleshash)) {
5610: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5611: my $area = '/'.$tdomain.'/'.$trest;
5612: if ($sec ne '') {
5613: $area .= '/'.$sec;
5614: }
5615: if (($area ne '') && ($trole ne '')) {
5616: my $spec=$trole.'.'.$area;
5617: if ($trole =~ /^cr\//) {
5618: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5619: } elsif ($trole ne 'gr') {
5620: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5621: }
5622: if ($trole eq 'au') {
5623: $is_author = 1;
5624: }
5625: }
5626: }
5627: foreach my $role (keys(%allroles)) {
5628: last if ($is_adv);
5629: foreach my $item (split(/:/,$allroles{$role})) {
5630: if ($item ne '') {
5631: my ($privilege,$restrictions)=split(/&/,$item);
5632: if ($privilege eq 'adv') {
5633: $is_adv = 1;
5634: last;
5635: }
5636: }
5637: }
5638: }
5639: if (wantarray) {
5640: return ($is_adv,$is_author);
5641: }
5642: return $is_adv;
5643: }
5644:
5645: sub check_can_request {
5646: my ($dom,$can_request,$request_domains) = @_;
5647: my $canreq = 0;
5648: my ($types,$typename) = &Apache::loncommon::course_types();
5649: my @options = ('approval','validate','autolimit');
5650: my $optregex = join('|',@options);
5651: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5652: foreach my $type (@{$types}) {
5653: if (&usertools_access($env{'user.name'},
5654: $env{'user.domain'},
5655: $type,undef,'requestcourses')) {
5656: $canreq ++;
5657: if (ref($request_domains) eq 'HASH') {
5658: push(@{$request_domains->{$type}},$env{'user.domain'});
5659: }
5660: if ($dom eq $env{'user.domain'}) {
5661: $can_request->{$type} = 1;
5662: }
5663: }
5664: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5665: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5666: if (@curr > 0) {
5667: foreach my $item (@curr) {
5668: if (ref($request_domains) eq 'HASH') {
5669: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5670: if ($otherdom ne '') {
5671: if (ref($request_domains->{$type}) eq 'ARRAY') {
5672: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5673: push(@{$request_domains->{$type}},$otherdom);
5674: }
5675: } else {
5676: push(@{$request_domains->{$type}},$otherdom);
5677: }
5678: }
5679: }
5680: }
5681: unless($dom eq $env{'user.domain'}) {
5682: $canreq ++;
5683: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5684: $can_request->{$type} = 1;
5685: }
5686: }
5687: }
5688: }
5689: }
5690: }
5691: return $canreq;
5692: }
5693:
5694: # ---------------------------------------------- Custom access rule evaluation
5695:
5696: sub customaccess {
5697: my ($priv,$uri)=@_;
5698: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5699: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5700: $udom = &LONCAPA::clean_domain($udom);
5701: $ucrs = &LONCAPA::clean_username($ucrs);
5702: my $access=0;
5703: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5704: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5705: if ($type eq 'user') {
5706: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5707: my ($tdom,$tuname)=split(m{/},$scope);
5708: if ($tdom) {
5709: if ($tdom ne $env{'user.domain'}) { next; }
5710: }
5711: if ($tuname) {
5712: if ($tuname ne $env{'user.name'}) { next; }
5713: }
5714: $access=($effect eq 'allow');
5715: last;
5716: }
5717: } else {
5718: if ($role) {
5719: if ($role ne $urole) { next; }
5720: }
5721: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5722: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5723: if ($tdom) {
5724: if ($tdom ne $udom) { next; }
5725: }
5726: if ($tcrs) {
5727: if ($tcrs ne $ucrs) { next; }
5728: }
5729: if ($tsec) {
5730: if ($tsec ne $usec) { next; }
5731: }
5732: $access=($effect eq 'allow');
5733: last;
5734: }
5735: if ($realm eq '' && $role eq '') {
5736: $access=($effect eq 'allow');
5737: }
5738: }
5739: }
5740: return $access;
5741: }
5742:
5743: # ------------------------------------------------- Check for a user privilege
5744:
5745: sub allowed {
5746: my ($priv,$uri,$symb,$role)=@_;
5747: my $ver_orguri=$uri;
5748: $uri=&deversion($uri);
5749: my $orguri=$uri;
5750: $uri=&declutter($uri);
5751:
5752: if ($priv eq 'evb') {
5753: # Evade communication block restrictions for specified role in a course
5754: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5755: return $1;
5756: } else {
5757: return;
5758: }
5759: }
5760:
5761: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5762: # Free bre access to adm and meta resources
5763: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5764: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5765: && ($priv eq 'bre')) {
5766: return 'F';
5767: }
5768:
5769: # Free bre access to user's own portfolio contents
5770: my ($space,$domain,$name,@dir)=split('/',$uri);
5771: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5772: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5773: my %setters;
5774: my ($startblock,$endblock) =
5775: &Apache::loncommon::blockcheck(\%setters,'port');
5776: if ($startblock && $endblock) {
5777: return 'B';
5778: } else {
5779: return 'F';
5780: }
5781: }
5782:
5783: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5784: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5785: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5786: if (exists($env{'request.course.id'})) {
5787: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5788: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5789: if (($domain eq $cdom) && ($name eq $cnum)) {
5790: my $courseprivid=$env{'request.course.id'};
5791: $courseprivid=~s/\_/\//;
5792: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5793: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5794: return $1;
5795: } else {
5796: if ($env{'request.course.sec'}) {
5797: $courseprivid.='/'.$env{'request.course.sec'};
5798: }
5799: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5800: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5801: return $2;
5802: }
5803: }
5804: }
5805: }
5806: }
5807:
5808: # Free bre to public access
5809:
5810: if ($priv eq 'bre') {
5811: my $copyright=&metadata($uri,'copyright');
5812: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5813: return 'F';
5814: }
5815: if ($copyright eq 'priv') {
5816: $uri=~/([^\/]+)\/([^\/]+)\//;
5817: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5818: return '';
5819: }
5820: }
5821: if ($copyright eq 'domain') {
5822: $uri=~/([^\/]+)\/([^\/]+)\//;
5823: unless (($env{'user.domain'} eq $1) ||
5824: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5825: return '';
5826: }
5827: }
5828: if ($env{'request.role'}=~ /li\.\//) {
5829: # Library role, so allow browsing of resources in this domain.
5830: return 'F';
5831: }
5832: if ($copyright eq 'custom') {
5833: unless (&customaccess($priv,$uri)) { return ''; }
5834: }
5835: }
5836: # Domain coordinator is trying to create a course
5837: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5838: # uri is the requested domain in this case.
5839: # comparison to 'request.role.domain' shows if the user has selected
5840: # a role of dc for the domain in question.
5841: return 'F' if ($uri eq $env{'request.role.domain'});
5842: }
5843:
5844: my $thisallowed='';
5845: my $statecond=0;
5846: my $courseprivid='';
5847:
5848: my $ownaccess;
5849: # Community Coordinator or Assistant Co-author browsing resource space.
5850: if (($priv eq 'bro') && ($env{'user.author'})) {
5851: if ($uri eq '') {
5852: $ownaccess = 1;
5853: } else {
5854: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5855: my $udom = $env{'user.domain'};
5856: my $uname = $env{'user.name'};
5857: if ($uri =~ m{^\Q$udom\E/?$}) {
5858: $ownaccess = 1;
5859: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
5860: unless ($uri =~ m{\.\./}) {
5861: $ownaccess = 1;
5862: }
5863: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5864: my $now = time;
5865: if ($uri =~ m{^([^/]+)/?$}) {
5866: my $adom = $1;
5867: foreach my $key (keys(%env)) {
5868: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
5869: my ($start,$end) = split('.',$env{$key});
5870: if (($now >= $start) && (!$end || $end < $now)) {
5871: $ownaccess = 1;
5872: last;
5873: }
5874: }
5875: }
5876: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5877: my $adom = $1;
5878: my $aname = $2;
5879: foreach my $role ('ca','aa') {
5880: if ($env{"user.role.$role./$adom/$aname"}) {
5881: my ($start,$end) =
5882: split('.',$env{"user.role.$role./$adom/$aname"});
5883: if (($now >= $start) && (!$end || $end < $now)) {
5884: $ownaccess = 1;
5885: last;
5886: }
5887: }
5888: }
5889: }
5890: }
5891: }
5892: }
5893: }
5894:
5895: # Course
5896:
5897: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5898: unless (($priv eq 'bro') && (!$ownaccess)) {
5899: $thisallowed.=$1;
5900: }
5901: }
5902:
5903: # Domain
5904:
5905: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5906: =~/\Q$priv\E\&([^\:]*)/) {
5907: unless (($priv eq 'bro') && (!$ownaccess)) {
5908: $thisallowed.=$1;
5909: }
5910: }
5911:
5912: # Course: uri itself is a course
5913: my $courseuri=$uri;
5914: $courseuri=~s/\_(\d)/\/$1/;
5915: $courseuri=~s/^([^\/])/\/$1/;
5916:
5917: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5918: =~/\Q$priv\E\&([^\:]*)/) {
5919: unless (($priv eq 'bro') && (!$ownaccess)) {
5920: $thisallowed.=$1;
5921: }
5922: }
5923:
5924: # URI is an uploaded document for this course, default permissions don't matter
5925: # not allowing 'edit' access (editupload) to uploaded course docs
5926: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5927: $thisallowed='';
5928: my ($match)=&is_on_map($uri);
5929: if ($match) {
5930: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5931: =~/\Q$priv\E\&([^\:]*)/) {
5932: $thisallowed.=$1;
5933: }
5934: } else {
5935: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5936: if ($refuri) {
5937: if ($refuri =~ m|^/adm/|) {
5938: $thisallowed='F';
5939: } else {
5940: $refuri=&declutter($refuri);
5941: my ($match) = &is_on_map($refuri);
5942: if ($match) {
5943: $thisallowed='F';
5944: }
5945: }
5946: }
5947: }
5948: }
5949:
5950: if ($priv eq 'bre'
5951: && $thisallowed ne 'F'
5952: && $thisallowed ne '2'
5953: && &is_portfolio_url($uri)) {
5954: $thisallowed = &portfolio_access($uri);
5955: }
5956:
5957: # Full access at system, domain or course-wide level? Exit.
5958: if ($thisallowed=~/F/) {
5959: return 'F';
5960: }
5961:
5962: # If this is generating or modifying users, exit with special codes
5963:
5964: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5965: if (($priv eq 'cca') || ($priv eq 'caa')) {
5966: my ($audom,$auname)=split('/',$uri);
5967: # no author name given, so this just checks on the general right to make a co-author in this domain
5968: unless ($auname) { return $thisallowed; }
5969: # an author name is given, so we are about to actually make a co-author for a certain account
5970: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5971: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5972: ($audom ne $env{'request.role.domain'}))) { return ''; }
5973: }
5974: return $thisallowed;
5975: }
5976: #
5977: # Gathered so far: system, domain and course wide privileges
5978: #
5979: # Course: See if uri or referer is an individual resource that is part of
5980: # the course
5981:
5982: if ($env{'request.course.id'}) {
5983:
5984: $courseprivid=$env{'request.course.id'};
5985: if ($env{'request.course.sec'}) {
5986: $courseprivid.='/'.$env{'request.course.sec'};
5987: }
5988: $courseprivid=~s/\_/\//;
5989: my $checkreferer=1;
5990: my ($match,$cond)=&is_on_map($uri);
5991: if ($match) {
5992: $statecond=$cond;
5993: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5994: =~/\Q$priv\E\&([^\:]*)/) {
5995: $thisallowed.=$1;
5996: $checkreferer=0;
5997: }
5998: }
5999:
6000: if ($checkreferer) {
6001: my $refuri=$env{'httpref.'.$orguri};
6002: unless ($refuri) {
6003: foreach my $key (keys(%env)) {
6004: if ($key=~/^httpref\..*\*/) {
6005: my $pattern=$key;
6006: $pattern=~s/^httpref\.\/res\///;
6007: $pattern=~s/\*/\[\^\/\]\+/g;
6008: $pattern=~s/\//\\\//g;
6009: if ($orguri=~/$pattern/) {
6010: $refuri=$env{$key};
6011: }
6012: }
6013: }
6014: }
6015:
6016: if ($refuri) {
6017: $refuri=&declutter($refuri);
6018: my ($match,$cond)=&is_on_map($refuri);
6019: if ($match) {
6020: my $refstatecond=$cond;
6021: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6022: =~/\Q$priv\E\&([^\:]*)/) {
6023: $thisallowed.=$1;
6024: $uri=$refuri;
6025: $statecond=$refstatecond;
6026: }
6027: }
6028: }
6029: }
6030: }
6031:
6032: #
6033: # Gathered now: all privileges that could apply, and condition number
6034: #
6035: #
6036: # Full or no access?
6037: #
6038:
6039: if ($thisallowed=~/F/) {
6040: return 'F';
6041: }
6042:
6043: unless ($thisallowed) {
6044: return '';
6045: }
6046:
6047: # Restrictions exist, deal with them
6048: #
6049: # C:according to course preferences
6050: # R:according to resource settings
6051: # L:unless locked
6052: # X:according to user session state
6053: #
6054:
6055: # Possibly locked functionality, check all courses
6056: # Locks might take effect only after 10 minutes cache expiration for other
6057: # courses, and 2 minutes for current course
6058:
6059: my $envkey;
6060: if ($thisallowed=~/L/) {
6061: foreach $envkey (keys(%env)) {
6062: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6063: my $courseid=$2;
6064: my $roleid=$1.'.'.$2;
6065: $courseid=~s/^\///;
6066: my $expiretime=600;
6067: if ($env{'request.role'} eq $roleid) {
6068: $expiretime=120;
6069: }
6070: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6071: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6072: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6073: &coursedescription($courseid,{'freshen_cache' => 1});
6074: }
6075: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6076: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6077: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6078: &log($env{'user.domain'},$env{'user.name'},
6079: $env{'user.home'},
6080: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6081: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6082: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6083: return '';
6084: }
6085: }
6086: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6087: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6088: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6089: &log($env{'user.domain'},$env{'user.name'},
6090: $env{'user.home'},
6091: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6092: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6093: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6094: return '';
6095: }
6096: }
6097: }
6098: }
6099: }
6100:
6101: #
6102: # Rest of the restrictions depend on selected course
6103: #
6104:
6105: unless ($env{'request.course.id'}) {
6106: if ($thisallowed eq 'A') {
6107: return 'A';
6108: } elsif ($thisallowed eq 'B') {
6109: return 'B';
6110: } else {
6111: return '1';
6112: }
6113: }
6114:
6115: #
6116: # Now user is definitely in a course
6117: #
6118:
6119:
6120: # Course preferences
6121:
6122: if ($thisallowed=~/C/) {
6123: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6124: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6125: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6126: =~/\Q$rolecode\E/) {
6127: if (($priv ne 'pch') && ($priv ne 'plc')) {
6128: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6129: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6130: $env{'request.course.id'});
6131: }
6132: return '';
6133: }
6134:
6135: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6136: =~/\Q$unamedom\E/) {
6137: if (($priv ne 'pch') && ($priv ne 'plc')) {
6138: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6139: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6140: $env{'request.course.id'});
6141: }
6142: return '';
6143: }
6144: }
6145:
6146: # Resource preferences
6147:
6148: if ($thisallowed=~/R/) {
6149: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6150: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6151: if (($priv ne 'pch') && ($priv ne 'plc')) {
6152: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6153: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6154: }
6155: return '';
6156: }
6157: }
6158:
6159: # Restricted by state or randomout?
6160:
6161: if ($thisallowed=~/X/) {
6162: if ($env{'acc.randomout'}) {
6163: if (!$symb) { $symb=&symbread($uri,1); }
6164: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6165: return '';
6166: }
6167: }
6168: if (&condval($statecond)) {
6169: return '2';
6170: } else {
6171: return '';
6172: }
6173: }
6174:
6175: if ($thisallowed eq 'A') {
6176: return 'A';
6177: } elsif ($thisallowed eq 'B') {
6178: return 'B';
6179: }
6180: return 'F';
6181: }
6182: #
6183: # Removes the versino from a URI and
6184: # splits it in to its filename and path to the filename.
6185: # Seems like File::Basename could have done this more clearly.
6186: # Parameters:
6187: # $uri - input URI
6188: # Returns:
6189: # Two element list consisting of
6190: # $pathname - the URI up to and excluding the trailing /
6191: # $filename - The part of the URI following the last /
6192: # NOTE:
6193: # Another realization of this is simply:
6194: # use File::Basename;
6195: # ...
6196: # $uri = shift;
6197: # $filename = basename($uri);
6198: # $path = dirname($uri);
6199: # return ($filename, $path);
6200: #
6201: # The implementation below is probably faster however.
6202: #
6203: sub split_uri_for_cond {
6204: my $uri=&deversion(&declutter(shift));
6205: my @uriparts=split(/\//,$uri);
6206: my $filename=pop(@uriparts);
6207: my $pathname=join('/',@uriparts);
6208: return ($pathname,$filename);
6209: }
6210: # --------------------------------------------------- Is a resource on the map?
6211:
6212: sub is_on_map {
6213: my ($pathname,$filename) = &split_uri_for_cond(shift);
6214: #Trying to find the conditional for the file
6215: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6216: /\&\Q$filename\E\:([\d\|]+)\&/);
6217: if ($match) {
6218: return (1,$1);
6219: } else {
6220: return (0,0);
6221: }
6222: }
6223:
6224: # --------------------------------------------------------- Get symb from alias
6225:
6226: sub get_symb_from_alias {
6227: my $symb=shift;
6228: my ($map,$resid,$url)=&decode_symb($symb);
6229: # Already is a symb
6230: if ($url) { return $symb; }
6231: # Must be an alias
6232: my $aliassymb='';
6233: my %bighash;
6234: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6235: &GDBM_READER(),0640)) {
6236: my $rid=$bighash{'mapalias_'.$symb};
6237: if ($rid) {
6238: my ($mapid,$resid)=split(/\./,$rid);
6239: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6240: $resid,$bighash{'src_'.$rid});
6241: }
6242: untie %bighash;
6243: }
6244: return $aliassymb;
6245: }
6246:
6247: # ----------------------------------------------------------------- Define Role
6248:
6249: sub definerole {
6250: if (allowed('mcr','/')) {
6251: my ($rolename,$sysrole,$domrole,$courole)=@_;
6252: foreach my $role (split(':',$sysrole)) {
6253: my ($crole,$cqual)=split(/\&/,$role);
6254: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6255: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6256: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6257: return "refused:s:$crole&$cqual";
6258: }
6259: }
6260: }
6261: foreach my $role (split(':',$domrole)) {
6262: my ($crole,$cqual)=split(/\&/,$role);
6263: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6264: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6265: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6266: return "refused:d:$crole&$cqual";
6267: }
6268: }
6269: }
6270: foreach my $role (split(':',$courole)) {
6271: my ($crole,$cqual)=split(/\&/,$role);
6272: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6273: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6274: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6275: return "refused:c:$crole&$cqual";
6276: }
6277: }
6278: }
6279: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6280: "$env{'user.domain'}:$env{'user.name'}:".
6281: "rolesdef_$rolename=".
6282: escape($sysrole.'_'.$domrole.'_'.$courole);
6283: return reply($command,$env{'user.home'});
6284: } else {
6285: return 'refused';
6286: }
6287: }
6288:
6289: # ---------------- Make a metadata query against the network of library servers
6290:
6291: sub metadata_query {
6292: my ($query,$custom,$customshow,$server_array)=@_;
6293: my %rhash;
6294: my %libserv = &all_library();
6295: my @server_list = (defined($server_array) ? @$server_array
6296: : keys(%libserv) );
6297: for my $server (@server_list) {
6298: unless ($custom or $customshow) {
6299: my $reply=&reply("querysend:".&escape($query),$server);
6300: $rhash{$server}=$reply;
6301: }
6302: else {
6303: my $reply=&reply("querysend:".&escape($query).':'.
6304: &escape($custom).':'.&escape($customshow),
6305: $server);
6306: $rhash{$server}=$reply;
6307: }
6308: }
6309: return \%rhash;
6310: }
6311:
6312: # ----------------------------------------- Send log queries and wait for reply
6313:
6314: sub log_query {
6315: my ($uname,$udom,$query,%filters)=@_;
6316: my $uhome=&homeserver($uname,$udom);
6317: if ($uhome eq 'no_host') { return 'error: no_host'; }
6318: my $uhost=&hostname($uhome);
6319: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6320: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6321: $uhome);
6322: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6323: return get_query_reply($queryid);
6324: }
6325:
6326: # -------------------------- Update MySQL table for portfolio file
6327:
6328: sub update_portfolio_table {
6329: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6330: if ($group ne '') {
6331: $file_name =~s /^\Q$group\E//;
6332: }
6333: my $homeserver = &homeserver($uname,$udom);
6334: my $queryid=
6335: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6336: ':'.&escape($file_name).':'.$action,$homeserver);
6337: my $reply = &get_query_reply($queryid);
6338: return $reply;
6339: }
6340:
6341: # -------------------------- Update MySQL allusers table
6342:
6343: sub update_allusers_table {
6344: my ($uname,$udom,$names) = @_;
6345: my $homeserver = &homeserver($uname,$udom);
6346: my $queryid=
6347: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6348: 'lastname='.&escape($names->{'lastname'}).'%%'.
6349: 'firstname='.&escape($names->{'firstname'}).'%%'.
6350: 'middlename='.&escape($names->{'middlename'}).'%%'.
6351: 'generation='.&escape($names->{'generation'}).'%%'.
6352: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6353: 'id='.&escape($names->{'id'}),$homeserver);
6354: return;
6355: }
6356:
6357: # ------- Request retrieval of institutional classlists for course(s)
6358:
6359: sub fetch_enrollment_query {
6360: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6361: my $homeserver;
6362: my $maxtries = 1;
6363: if ($context eq 'automated') {
6364: $homeserver = $perlvar{'lonHostID'};
6365: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6366: } else {
6367: $homeserver = &homeserver($cnum,$dom);
6368: }
6369: my $host=&hostname($homeserver);
6370: my $cmd = '';
6371: foreach my $affiliate (keys(%{$affiliatesref})) {
6372: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6373: }
6374: $cmd =~ s/%%$//;
6375: $cmd = &escape($cmd);
6376: my $query = 'fetchenrollment';
6377: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6378: unless ($queryid=~/^\Q$host\E\_/) {
6379: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6380: return 'error: '.$queryid;
6381: }
6382: my $reply = &get_query_reply($queryid);
6383: my $tries = 1;
6384: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6385: $reply = &get_query_reply($queryid);
6386: $tries ++;
6387: }
6388: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6389: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6390: } else {
6391: my @responses = split(/:/,$reply);
6392: if ($homeserver eq $perlvar{'lonHostID'}) {
6393: foreach my $line (@responses) {
6394: my ($key,$value) = split(/=/,$line,2);
6395: $$replyref{$key} = $value;
6396: }
6397: } else {
6398: my $pathname = LONCAPA::tempdir();
6399: foreach my $line (@responses) {
6400: my ($key,$value) = split(/=/,$line);
6401: $$replyref{$key} = $value;
6402: if ($value > 0) {
6403: foreach my $item (@{$$affiliatesref{$key}}) {
6404: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6405: my $destname = $pathname.'/'.$filename;
6406: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6407: if ($xml_classlist =~ /^error/) {
6408: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6409: } else {
6410: if ( open(FILE,">$destname") ) {
6411: print FILE &unescape($xml_classlist);
6412: close(FILE);
6413: } else {
6414: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6415: }
6416: }
6417: }
6418: }
6419: }
6420: }
6421: return 'ok';
6422: }
6423: return 'error';
6424: }
6425:
6426: sub get_query_reply {
6427: my $queryid=shift;
6428: my $replyfile=LONCAPA::tempdir().$queryid;
6429: my $reply='';
6430: for (1..100) {
6431: sleep 2;
6432: if (-e $replyfile.'.end') {
6433: if (open(my $fh,$replyfile)) {
6434: $reply = join('',<$fh>);
6435: close($fh);
6436: } else { return 'error: reply_file_error'; }
6437: return &unescape($reply);
6438: }
6439: }
6440: return 'timeout:'.$queryid;
6441: }
6442:
6443: sub courselog_query {
6444: #
6445: # possible filters:
6446: # url: url or symb
6447: # username
6448: # domain
6449: # action: view, submit, grade
6450: # start: timestamp
6451: # end: timestamp
6452: #
6453: my (%filters)=@_;
6454: unless ($env{'request.course.id'}) { return 'no_course'; }
6455: if ($filters{'url'}) {
6456: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6457: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6458: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6459: }
6460: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6461: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6462: return &log_query($cname,$cdom,'courselog',%filters);
6463: }
6464:
6465: sub userlog_query {
6466: #
6467: # possible filters:
6468: # action: log check role
6469: # start: timestamp
6470: # end: timestamp
6471: #
6472: my ($uname,$udom,%filters)=@_;
6473: return &log_query($uname,$udom,'userlog',%filters);
6474: }
6475:
6476: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6477:
6478: sub auto_run {
6479: my ($cnum,$cdom) = @_;
6480: my $response = 0;
6481: my $settings;
6482: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6483: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6484: $settings = $domconfig{'autoenroll'};
6485: if ($settings->{'run'} eq '1') {
6486: $response = 1;
6487: }
6488: } else {
6489: my $homeserver;
6490: if (&is_course($cdom,$cnum)) {
6491: $homeserver = &homeserver($cnum,$cdom);
6492: } else {
6493: $homeserver = &domain($cdom,'primary');
6494: }
6495: if ($homeserver ne 'no_host') {
6496: $response = &reply('autorun:'.$cdom,$homeserver);
6497: }
6498: }
6499: return $response;
6500: }
6501:
6502: sub auto_get_sections {
6503: my ($cnum,$cdom,$inst_coursecode) = @_;
6504: my $homeserver;
6505: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6506: $homeserver = &homeserver($cnum,$cdom);
6507: }
6508: if (!defined($homeserver)) {
6509: if ($cdom =~ /^$match_domain$/) {
6510: $homeserver = &domain($cdom,'primary');
6511: }
6512: }
6513: my @secs;
6514: if (defined($homeserver)) {
6515: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6516: unless ($response eq 'refused') {
6517: @secs = split(/:/,$response);
6518: }
6519: }
6520: return @secs;
6521: }
6522:
6523: sub auto_new_course {
6524: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6525: my $homeserver = &homeserver($cnum,$cdom);
6526: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6527: return $response;
6528: }
6529:
6530: sub auto_validate_courseID {
6531: my ($cnum,$cdom,$inst_course_id) = @_;
6532: my $homeserver = &homeserver($cnum,$cdom);
6533: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6534: return $response;
6535: }
6536:
6537: sub auto_validate_instcode {
6538: my ($cnum,$cdom,$instcode,$owner) = @_;
6539: my ($homeserver,$response);
6540: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6541: $homeserver = &homeserver($cnum,$cdom);
6542: }
6543: if (!defined($homeserver)) {
6544: if ($cdom =~ /^$match_domain$/) {
6545: $homeserver = &domain($cdom,'primary');
6546: }
6547: }
6548: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6549: &escape($instcode).':'.&escape($owner),$homeserver));
6550: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6551: return ($outcome,$description);
6552: }
6553:
6554: sub auto_create_password {
6555: my ($cnum,$cdom,$authparam,$udom) = @_;
6556: my ($homeserver,$response);
6557: my $create_passwd = 0;
6558: my $authchk = '';
6559: if ($udom =~ /^$match_domain$/) {
6560: $homeserver = &domain($udom,'primary');
6561: }
6562: if ($homeserver eq '') {
6563: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6564: $homeserver = &homeserver($cnum,$cdom);
6565: }
6566: }
6567: if ($homeserver eq '') {
6568: $authchk = 'nodomain';
6569: } else {
6570: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6571: if ($response eq 'refused') {
6572: $authchk = 'refused';
6573: } else {
6574: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6575: }
6576: }
6577: return ($authparam,$create_passwd,$authchk);
6578: }
6579:
6580: sub auto_photo_permission {
6581: my ($cnum,$cdom,$students) = @_;
6582: my $homeserver = &homeserver($cnum,$cdom);
6583: my ($outcome,$perm_reqd,$conditions) =
6584: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6585: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6586: return (undef,undef);
6587: }
6588: return ($outcome,$perm_reqd,$conditions);
6589: }
6590:
6591: sub auto_checkphotos {
6592: my ($uname,$udom,$pid) = @_;
6593: my $homeserver = &homeserver($uname,$udom);
6594: my ($result,$resulttype);
6595: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6596: &escape($uname).':'.&escape($pid),
6597: $homeserver));
6598: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6599: return (undef,undef);
6600: }
6601: if ($outcome) {
6602: ($result,$resulttype) = split(/:/,$outcome);
6603: }
6604: return ($result,$resulttype);
6605: }
6606:
6607: sub auto_photochoice {
6608: my ($cnum,$cdom) = @_;
6609: my $homeserver = &homeserver($cnum,$cdom);
6610: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6611: &escape($cdom),
6612: $homeserver)));
6613: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6614: return (undef,undef);
6615: }
6616: return ($update,$comment);
6617: }
6618:
6619: sub auto_photoupdate {
6620: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6621: my $homeserver = &homeserver($cnum,$dom);
6622: my $host=&hostname($homeserver);
6623: my $cmd = '';
6624: my $maxtries = 1;
6625: foreach my $affiliate (keys(%{$affiliatesref})) {
6626: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6627: }
6628: $cmd =~ s/%%$//;
6629: $cmd = &escape($cmd);
6630: my $query = 'institutionalphotos';
6631: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6632: unless ($queryid=~/^\Q$host\E\_/) {
6633: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6634: return 'error: '.$queryid;
6635: }
6636: my $reply = &get_query_reply($queryid);
6637: my $tries = 1;
6638: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6639: $reply = &get_query_reply($queryid);
6640: $tries ++;
6641: }
6642: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6643: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6644: } else {
6645: my @responses = split(/:/,$reply);
6646: my $outcome = shift(@responses);
6647: foreach my $item (@responses) {
6648: my ($key,$value) = split(/=/,$item);
6649: $$photo{$key} = $value;
6650: }
6651: return $outcome;
6652: }
6653: return 'error';
6654: }
6655:
6656: sub auto_instcode_format {
6657: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6658: $cat_order) = @_;
6659: my $courses = '';
6660: my @homeservers;
6661: if ($caller eq 'global') {
6662: my %servers = &get_servers($codedom,'library');
6663: foreach my $tryserver (keys(%servers)) {
6664: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6665: push(@homeservers,$tryserver);
6666: }
6667: }
6668: } elsif ($caller eq 'requests') {
6669: if ($codedom =~ /^$match_domain$/) {
6670: my $chome = &domain($codedom,'primary');
6671: unless ($chome eq 'no_host') {
6672: push(@homeservers,$chome);
6673: }
6674: }
6675: } else {
6676: push(@homeservers,&homeserver($caller,$codedom));
6677: }
6678: foreach my $code (keys(%{$instcodes})) {
6679: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
6680: }
6681: chop($courses);
6682: my $ok_response = 0;
6683: my $response;
6684: while (@homeservers > 0 && $ok_response == 0) {
6685: my $server = shift(@homeservers);
6686: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6687: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6688: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
6689: split(/:/,$response);
6690: %{$codes} = (%{$codes},&str2hash($codes_str));
6691: push(@{$codetitles},&str2array($codetitles_str));
6692: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6693: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6694: $ok_response = 1;
6695: }
6696: }
6697: if ($ok_response) {
6698: return 'ok';
6699: } else {
6700: return $response;
6701: }
6702: }
6703:
6704: sub auto_instcode_defaults {
6705: my ($domain,$returnhash,$code_order) = @_;
6706: my @homeservers;
6707:
6708: my %servers = &get_servers($domain,'library');
6709: foreach my $tryserver (keys(%servers)) {
6710: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6711: push(@homeservers,$tryserver);
6712: }
6713: }
6714:
6715: my $response;
6716: foreach my $server (@homeservers) {
6717: $response=&reply('autoinstcodedefaults:'.$domain,$server);
6718: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6719:
6720: foreach my $pair (split(/\&/,$response)) {
6721: my ($name,$value)=split(/\=/,$pair);
6722: if ($name eq 'code_order') {
6723: @{$code_order} = split(/\&/,&unescape($value));
6724: } else {
6725: $returnhash->{&unescape($name)}=&unescape($value);
6726: }
6727: }
6728: return 'ok';
6729: }
6730:
6731: return $response;
6732: }
6733:
6734: sub auto_possible_instcodes {
6735: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6736: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6737: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6738: return;
6739: }
6740: my (@homeservers,$uhome);
6741: if (defined(&domain($domain,'primary'))) {
6742: $uhome=&domain($domain,'primary');
6743: push(@homeservers,&domain($domain,'primary'));
6744: } else {
6745: my %servers = &get_servers($domain,'library');
6746: foreach my $tryserver (keys(%servers)) {
6747: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6748: push(@homeservers,$tryserver);
6749: }
6750: }
6751: }
6752: my $response;
6753: foreach my $server (@homeservers) {
6754: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6755: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6756: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6757: split(':',$response);
6758: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6759: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
6760: foreach my $item (split('&',$cat_title)) {
6761: my ($name,$value)=split('=',$item);
6762: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
6763: }
6764: foreach my $item (split('&',$cat_order)) {
6765: my ($name,$value)=split('=',$item);
6766: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
6767: }
6768: return 'ok';
6769: }
6770: return $response;
6771: }
6772:
6773: sub auto_courserequest_checks {
6774: my ($dom) = @_;
6775: my ($homeserver,%validations);
6776: if ($dom =~ /^$match_domain$/) {
6777: $homeserver = &domain($dom,'primary');
6778: }
6779: unless ($homeserver eq 'no_host') {
6780: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6781: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6782: my @items = split(/&/,$response);
6783: foreach my $item (@items) {
6784: my ($key,$value) = split('=',$item);
6785: $validations{&unescape($key)} = &thaw_unescape($value);
6786: }
6787: }
6788: }
6789: return %validations;
6790: }
6791:
6792: sub auto_courserequest_validation {
6793: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6794: my ($homeserver,$response);
6795: if ($dom =~ /^$match_domain$/) {
6796: $homeserver = &domain($dom,'primary');
6797: }
6798: unless ($homeserver eq 'no_host') {
6799:
6800: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
6801: ':'.&escape($crstype).':'.&escape($inststatuslist).
6802: ':'.&escape($instcode).':'.&escape($instseclist),
6803: $homeserver));
6804: }
6805: return $response;
6806: }
6807:
6808: sub auto_validate_class_sec {
6809: my ($cdom,$cnum,$owners,$inst_class) = @_;
6810: my $homeserver = &homeserver($cnum,$cdom);
6811: my $ownerlist;
6812: if (ref($owners) eq 'ARRAY') {
6813: $ownerlist = join(',',@{$owners});
6814: } else {
6815: $ownerlist = $owners;
6816: }
6817: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
6818: &escape($ownerlist).':'.$cdom,$homeserver);
6819: return $response;
6820: }
6821:
6822: # ------------------------------------------------------- Course Group routines
6823:
6824: sub get_coursegroups {
6825: my ($cdom,$cnum,$group,$namespace) = @_;
6826: return(&dump($namespace,$cdom,$cnum,$group));
6827: }
6828:
6829: sub modify_coursegroup {
6830: my ($cdom,$cnum,$groupsettings) = @_;
6831: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6832: }
6833:
6834: sub toggle_coursegroup_status {
6835: my ($cdom,$cnum,$group,$action) = @_;
6836: my ($from_namespace,$to_namespace);
6837: if ($action eq 'delete') {
6838: $from_namespace = 'coursegroups';
6839: $to_namespace = 'deleted_groups';
6840: } else {
6841: $from_namespace = 'deleted_groups';
6842: $to_namespace = 'coursegroups';
6843: }
6844: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
6845: if (my $tmp = &error(%curr_group)) {
6846: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6847: return ('read error',$tmp);
6848: } else {
6849: my %savedsettings = %curr_group;
6850: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
6851: my $deloutcome;
6852: if ($result eq 'ok') {
6853: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
6854: } else {
6855: return ('write error',$result);
6856: }
6857: if ($deloutcome eq 'ok') {
6858: return 'ok';
6859: } else {
6860: return ('delete error',$deloutcome);
6861: }
6862: }
6863: }
6864:
6865: sub modify_group_roles {
6866: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
6867: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6868: my $role = 'gr/'.&escape($userprivs);
6869: my ($uname,$udom) = split(/:/,$user);
6870: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
6871: if ($result eq 'ok') {
6872: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6873: }
6874: return $result;
6875: }
6876:
6877: sub modify_coursegroup_membership {
6878: my ($cdom,$cnum,$membership) = @_;
6879: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6880: return $result;
6881: }
6882:
6883: sub get_active_groups {
6884: my ($udom,$uname,$cdom,$cnum) = @_;
6885: my $now = time;
6886: my %groups = ();
6887: foreach my $key (keys(%env)) {
6888: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
6889: my ($start,$end) = split(/\./,$env{$key});
6890: if (($end!=0) && ($end<$now)) { next; }
6891: if (($start!=0) && ($start>$now)) { next; }
6892: if ($1 eq $cdom && $2 eq $cnum) {
6893: $groups{$3} = $env{$key} ;
6894: }
6895: }
6896: }
6897: return %groups;
6898: }
6899:
6900: sub get_group_membership {
6901: my ($cdom,$cnum,$group) = @_;
6902: return(&dump('groupmembership',$cdom,$cnum,$group));
6903: }
6904:
6905: sub get_users_groups {
6906: my ($udom,$uname,$courseid) = @_;
6907: my @usersgroups;
6908: my $cachetime=1800;
6909:
6910: my $hashid="$udom:$uname:$courseid";
6911: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6912: if (defined($cached)) {
6913: @usersgroups = split(/:/,$grouplist);
6914: } else {
6915: $grouplist = '';
6916: my $courseurl = &courseid_to_courseurl($courseid);
6917: my $extra = &freeze_escape({'skipcheck' => 1});
6918: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
6919: my $access_end = $env{'course.'.$courseid.
6920: '.default_enrollment_end_date'};
6921: my $now = time;
6922: foreach my $key (keys(%roleshash)) {
6923: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6924: my $group = $1;
6925: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6926: my $start = $2;
6927: my $end = $1;
6928: if ($start == -1) { next; } # deleted from group
6929: if (($start!=0) && ($start>$now)) { next; }
6930: if (($end!=0) && ($end<$now)) {
6931: if ($access_end && $access_end < $now) {
6932: if ($access_end - $end < 86400) {
6933: push(@usersgroups,$group);
6934: }
6935: }
6936: next;
6937: }
6938: push(@usersgroups,$group);
6939: }
6940: }
6941: }
6942: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6943: $grouplist = join(':',@usersgroups);
6944: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6945: }
6946: return @usersgroups;
6947: }
6948:
6949: sub devalidate_getgroups_cache {
6950: my ($udom,$uname,$cdom,$cnum)=@_;
6951: my $courseid = $cdom.'_'.$cnum;
6952:
6953: my $hashid="$udom:$uname:$courseid";
6954: &devalidate_cache_new('getgroups',$hashid);
6955: }
6956:
6957: # ------------------------------------------------------------------ Plain Text
6958:
6959: sub plaintext {
6960: my ($short,$type,$cid,$forcedefault) = @_;
6961: if ($short =~ m{^cr/}) {
6962: return (split('/',$short))[-1];
6963: }
6964: if (!defined($cid)) {
6965: $cid = $env{'request.course.id'};
6966: }
6967: my %rolenames = (
6968: Course => 'std',
6969: Community => 'alt1',
6970: );
6971: if ($cid ne '') {
6972: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6973: unless ($forcedefault) {
6974: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6975: &Apache::lonlocal::mt_escape(\$roletext);
6976: return &Apache::lonlocal::mt($roletext);
6977: }
6978: }
6979: }
6980: if ((defined($type)) && (defined($rolenames{$type})) &&
6981: (defined($rolenames{$type})) &&
6982: (defined($prp{$short}{$rolenames{$type}}))) {
6983: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6984: } elsif ($cid ne '') {
6985: my $crstype = $env{'course.'.$cid.'.type'};
6986: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6987: (defined($prp{$short}{$rolenames{$crstype}}))) {
6988: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6989: }
6990: }
6991: return &Apache::lonlocal::mt($prp{$short}{'std'});
6992: }
6993:
6994: # ----------------------------------------------------------------- Assign Role
6995:
6996: sub assignrole {
6997: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6998: $context)=@_;
6999: my $mrole;
7000: if ($role =~ /^cr\//) {
7001: my $cwosec=$url;
7002: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7003: unless (&allowed('ccr',$cwosec)) {
7004: my $refused = 1;
7005: if ($context eq 'requestcourses') {
7006: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7007: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7008: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7009: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7010: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7011: if ($crsenv{'internal.courseowner'} eq
7012: $env{'user.name'}.':'.$env{'user.domain'}) {
7013: $refused = '';
7014: }
7015: }
7016: }
7017: }
7018: }
7019: if ($refused) {
7020: &logthis('Refused custom assignrole: '.
7021: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7022: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7023: return 'refused';
7024: }
7025: }
7026: $mrole='cr';
7027: } elsif ($role =~ /^gr\//) {
7028: my $cwogrp=$url;
7029: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7030: unless (&allowed('mdg',$cwogrp)) {
7031: &logthis('Refused group assignrole: '.
7032: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7033: $env{'user.name'}.' at '.$env{'user.domain'});
7034: return 'refused';
7035: }
7036: $mrole='gr';
7037: } else {
7038: my $cwosec=$url;
7039: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7040: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7041: my $refused;
7042: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7043: if (!(&allowed('c'.$role,$url))) {
7044: $refused = 1;
7045: }
7046: } else {
7047: $refused = 1;
7048: }
7049: if ($refused) {
7050: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7051: if (!$selfenroll && $context eq 'course') {
7052: my %crsenv;
7053: if ($role eq 'cc' || $role eq 'co') {
7054: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7055: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7056: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7057: if ($crsenv{'internal.courseowner'} eq
7058: $env{'user.name'}.':'.$env{'user.domain'}) {
7059: $refused = '';
7060: }
7061: }
7062: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7063: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7064: if ($crsenv{'internal.courseowner'} eq
7065: $env{'user.name'}.':'.$env{'user.domain'}) {
7066: $refused = '';
7067: }
7068: }
7069: }
7070: }
7071: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7072: $refused = '';
7073: } elsif ($context eq 'requestcourses') {
7074: my @possroles = ('st','ta','ep','in','cc','co');
7075: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7076: my $wrongcc;
7077: if ($cnum =~ /^$match_community$/) {
7078: $wrongcc = 1 if ($role eq 'cc');
7079: } else {
7080: $wrongcc = 1 if ($role eq 'co');
7081: }
7082: unless ($wrongcc) {
7083: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7084: if ($crsenv{'internal.courseowner'} eq
7085: $env{'user.name'}.':'.$env{'user.domain'}) {
7086: $refused = '';
7087: }
7088: }
7089: }
7090: }
7091: if ($refused) {
7092: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7093: ' '.$role.' '.$end.' '.$start.' by '.
7094: $env{'user.name'}.' at '.$env{'user.domain'});
7095: return 'refused';
7096: }
7097: }
7098: } elsif ($role eq 'au') {
7099: if ($url ne '/'.$udom.'/') {
7100: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7101: ' to assign author role for '.$uname.':'.$udom.
7102: ' in domain: '.$url.' refused (wrong domain).');
7103: return 'refused';
7104: }
7105: }
7106: $mrole=$role;
7107: }
7108: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7109: "$udom:$uname:$url".'_'."$mrole=$role";
7110: if ($end) { $command.='_'.$end; }
7111: if ($start) {
7112: if ($end) {
7113: $command.='_'.$start;
7114: } else {
7115: $command.='_0_'.$start;
7116: }
7117: }
7118: my $origstart = $start;
7119: my $origend = $end;
7120: my $delflag;
7121: # actually delete
7122: if ($deleteflag) {
7123: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7124: # modify command to delete the role
7125: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7126: "$udom:$uname:$url".'_'."$mrole";
7127: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7128: # set start and finish to negative values for userrolelog
7129: $start=-1;
7130: $end=-1;
7131: $delflag = 1;
7132: }
7133: }
7134: # send command
7135: my $answer=&reply($command,&homeserver($uname,$udom));
7136: # log new user role if status is ok
7137: if ($answer eq 'ok') {
7138: &userrolelog($role,$uname,$udom,$url,$start,$end);
7139: # for course roles, perform group memberships changes triggered by role change.
7140: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7141: unless ($role =~ /^gr/) {
7142: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7143: $origstart,$selfenroll,$context);
7144: }
7145: if ($role eq 'cc') {
7146: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7147: }
7148: }
7149: return $answer;
7150: }
7151:
7152: sub autoupdate_coowners {
7153: my ($url,$end,$start,$uname,$udom) = @_;
7154: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7155: if (($cdom ne '') && ($cnum ne '')) {
7156: my $now = time;
7157: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7158: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7159: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7160: my $instcode = $coursehash{'internal.coursecode'};
7161: if ($instcode ne '') {
7162: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7163: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7164: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7165: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7166: if ($result eq 'valid') {
7167: if ($coursehash{'internal.co-owners'}) {
7168: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7169: push(@newcoowners,$coowner);
7170: }
7171: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7172: push(@newcoowners,$uname.':'.$udom);
7173: }
7174: @newcoowners = sort(@newcoowners);
7175: } else {
7176: push(@newcoowners,$uname.':'.$udom);
7177: }
7178: } else {
7179: if ($coursehash{'internal.co-owners'}) {
7180: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7181: unless ($coowner eq $uname.':'.$udom) {
7182: push(@newcoowners,$coowner);
7183: }
7184: }
7185: unless (@newcoowners > 0) {
7186: $delcoowners = 1;
7187: $coowners = '';
7188: }
7189: }
7190: }
7191: if (@newcoowners || $delcoowners) {
7192: &store_coowners($cdom,$cnum,$coursehash{'home'},
7193: $delcoowners,@newcoowners);
7194: }
7195: }
7196: }
7197: }
7198: }
7199: }
7200: }
7201:
7202: sub store_coowners {
7203: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7204: my $cid = $cdom.'_'.$cnum;
7205: my ($coowners,$delresult,$putresult);
7206: if (@newcoowners) {
7207: $coowners = join(',',@newcoowners);
7208: my %coownershash = (
7209: 'internal.co-owners' => $coowners,
7210: );
7211: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7212: if ($putresult eq 'ok') {
7213: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7214: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7215: }
7216: }
7217: }
7218: if ($delcoowners) {
7219: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7220: if ($delresult eq 'ok') {
7221: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7222: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7223: }
7224: }
7225: }
7226: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7227: my %crsinfo =
7228: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7229: if (ref($crsinfo{$cid}) eq 'HASH') {
7230: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7231: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7232: }
7233: }
7234: }
7235:
7236: # -------------------------------------------------- Modify user authentication
7237: # Overrides without validation
7238:
7239: sub modifyuserauth {
7240: my ($udom,$uname,$umode,$upass)=@_;
7241: my $uhome=&homeserver($uname,$udom);
7242: unless (&allowed('mau',$udom)) { return 'refused'; }
7243: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7244: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7245: ' in domain '.$env{'request.role.domain'});
7246: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7247: &escape($upass),$uhome);
7248: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7249: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7250: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7251: &log($udom,,$uname,$uhome,
7252: 'Authentication changed by '.$env{'user.domain'}.', '.
7253: $env{'user.name'}.', '.$umode.
7254: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7255: unless ($reply eq 'ok') {
7256: &logthis('Authentication mode error: '.$reply);
7257: return 'error: '.$reply;
7258: }
7259: return 'ok';
7260: }
7261:
7262: # --------------------------------------------------------------- Modify a user
7263:
7264: sub modifyuser {
7265: my ($udom, $uname, $uid,
7266: $umode, $upass, $first,
7267: $middle, $last, $gene,
7268: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7269: $udom= &LONCAPA::clean_domain($udom);
7270: $uname=&LONCAPA::clean_username($uname);
7271: my $showcandelete = 'none';
7272: if (ref($candelete) eq 'ARRAY') {
7273: if (@{$candelete} > 0) {
7274: $showcandelete = join(', ',@{$candelete});
7275: }
7276: }
7277: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7278: $umode.', '.$first.', '.$middle.', '.
7279: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7280: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7281: ' desiredhome not specified').
7282: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7283: ' in domain '.$env{'request.role.domain'});
7284: my $uhome=&homeserver($uname,$udom,'true');
7285: my $newuser;
7286: if ($uhome eq 'no_host') {
7287: $newuser = 1;
7288: }
7289: # ----------------------------------------------------------------- Create User
7290: if (($uhome eq 'no_host') &&
7291: (($umode && $upass) || ($umode eq 'localauth'))) {
7292: my $unhome='';
7293: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7294: $unhome = $desiredhome;
7295: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7296: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7297: } else { # load balancing routine for determining $unhome
7298: my $loadm=10000000;
7299: my %servers = &get_servers($udom,'library');
7300: foreach my $tryserver (keys(%servers)) {
7301: my $answer=reply('load',$tryserver);
7302: if (($answer=~/\d+/) && ($answer<$loadm)) {
7303: $loadm=$answer;
7304: $unhome=$tryserver;
7305: }
7306: }
7307: }
7308: if (($unhome eq '') || ($unhome eq 'no_host')) {
7309: return 'error: unable to find a home server for '.$uname.
7310: ' in domain '.$udom;
7311: }
7312: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7313: &escape($upass),$unhome);
7314: unless ($reply eq 'ok') {
7315: return 'error: '.$reply;
7316: }
7317: $uhome=&homeserver($uname,$udom,'true');
7318: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7319: return 'error: unable verify users home machine.';
7320: }
7321: } # End of creation of new user
7322: # ---------------------------------------------------------------------- Add ID
7323: if ($uid) {
7324: $uid=~tr/A-Z/a-z/;
7325: my %uidhash=&idrget($udom,$uname);
7326: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7327: && (!$forceid)) {
7328: unless ($uid eq $uidhash{$uname}) {
7329: return 'error: user id "'.$uid.'" does not match '.
7330: 'current user id "'.$uidhash{$uname}.'".';
7331: }
7332: } else {
7333: &idput($udom,($uname => $uid));
7334: }
7335: }
7336: # -------------------------------------------------------------- Add names, etc
7337: my @tmp=&get('environment',
7338: ['firstname','middlename','lastname','generation','id',
7339: 'permanentemail','inststatus'],
7340: $udom,$uname);
7341: my (%names,%oldnames);
7342: if ($tmp[0] =~ m/^error:.*/) {
7343: %names=();
7344: } else {
7345: %names = @tmp;
7346: %oldnames = %names;
7347: }
7348: #
7349: # If name, email and/or uid are blank (e.g., because an uploaded file
7350: # of users did not contain them), do not overwrite existing values
7351: # unless field is in $candelete array ref.
7352: #
7353:
7354: my @fields = ('firstname','middlename','lastname','generation',
7355: 'permanentemail','id');
7356: my %newvalues;
7357: if (ref($candelete) eq 'ARRAY') {
7358: foreach my $field (@fields) {
7359: if (grep(/^\Q$field\E$/,@{$candelete})) {
7360: if ($field eq 'firstname') {
7361: $names{$field} = $first;
7362: } elsif ($field eq 'middlename') {
7363: $names{$field} = $middle;
7364: } elsif ($field eq 'lastname') {
7365: $names{$field} = $last;
7366: } elsif ($field eq 'generation') {
7367: $names{$field} = $gene;
7368: } elsif ($field eq 'permanentemail') {
7369: $names{$field} = $email;
7370: } elsif ($field eq 'id') {
7371: $names{$field} = $uid;
7372: }
7373: }
7374: }
7375: }
7376: if ($first) { $names{'firstname'} = $first; }
7377: if (defined($middle)) { $names{'middlename'} = $middle; }
7378: if ($last) { $names{'lastname'} = $last; }
7379: if (defined($gene)) { $names{'generation'} = $gene; }
7380: if ($email) {
7381: $email=~s/[^\w\@\.\-\,]//gs;
7382: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7383: }
7384: if ($uid) { $names{'id'} = $uid; }
7385: if (defined($inststatus)) {
7386: $names{'inststatus'} = '';
7387: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7388: if (ref($usertypes) eq 'HASH') {
7389: my @okstatuses;
7390: foreach my $item (split(/:/,$inststatus)) {
7391: if (defined($usertypes->{$item})) {
7392: push(@okstatuses,$item);
7393: }
7394: }
7395: if (@okstatuses) {
7396: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7397: }
7398: }
7399: }
7400: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7401: $umode.', '.$first.', '.$middle.', '.
7402: $last.', '.$gene.', '.$email.', '.$inststatus;
7403: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7404: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7405: } else {
7406: $logmsg .= ' during self creation';
7407: }
7408: my $changed;
7409: if ($newuser) {
7410: $changed = 1;
7411: } else {
7412: foreach my $field (@fields) {
7413: if ($names{$field} ne $oldnames{$field}) {
7414: $changed = 1;
7415: last;
7416: }
7417: }
7418: }
7419: unless ($changed) {
7420: $logmsg = 'No changes in user information needed for: '.$logmsg;
7421: &logthis($logmsg);
7422: return 'ok';
7423: }
7424: my $reply = &put('environment', \%names, $udom,$uname);
7425: if ($reply ne 'ok') {
7426: return 'error: '.$reply;
7427: }
7428: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7429: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7430: }
7431: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7432: &devalidate_cache_new('namescache',$uname.':'.$udom);
7433: $logmsg = 'Success modifying user '.$logmsg;
7434: &logthis($logmsg);
7435: return 'ok';
7436: }
7437:
7438: # -------------------------------------------------------------- Modify student
7439:
7440: sub modifystudent {
7441: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7442: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7443: $selfenroll,$context,$inststatus)=@_;
7444: if (!$cid) {
7445: unless ($cid=$env{'request.course.id'}) {
7446: return 'not_in_class';
7447: }
7448: }
7449: # --------------------------------------------------------------- Make the user
7450: my $reply=&modifyuser
7451: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7452: $desiredhome,$email,$inststatus);
7453: unless ($reply eq 'ok') { return $reply; }
7454: # This will cause &modify_student_enrollment to get the uid from the
7455: # students environment
7456: $uid = undef if (!$forceid);
7457: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7458: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7459: return $reply;
7460: }
7461:
7462: sub modify_student_enrollment {
7463: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7464: my ($cdom,$cnum,$chome);
7465: if (!$cid) {
7466: unless ($cid=$env{'request.course.id'}) {
7467: return 'not_in_class';
7468: }
7469: $cdom=$env{'course.'.$cid.'.domain'};
7470: $cnum=$env{'course.'.$cid.'.num'};
7471: } else {
7472: ($cdom,$cnum)=split(/_/,$cid);
7473: }
7474: $chome=$env{'course.'.$cid.'.home'};
7475: if (!$chome) {
7476: $chome=&homeserver($cnum,$cdom);
7477: }
7478: if (!$chome) { return 'unknown_course'; }
7479: # Make sure the user exists
7480: my $uhome=&homeserver($uname,$udom);
7481: if (($uhome eq '') || ($uhome eq 'no_host')) {
7482: return 'error: no such user';
7483: }
7484: # Get student data if we were not given enough information
7485: if (!defined($first) || $first eq '' ||
7486: !defined($last) || $last eq '' ||
7487: !defined($uid) || $uid eq '' ||
7488: !defined($middle) || $middle eq '' ||
7489: !defined($gene) || $gene eq '') {
7490: # They did not supply us with enough data to enroll the student, so
7491: # we need to pick up more information.
7492: my %tmp = &get('environment',
7493: ['firstname','middlename','lastname', 'generation','id']
7494: ,$udom,$uname);
7495:
7496: #foreach my $key (keys(%tmp)) {
7497: # &logthis("key $key = ".$tmp{$key});
7498: #}
7499: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7500: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7501: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7502: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7503: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7504: }
7505: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7506: my $reply=cput('classlist',
7507: {"$uname:$udom" =>
7508: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7509: $cdom,$cnum);
7510: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7511: return 'error: '.$reply;
7512: } else {
7513: &devalidate_getsection_cache($udom,$uname,$cid);
7514: }
7515: # Add student role to user
7516: my $uurl='/'.$cid;
7517: $uurl=~s/\_/\//g;
7518: if ($usec) {
7519: $uurl.='/'.$usec;
7520: }
7521: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
7522: }
7523:
7524: sub format_name {
7525: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7526: my $name;
7527: if ($first ne 'lastname') {
7528: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7529: } else {
7530: if ($lastname=~/\S/) {
7531: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7532: $name=~s/\s+,/,/;
7533: } else {
7534: $name.= $firstname.' '.$middlename.' '.$generation;
7535: }
7536: }
7537: $name=~s/^\s+//;
7538: $name=~s/\s+$//;
7539: $name=~s/\s+/ /g;
7540: return $name;
7541: }
7542:
7543: # ------------------------------------------------- Write to course preferences
7544:
7545: sub writecoursepref {
7546: my ($courseid,%prefs)=@_;
7547: $courseid=~s/^\///;
7548: $courseid=~s/\_/\//g;
7549: my ($cdomain,$cnum)=split(/\//,$courseid);
7550: my $chome=homeserver($cnum,$cdomain);
7551: if (($chome eq '') || ($chome eq 'no_host')) {
7552: return 'error: no such course';
7553: }
7554: my $cstring='';
7555: foreach my $pref (keys(%prefs)) {
7556: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7557: }
7558: $cstring=~s/\&$//;
7559: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7560: }
7561:
7562: # ---------------------------------------------------------- Make/modify course
7563:
7564: sub createcourse {
7565: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7566: $course_owner,$crstype,$cnum,$context,$category)=@_;
7567: $url=&declutter($url);
7568: my $cid='';
7569: if ($context eq 'requestcourses') {
7570: my $can_create = 0;
7571: my ($ownername,$ownerdom) = split(':',$course_owner);
7572: if ($udom eq $ownerdom) {
7573: if (&usertools_access($ownername,$ownerdom,$category,undef,
7574: $context)) {
7575: $can_create = 1;
7576: }
7577: } else {
7578: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7579: $category);
7580: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7581: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7582: if (@curr > 0) {
7583: my @options = qw(approval validate autolimit);
7584: my $optregex = join('|',@options);
7585: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7586: $can_create = 1;
7587: }
7588: }
7589: }
7590: }
7591: if ($can_create) {
7592: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7593: unless (&allowed('ccc',$udom)) {
7594: return 'refused';
7595: }
7596: }
7597: } else {
7598: return 'refused';
7599: }
7600: } elsif (!&allowed('ccc',$udom)) {
7601: return 'refused';
7602: }
7603: # --------------------------------------------------------------- Get Unique ID
7604: my $uname;
7605: if ($cnum =~ /^$match_courseid$/) {
7606: my $chome=&homeserver($cnum,$udom,'true');
7607: if (($chome eq '') || ($chome eq 'no_host')) {
7608: $uname = $cnum;
7609: } else {
7610: $uname = &generate_coursenum($udom,$crstype);
7611: }
7612: } else {
7613: $uname = &generate_coursenum($udom,$crstype);
7614: }
7615: return $uname if ($uname =~ /^error/);
7616: # -------------------------------------------------- Check supplied server name
7617: if (!defined($course_server)) {
7618: if (defined(&domain($udom,'primary'))) {
7619: $course_server = &domain($udom,'primary');
7620: } else {
7621: $course_server = $env{'user.home'};
7622: }
7623: }
7624: my %host_servers =
7625: &Apache::lonnet::get_servers($udom,'library');
7626: unless ($host_servers{$course_server}) {
7627: return 'error: invalid home server for course: '.$course_server;
7628: }
7629: # ------------------------------------------------------------- Make the course
7630: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
7631: $course_server);
7632: unless ($reply eq 'ok') { return 'error: '.$reply; }
7633: my $uhome=&homeserver($uname,$udom,'true');
7634: if (($uhome eq '') || ($uhome eq 'no_host')) {
7635: return 'error: no such course';
7636: }
7637: # ----------------------------------------------------------------- Course made
7638: # log existence
7639: my $now = time;
7640: my $newcourse = {
7641: $udom.'_'.$uname => {
7642: description => $description,
7643: inst_code => $inst_code,
7644: owner => $course_owner,
7645: type => $crstype,
7646: creator => $env{'user.name'}.':'.
7647: $env{'user.domain'},
7648: created => $now,
7649: context => $context,
7650: },
7651: };
7652: &courseidput($udom,$newcourse,$uhome,'notime');
7653: # set toplevel url
7654: my $topurl=$url;
7655: unless ($nonstandard) {
7656: # ------------------------------------------ For standard courses, make top url
7657: my $mapurl=&clutter($url);
7658: if ($mapurl eq '/res/') { $mapurl=''; }
7659: $env{'form.initmap'}=(<<ENDINITMAP);
7660: <map>
7661: <resource id="1" type="start"></resource>
7662: <resource id="2" src="$mapurl"></resource>
7663: <resource id="3" type="finish"></resource>
7664: <link index="1" from="1" to="2"></link>
7665: <link index="2" from="2" to="3"></link>
7666: </map>
7667: ENDINITMAP
7668: $topurl=&declutter(
7669: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
7670: );
7671: }
7672: # ----------------------------------------------------------- Write preferences
7673: &writecoursepref($udom.'_'.$uname,
7674: ('description' => $description,
7675: 'url' => $topurl,
7676: 'internal.creator' => $env{'user.name'}.':'.
7677: $env{'user.domain'},
7678: 'internal.created' => $now,
7679: 'internal.creationcontext' => $context)
7680: );
7681: return '/'.$udom.'/'.$uname;
7682: }
7683:
7684: # ------------------------------------------------------------------- Create ID
7685: sub generate_coursenum {
7686: my ($udom,$crstype) = @_;
7687: my $domdesc = &domain($udom);
7688: return 'error: invalid domain' if ($domdesc eq '');
7689: my $first;
7690: if ($crstype eq 'Community') {
7691: $first = '0';
7692: } else {
7693: $first = int(1+rand(9));
7694: }
7695: my $uname=$first.
7696: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7697: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7698: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7699: # ----------------------------------------------- Make sure that does not exist
7700: my $uhome=&homeserver($uname,$udom,'true');
7701: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7702: if ($crstype eq 'Community') {
7703: $first = '0';
7704: } else {
7705: $first = int(1+rand(9));
7706: }
7707: $uname=$first.
7708: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7709: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7710: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7711: $uhome=&homeserver($uname,$udom,'true');
7712: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7713: return 'error: unable to generate unique course-ID';
7714: }
7715: }
7716: return $uname;
7717: }
7718:
7719: sub is_course {
7720: my ($cdom,$cnum) = @_;
7721: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
7722: undef,'.');
7723: if (exists($courses{$cdom.'_'.$cnum})) {
7724: return 1;
7725: }
7726: return 0;
7727: }
7728:
7729: sub store_userdata {
7730: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
7731: my $result;
7732: if ($datakey ne '') {
7733: if (ref($storehash) eq 'HASH') {
7734: if ($udom eq '' || $uname eq '') {
7735: $udom = $env{'user.domain'};
7736: $uname = $env{'user.name'};
7737: }
7738: my $uhome=&homeserver($uname,$udom);
7739: if (($uhome eq '') || ($uhome eq 'no_host')) {
7740: $result = 'error: no_host';
7741: } else {
7742: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7743: $storehash->{'host'} = $perlvar{'lonHostID'};
7744:
7745: my $namevalue='';
7746: foreach my $key (keys(%{$storehash})) {
7747: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7748: }
7749: $namevalue=~s/\&$//;
7750: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7751: $namevalue,$uhome);
7752: }
7753: } else {
7754: $result = 'error: data to store was not a hash reference';
7755: }
7756: } else {
7757: $result= 'error: invalid requestkey';
7758: }
7759: return $result;
7760: }
7761:
7762: # ---------------------------------------------------------- Assign Custom Role
7763:
7764: sub assigncustomrole {
7765: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
7766: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
7767: $end,$start,$deleteflag,$selfenroll,$context);
7768: }
7769:
7770: # ----------------------------------------------------------------- Revoke Role
7771:
7772: sub revokerole {
7773: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
7774: my $now=time;
7775: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
7776: }
7777:
7778: # ---------------------------------------------------------- Revoke Custom Role
7779:
7780: sub revokecustomrole {
7781: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
7782: my $now=time;
7783: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
7784: $deleteflag,$selfenroll,$context);
7785: }
7786:
7787: # ------------------------------------------------------------ Disk usage
7788: sub diskusage {
7789: my ($udom,$uname,$directorypath,$getpropath)=@_;
7790: $directorypath =~ s/\/$//;
7791: my $listing=&reply('du2:'.&escape($directorypath).':'
7792: .&escape($getpropath).':'.&escape($uname).':'
7793: .&escape($udom),homeserver($uname,$udom));
7794: if ($listing eq 'unknown_cmd') {
7795: if ($getpropath) {
7796: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7797: }
7798: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7799: }
7800: return $listing;
7801: }
7802:
7803: sub is_locked {
7804: my ($file_name, $domain, $user, $which) = @_;
7805: my @check;
7806: my $is_locked;
7807: push (@check,$file_name);
7808: my %locked = &get('file_permissions',\@check,
7809: $env{'user.domain'},$env{'user.name'});
7810: my ($tmp)=keys(%locked);
7811: if ($tmp=~/^error:/) { undef(%locked); }
7812:
7813: if (ref($locked{$file_name}) eq 'ARRAY') {
7814: $is_locked = 'false';
7815: foreach my $entry (@{$locked{$file_name}}) {
7816: if (ref($entry) eq 'ARRAY') {
7817: $is_locked = 'true';
7818: if (ref($which) eq 'ARRAY') {
7819: push(@{$which},$entry);
7820: } else {
7821: last;
7822: }
7823: }
7824: }
7825: } else {
7826: $is_locked = 'false';
7827: }
7828: return $is_locked;
7829: }
7830:
7831: sub declutter_portfile {
7832: my ($file) = @_;
7833: $file =~ s{^(/portfolio/|portfolio/)}{/};
7834: return $file;
7835: }
7836:
7837: # ------------------------------------------------------------- Mark as Read Only
7838:
7839: sub mark_as_readonly {
7840: my ($domain,$user,$files,$what) = @_;
7841: my %current_permissions = &dump('file_permissions',$domain,$user);
7842: my ($tmp)=keys(%current_permissions);
7843: if ($tmp=~/^error:/) { undef(%current_permissions); }
7844: foreach my $file (@{$files}) {
7845: $file = &declutter_portfile($file);
7846: push(@{$current_permissions{$file}},$what);
7847: }
7848: &put('file_permissions',\%current_permissions,$domain,$user);
7849: return;
7850: }
7851:
7852: # ------------------------------------------------------------Save Selected Files
7853:
7854: sub save_selected_files {
7855: my ($user, $path, @files) = @_;
7856: my $filename = $user."savedfiles";
7857: my @other_files = &files_not_in_path($user, $path);
7858: open (OUT, '>'.$tmpdir.$filename);
7859: foreach my $file (@files) {
7860: print (OUT $env{'form.currentpath'}.$file."\n");
7861: }
7862: foreach my $file (@other_files) {
7863: print (OUT $file."\n");
7864: }
7865: close (OUT);
7866: return 'ok';
7867: }
7868:
7869: sub clear_selected_files {
7870: my ($user) = @_;
7871: my $filename = $user."savedfiles";
7872: open (OUT, '>'.LONCAPA::tempdir().$filename);
7873: print (OUT undef);
7874: close (OUT);
7875: return ("ok");
7876: }
7877:
7878: sub files_in_path {
7879: my ($user, $path) = @_;
7880: my $filename = $user."savedfiles";
7881: my %return_files;
7882: open (IN, '<'.LONCAPA::tempdir().$filename);
7883: while (my $line_in = <IN>) {
7884: chomp ($line_in);
7885: my @paths_and_file = split (m!/!, $line_in);
7886: my $file_part = pop (@paths_and_file);
7887: my $path_part = join ('/', @paths_and_file);
7888: $path_part.='/';
7889: my $path_and_file = $path_part.$file_part;
7890: if ($path_part eq $path) {
7891: $return_files{$file_part}= 'selected';
7892: }
7893: }
7894: close (IN);
7895: return (\%return_files);
7896: }
7897:
7898: # called in portfolio select mode, to show files selected NOT in current directory
7899: sub files_not_in_path {
7900: my ($user, $path) = @_;
7901: my $filename = $user."savedfiles";
7902: my @return_files;
7903: my $path_part;
7904: open(IN, '<'.LONCAPA::.$filename);
7905: while (my $line = <IN>) {
7906: #ok, I know it's clunky, but I want it to work
7907: my @paths_and_file = split(m|/|, $line);
7908: my $file_part = pop(@paths_and_file);
7909: chomp($file_part);
7910: my $path_part = join('/', @paths_and_file);
7911: $path_part .= '/';
7912: my $path_and_file = $path_part.$file_part;
7913: if ($path_part ne $path) {
7914: push(@return_files, ($path_and_file));
7915: }
7916: }
7917: close(OUT);
7918: return (@return_files);
7919: }
7920:
7921: #----------------------------------------------Get portfolio file permissions
7922:
7923: sub get_portfile_permissions {
7924: my ($domain,$user) = @_;
7925: my %current_permissions = &dump('file_permissions',$domain,$user);
7926: my ($tmp)=keys(%current_permissions);
7927: if ($tmp=~/^error:/) { undef(%current_permissions); }
7928: return \%current_permissions;
7929: }
7930:
7931: #---------------------------------------------Get portfolio file access controls
7932:
7933: sub get_access_controls {
7934: my ($current_permissions,$group,$file) = @_;
7935: my %access;
7936: my $real_file = $file;
7937: $file =~ s/\.meta$//;
7938: if (defined($file)) {
7939: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7940: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
7941: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
7942: }
7943: }
7944: } else {
7945: foreach my $key (keys(%{$current_permissions})) {
7946: if ($key =~ /\0accesscontrol$/) {
7947: if (defined($group)) {
7948: if ($key !~ m-^\Q$group\E/-) {
7949: next;
7950: }
7951: }
7952: my ($fullpath) = split(/\0/,$key);
7953: if (ref($$current_permissions{$key}) eq 'HASH') {
7954: foreach my $control (keys(%{$$current_permissions{$key}})) {
7955: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7956: }
7957: }
7958: }
7959: }
7960: }
7961: return %access;
7962: }
7963:
7964: sub modify_access_controls {
7965: my ($file_name,$changes,$domain,$user)=@_;
7966: my ($outcome,$deloutcome);
7967: my %store_permissions;
7968: my %new_values;
7969: my %new_control;
7970: my %translation;
7971: my @deletions = ();
7972: my $now = time;
7973: if (exists($$changes{'activate'})) {
7974: if (ref($$changes{'activate'}) eq 'HASH') {
7975: my @newitems = sort(keys(%{$$changes{'activate'}}));
7976: my $numnew = scalar(@newitems);
7977: for (my $i=0; $i<$numnew; $i++) {
7978: my $newkey = $newitems[$i];
7979: my $newid = &Apache::loncommon::get_cgi_id();
7980: if ($newkey =~ /^\d+:/) {
7981: $newkey =~ s/^(\d+)/$newid/;
7982: $translation{$1} = $newid;
7983: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7984: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7985: $translation{$1} = $newid;
7986: }
7987: $new_values{$file_name."\0".$newkey} =
7988: $$changes{'activate'}{$newitems[$i]};
7989: $new_control{$newkey} = $now;
7990: }
7991: }
7992: }
7993: my %todelete;
7994: my %changed_items;
7995: foreach my $action ('delete','update') {
7996: if (exists($$changes{$action})) {
7997: if (ref($$changes{$action}) eq 'HASH') {
7998: foreach my $key (keys(%{$$changes{$action}})) {
7999: my ($itemnum) = ($key =~ /^([^:]+):/);
8000: if ($action eq 'delete') {
8001: $todelete{$itemnum} = 1;
8002: } else {
8003: $changed_items{$itemnum} = $key;
8004: }
8005: }
8006: }
8007: }
8008: }
8009: # get lock on access controls for file.
8010: my $lockhash = {
8011: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8012: ':'.$env{'user.domain'},
8013: };
8014: my $tries = 0;
8015: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8016:
8017: while (($gotlock ne 'ok') && $tries <3) {
8018: $tries ++;
8019: sleep 1;
8020: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8021: }
8022: if ($gotlock eq 'ok') {
8023: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8024: my ($tmp)=keys(%curr_permissions);
8025: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8026: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8027: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8028: if (ref($curr_controls) eq 'HASH') {
8029: foreach my $control_item (keys(%{$curr_controls})) {
8030: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8031: if (defined($todelete{$itemnum})) {
8032: push(@deletions,$file_name."\0".$control_item);
8033: } else {
8034: if (defined($changed_items{$itemnum})) {
8035: $new_control{$changed_items{$itemnum}} = $now;
8036: push(@deletions,$file_name."\0".$control_item);
8037: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8038: } else {
8039: $new_control{$control_item} = $$curr_controls{$control_item};
8040: }
8041: }
8042: }
8043: }
8044: }
8045: my ($group);
8046: if (&is_course($domain,$user)) {
8047: ($group,my $file) = split(/\//,$file_name,2);
8048: }
8049: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8050: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8051: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8052: # remove lock
8053: my @del_lock = ($file_name."\0".'locked_access_records');
8054: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8055: my $sqlresult =
8056: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8057: $group);
8058: } else {
8059: $outcome = "error: could not obtain lockfile\n";
8060: }
8061: return ($outcome,$deloutcome,\%new_values,\%translation);
8062: }
8063:
8064: sub make_public_indefinitely {
8065: my ($requrl) = @_;
8066: my $now = time;
8067: my $action = 'activate';
8068: my $aclnum = 0;
8069: if (&is_portfolio_url($requrl)) {
8070: my (undef,$udom,$unum,$file_name,$group) =
8071: &parse_portfolio_url($requrl);
8072: my $current_perms = &get_portfile_permissions($udom,$unum);
8073: my %access_controls = &get_access_controls($current_perms,
8074: $group,$file_name);
8075: foreach my $key (keys(%{$access_controls{$file_name}})) {
8076: my ($num,$scope,$end,$start) =
8077: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8078: if ($scope eq 'public') {
8079: if ($start <= $now && $end == 0) {
8080: $action = 'none';
8081: } else {
8082: $action = 'update';
8083: $aclnum = $num;
8084: }
8085: last;
8086: }
8087: }
8088: if ($action eq 'none') {
8089: return 'ok';
8090: } else {
8091: my %changes;
8092: my $newend = 0;
8093: my $newstart = $now;
8094: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8095: $changes{$action}{$newkey} = {
8096: type => 'public',
8097: time => {
8098: start => $newstart,
8099: end => $newend,
8100: },
8101: };
8102: my ($outcome,$deloutcome,$new_values,$translation) =
8103: &modify_access_controls($file_name,\%changes,$udom,$unum);
8104: return $outcome;
8105: }
8106: } else {
8107: return 'invalid';
8108: }
8109: }
8110:
8111: #------------------------------------------------------Get Marked as Read Only
8112:
8113: sub get_marked_as_readonly {
8114: my ($domain,$user,$what,$group) = @_;
8115: my $current_permissions = &get_portfile_permissions($domain,$user);
8116: my @readonly_files;
8117: my $cmp1=$what;
8118: if (ref($what)) { $cmp1=join('',@{$what}) };
8119: while (my ($file_name,$value) = each(%{$current_permissions})) {
8120: if (defined($group)) {
8121: if ($file_name !~ m-^\Q$group\E/-) {
8122: next;
8123: }
8124: }
8125: if (ref($value) eq "ARRAY"){
8126: foreach my $stored_what (@{$value}) {
8127: my $cmp2=$stored_what;
8128: if (ref($stored_what) eq 'ARRAY') {
8129: $cmp2=join('',@{$stored_what});
8130: }
8131: if ($cmp1 eq $cmp2) {
8132: push(@readonly_files, $file_name);
8133: last;
8134: } elsif (!defined($what)) {
8135: push(@readonly_files, $file_name);
8136: last;
8137: }
8138: }
8139: }
8140: }
8141: return @readonly_files;
8142: }
8143: #-----------------------------------------------------------Get Marked as Read Only Hash
8144:
8145: sub get_marked_as_readonly_hash {
8146: my ($current_permissions,$group,$what) = @_;
8147: my %readonly_files;
8148: while (my ($file_name,$value) = each(%{$current_permissions})) {
8149: if (defined($group)) {
8150: if ($file_name !~ m-^\Q$group\E/-) {
8151: next;
8152: }
8153: }
8154: if (ref($value) eq "ARRAY"){
8155: foreach my $stored_what (@{$value}) {
8156: if (ref($stored_what) eq 'ARRAY') {
8157: foreach my $lock_descriptor(@{$stored_what}) {
8158: if ($lock_descriptor eq 'graded') {
8159: $readonly_files{$file_name} = 'graded';
8160: } elsif ($lock_descriptor eq 'handback') {
8161: $readonly_files{$file_name} = 'handback';
8162: } else {
8163: if (!exists($readonly_files{$file_name})) {
8164: $readonly_files{$file_name} = 'locked';
8165: }
8166: }
8167: }
8168: }
8169: }
8170: }
8171: }
8172: return %readonly_files;
8173: }
8174: # ------------------------------------------------------------ Unmark as Read Only
8175:
8176: sub unmark_as_readonly {
8177: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8178: # for portfolio submissions, $what contains [$symb,$crsid]
8179: my ($domain,$user,$what,$file_name,$group) = @_;
8180: $file_name = &declutter_portfile($file_name);
8181: my $symb_crs = $what;
8182: if (ref($what)) { $symb_crs=join('',@$what); }
8183: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8184: my ($tmp)=keys(%current_permissions);
8185: if ($tmp=~/^error:/) { undef(%current_permissions); }
8186: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8187: foreach my $file (@readonly_files) {
8188: my $clean_file = &declutter_portfile($file);
8189: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8190: my $current_locks = $current_permissions{$file};
8191: my @new_locks;
8192: my @del_keys;
8193: if (ref($current_locks) eq "ARRAY"){
8194: foreach my $locker (@{$current_locks}) {
8195: my $compare=$locker;
8196: if (ref($locker) eq 'ARRAY') {
8197: $compare=join('',@{$locker});
8198: if ($compare ne $symb_crs) {
8199: push(@new_locks, $locker);
8200: }
8201: }
8202: }
8203: if (scalar(@new_locks) > 0) {
8204: $current_permissions{$file} = \@new_locks;
8205: } else {
8206: push(@del_keys, $file);
8207: &del('file_permissions',\@del_keys, $domain, $user);
8208: delete($current_permissions{$file});
8209: }
8210: }
8211: }
8212: &put('file_permissions',\%current_permissions,$domain,$user);
8213: return;
8214: }
8215:
8216: # ------------------------------------------------------------ Directory lister
8217:
8218: sub dirlist {
8219: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8220: $uri=~s/^\///;
8221: $uri=~s/\/$//;
8222: my ($udom, $uname);
8223: if ($getuserdir) {
8224: $udom = $userdomain;
8225: $uname = $username;
8226: } else {
8227: (undef,$udom,$uname)=split(/\//,$uri);
8228: if(defined($userdomain)) {
8229: $udom = $userdomain;
8230: }
8231: if(defined($username)) {
8232: $uname = $username;
8233: }
8234: }
8235: my ($dirRoot,$listing,@listing_results);
8236:
8237: $dirRoot = $perlvar{'lonDocRoot'};
8238: if (defined($getpropath)) {
8239: $dirRoot = &propath($udom,$uname);
8240: $dirRoot =~ s/\/$//;
8241: } elsif (defined($getuserdir)) {
8242: my $subdir=$uname.'__';
8243: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8244: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8245: ."/$udom/$subdir/$uname";
8246: } elsif (defined($alternateRoot)) {
8247: $dirRoot = $alternateRoot;
8248: }
8249:
8250: if($udom) {
8251: if($uname) {
8252: my $uhome = &homeserver($uname,$udom);
8253: if ($uhome eq 'no_host') {
8254: return ([],'no_host');
8255: }
8256: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8257: .$getuserdir.':'.&escape($dirRoot)
8258: .':'.&escape($uname).':'.&escape($udom),$uhome);
8259: if ($listing eq 'unknown_cmd') {
8260: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8261: } else {
8262: @listing_results = map { &unescape($_); } split(/:/,$listing);
8263: }
8264: if ($listing eq 'unknown_cmd') {
8265: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8266: @listing_results = split(/:/,$listing);
8267: } else {
8268: @listing_results = map { &unescape($_); } split(/:/,$listing);
8269: }
8270: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8271: ($listing eq 'rejected') || ($listing eq 'refused') ||
8272: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8273: return ([],$listing);
8274: } else {
8275: return (\@listing_results);
8276: }
8277: } elsif(!$alternateRoot) {
8278: my (%allusers,%listerror);
8279: my %servers = &get_servers($udom,'library');
8280: foreach my $tryserver (keys(%servers)) {
8281: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8282: &escape($udom),$tryserver);
8283: if ($listing eq 'unknown_cmd') {
8284: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8285: $udom, $tryserver);
8286: } else {
8287: @listing_results = map { &unescape($_); } split(/:/,$listing);
8288: }
8289: if ($listing eq 'unknown_cmd') {
8290: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8291: $udom, $tryserver);
8292: @listing_results = split(/:/,$listing);
8293: } else {
8294: @listing_results =
8295: map { &unescape($_); } split(/:/,$listing);
8296: }
8297: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8298: ($listing eq 'rejected') || ($listing eq 'refused') ||
8299: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8300: $listerror{$tryserver} = $listing;
8301: } else {
8302: foreach my $line (@listing_results) {
8303: my ($entry) = split(/&/,$line,2);
8304: $allusers{$entry} = 1;
8305: }
8306: }
8307: }
8308: my @alluserslist=();
8309: foreach my $user (sort(keys(%allusers))) {
8310: push(@alluserslist,$user.'&user');
8311: }
8312: return (\@alluserslist);
8313: } else {
8314: return ([],'missing username');
8315: }
8316: } elsif(!defined($getpropath)) {
8317: my $path = $perlvar{'lonDocRoot'}.'/res/';
8318: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8319: return (\@all_domains);
8320: } else {
8321: return ([],'missing domain');
8322: }
8323: }
8324:
8325: # --------------------------------------------- GetFileTimestamp
8326: # This function utilizes dirlist and returns the date stamp for
8327: # when it was last modified. It will also return an error of -1
8328: # if an error occurs
8329:
8330: sub GetFileTimestamp {
8331: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8332: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8333: $studentName = &LONCAPA::clean_username($studentName);
8334: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8335: undef,$getuserdir);
8336: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8337: return -1;
8338: }
8339: if (ref($fileref) eq 'ARRAY') {
8340: my @stats = split('&',$fileref->[0]);
8341: # @stats contains first the filename, then the stat output
8342: return $stats[10]; # so this is 10 instead of 9.
8343: } else {
8344: return -1;
8345: }
8346: }
8347:
8348: sub stat_file {
8349: my ($uri) = @_;
8350: $uri = &clutter_with_no_wrapper($uri);
8351:
8352: my ($udom,$uname,$file);
8353: if ($uri =~ m-^/(uploaded|editupload)/-) {
8354: ($udom,$uname,$file) =
8355: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8356: $file = 'userfiles/'.$file;
8357: }
8358: if ($uri =~ m-^/res/-) {
8359: ($udom,$uname) =
8360: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8361: $file = $uri;
8362: }
8363:
8364: if (!$udom || !$uname || !$file) {
8365: # unable to handle the uri
8366: return ();
8367: }
8368: my $getpropath;
8369: if ($file =~ /^userfiles\//) {
8370: $getpropath = 1;
8371: }
8372: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8373: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8374: return ();
8375: } else {
8376: if (ref($listref) eq 'ARRAY') {
8377: my @stats = split('&',$listref->[0]);
8378: shift(@stats); #filename is first
8379: return @stats;
8380: }
8381: }
8382: return ();
8383: }
8384:
8385: # -------------------------------------------------------- Value of a Condition
8386:
8387: # gets the value of a specific preevaluated condition
8388: # stored in the string $env{user.state.<cid>}
8389: # or looks up a condition reference in the bighash and if if hasn't
8390: # already been evaluated recurses into docondval to get the value of
8391: # the condition, then memoizing it to
8392: # $env{user.state.<cid>.<condition>}
8393: sub directcondval {
8394: my $number=shift;
8395: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8396: &Apache::lonuserstate::evalstate();
8397: }
8398: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8399: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8400: } elsif ($number =~ /^_/) {
8401: my $sub_condition;
8402: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8403: &GDBM_READER(),0640)) {
8404: $sub_condition=$bighash{'conditions'.$number};
8405: untie(%bighash);
8406: }
8407: my $value = &docondval($sub_condition);
8408: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8409: return $value;
8410: }
8411: if ($env{'user.state.'.$env{'request.course.id'}}) {
8412: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8413: } else {
8414: return 2;
8415: }
8416: }
8417:
8418: # get the collection of conditions for this resource
8419: sub condval {
8420: my $condidx=shift;
8421: my $allpathcond='';
8422: foreach my $cond (split(/\|/,$condidx)) {
8423: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8424: $allpathcond.=
8425: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8426: }
8427: }
8428: $allpathcond=~s/\|$//;
8429: return &docondval($allpathcond);
8430: }
8431:
8432: #evaluates an expression of conditions
8433: sub docondval {
8434: my ($allpathcond) = @_;
8435: my $result=0;
8436: if ($env{'request.course.id'}
8437: && defined($allpathcond)) {
8438: my $operand='|';
8439: my @stack;
8440: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8441: if ($chunk eq '(') {
8442: push @stack,($operand,$result);
8443: } elsif ($chunk eq ')') {
8444: my $before=pop @stack;
8445: if (pop @stack eq '&') {
8446: $result=$result>$before?$before:$result;
8447: } else {
8448: $result=$result>$before?$result:$before;
8449: }
8450: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8451: $operand=$chunk;
8452: } else {
8453: my $new=directcondval($chunk);
8454: if ($operand eq '&') {
8455: $result=$result>$new?$new:$result;
8456: } else {
8457: $result=$result>$new?$result:$new;
8458: }
8459: }
8460: }
8461: }
8462: return $result;
8463: }
8464:
8465: # ---------------------------------------------------- Devalidate courseresdata
8466:
8467: sub devalidatecourseresdata {
8468: my ($coursenum,$coursedomain)=@_;
8469: my $hashid=$coursenum.':'.$coursedomain;
8470: &devalidate_cache_new('courseres',$hashid);
8471: }
8472:
8473:
8474: # --------------------------------------------------- Course Resourcedata Query
8475: #
8476: # Parameters:
8477: # $coursenum - Number of the course.
8478: # $coursedomain - Domain at which the course was created.
8479: # Returns:
8480: # A hash of the course parameters along (I think) with timestamps
8481: # and version info.
8482:
8483: sub get_courseresdata {
8484: my ($coursenum,$coursedomain)=@_;
8485: my $coursehom=&homeserver($coursenum,$coursedomain);
8486: my $hashid=$coursenum.':'.$coursedomain;
8487: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8488: my %dumpreply;
8489: unless (defined($cached)) {
8490: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8491: $result=\%dumpreply;
8492: my ($tmp) = keys(%dumpreply);
8493: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8494: &do_cache_new('courseres',$hashid,$result,600);
8495: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8496: return $tmp;
8497: } elsif ($tmp =~ /^(error)/) {
8498: $result=undef;
8499: &do_cache_new('courseres',$hashid,$result,600);
8500: }
8501: }
8502: return $result;
8503: }
8504:
8505: sub devalidateuserresdata {
8506: my ($uname,$udom)=@_;
8507: my $hashid="$udom:$uname";
8508: &devalidate_cache_new('userres',$hashid);
8509: }
8510:
8511: sub get_userresdata {
8512: my ($uname,$udom)=@_;
8513: #most student don\'t have any data set, check if there is some data
8514: if (&EXT_cache_status($udom,$uname)) { return undef; }
8515:
8516: my $hashid="$udom:$uname";
8517: my ($result,$cached)=&is_cached_new('userres',$hashid);
8518: if (!defined($cached)) {
8519: my %resourcedata=&dump('resourcedata',$udom,$uname);
8520: $result=\%resourcedata;
8521: &do_cache_new('userres',$hashid,$result,600);
8522: }
8523: my ($tmp)=keys(%$result);
8524: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8525: return $result;
8526: }
8527: #error 2 occurs when the .db doesn't exist
8528: if ($tmp!~/error: 2 /) {
8529: &logthis("<font color=\"blue\">WARNING:".
8530: " Trying to get resource data for ".
8531: $uname." at ".$udom.": ".
8532: $tmp."</font>");
8533: } elsif ($tmp=~/error: 2 /) {
8534: #&EXT_cache_set($udom,$uname);
8535: &do_cache_new('userres',$hashid,undef,600);
8536: undef($tmp); # not really an error so don't send it back
8537: }
8538: return $tmp;
8539: }
8540: #----------------------------------------------- resdata - return resource data
8541: # Purpose:
8542: # Return resource data for either users or for a course.
8543: # Parameters:
8544: # $name - Course/user name.
8545: # $domain - Name of the domain the user/course is registered on.
8546: # $type - Type of thing $name is (must be 'course' or 'user'
8547: # @which - Array of names of resources desired.
8548: # Returns:
8549: # The value of the first reasource in @which that is found in the
8550: # resource hash.
8551: # Exceptional Conditions:
8552: # If the $type passed in is not valid (not the string 'course' or
8553: # 'user', an undefined reference is returned.
8554: # If none of the resources are found, an undef is returned
8555: sub resdata {
8556: my ($name,$domain,$type,@which)=@_;
8557: my $result;
8558: if ($type eq 'course') {
8559: $result=&get_courseresdata($name,$domain);
8560: } elsif ($type eq 'user') {
8561: $result=&get_userresdata($name,$domain);
8562: }
8563: if (!ref($result)) { return $result; }
8564: foreach my $item (@which) {
8565: if (defined($result->{$item->[0]})) {
8566: return [$result->{$item->[0]},$item->[1]];
8567: }
8568: }
8569: return undef;
8570: }
8571:
8572: #
8573: # EXT resource caching routines
8574: #
8575:
8576: sub clear_EXT_cache_status {
8577: &delenv('cache.EXT.');
8578: }
8579:
8580: sub EXT_cache_status {
8581: my ($target_domain,$target_user) = @_;
8582: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8583: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8584: # We know already the user has no data
8585: return 1;
8586: } else {
8587: return 0;
8588: }
8589: }
8590:
8591: sub EXT_cache_set {
8592: my ($target_domain,$target_user) = @_;
8593: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8594: #&appenv({$cachename => time});
8595: }
8596:
8597: # --------------------------------------------------------- Value of a Variable
8598: sub EXT {
8599:
8600: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8601: unless ($varname) { return ''; }
8602: #get real user name/domain, courseid and symb
8603: my $courseid;
8604: my $publicuser;
8605: if ($symbparm) {
8606: $symbparm=&get_symb_from_alias($symbparm);
8607: }
8608: if (!($uname && $udom)) {
8609: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8610: if (!$symbparm) { $symbparm=$cursymb; }
8611: } else {
8612: $courseid=$env{'request.course.id'};
8613: }
8614: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8615: my $rest;
8616: if (defined($therest[0])) {
8617: $rest=join('.',@therest);
8618: } else {
8619: $rest='';
8620: }
8621:
8622: my $qualifierrest=$qualifier;
8623: if ($rest) { $qualifierrest.='.'.$rest; }
8624: my $spacequalifierrest=$space;
8625: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
8626: if ($realm eq 'user') {
8627: # --------------------------------------------------------------- user.resource
8628: if ($space eq 'resource') {
8629: if ( (defined($Apache::lonhomework::parsing_a_problem)
8630: || defined($Apache::lonhomework::parsing_a_task))
8631: &&
8632: ($symbparm eq &symbread()) ) {
8633: # if we are in the middle of processing the resource the
8634: # get the value we are planning on committing
8635: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8636: return $Apache::lonhomework::results{$qualifierrest};
8637: } else {
8638: return $Apache::lonhomework::history{$qualifierrest};
8639: }
8640: } else {
8641: my %restored;
8642: if ($publicuser || $env{'request.state'} eq 'construct') {
8643: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8644: } else {
8645: %restored=&restore($symbparm,$courseid,$udom,$uname);
8646: }
8647: return $restored{$qualifierrest};
8648: }
8649: # ----------------------------------------------------------------- user.access
8650: } elsif ($space eq 'access') {
8651: # FIXME - not supporting calls for a specific user
8652: return &allowed($qualifier,$rest);
8653: # ------------------------------------------ user.preferences, user.environment
8654: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
8655: if (($uname eq $env{'user.name'}) &&
8656: ($udom eq $env{'user.domain'})) {
8657: return $env{join('.',('environment',$qualifierrest))};
8658: } else {
8659: my %returnhash;
8660: if (!$publicuser) {
8661: %returnhash=&userenvironment($udom,$uname,
8662: $qualifierrest);
8663: }
8664: return $returnhash{$qualifierrest};
8665: }
8666: # ----------------------------------------------------------------- user.course
8667: } elsif ($space eq 'course') {
8668: # FIXME - not supporting calls for a specific user
8669: return $env{join('.',('request.course',$qualifier))};
8670: # ------------------------------------------------------------------- user.role
8671: } elsif ($space eq 'role') {
8672: # FIXME - not supporting calls for a specific user
8673: my ($role,$where)=split(/\./,$env{'request.role'});
8674: if ($qualifier eq 'value') {
8675: return $role;
8676: } elsif ($qualifier eq 'extent') {
8677: return $where;
8678: }
8679: # ----------------------------------------------------------------- user.domain
8680: } elsif ($space eq 'domain') {
8681: return $udom;
8682: # ------------------------------------------------------------------- user.name
8683: } elsif ($space eq 'name') {
8684: return $uname;
8685: # ---------------------------------------------------- Any other user namespace
8686: } else {
8687: my %reply;
8688: if (!$publicuser) {
8689: %reply=&get($space,[$qualifierrest],$udom,$uname);
8690: }
8691: return $reply{$qualifierrest};
8692: }
8693: } elsif ($realm eq 'query') {
8694: # ---------------------------------------------- pull stuff out of query string
8695: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8696: [$spacequalifierrest]);
8697: return $env{'form.'.$spacequalifierrest};
8698: } elsif ($realm eq 'request') {
8699: # ------------------------------------------------------------- request.browser
8700: if ($space eq 'browser') {
8701: if ($qualifier eq 'textremote') {
8702: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
8703: return 1;
8704: } else {
8705: return 0;
8706: }
8707: } else {
8708: return $env{'browser.'.$qualifier};
8709: }
8710: # ------------------------------------------------------------ request.filename
8711: } else {
8712: return $env{'request.'.$spacequalifierrest};
8713: }
8714: } elsif ($realm eq 'course') {
8715: # ---------------------------------------------------------- course.description
8716: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
8717: } elsif ($realm eq 'resource') {
8718:
8719: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
8720: if (!$symbparm) { $symbparm=&symbread(); }
8721: }
8722:
8723: if ($space eq 'title') {
8724: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8725: return &gettitle($symbparm);
8726: }
8727:
8728: if ($space eq 'map') {
8729: my ($map) = &decode_symb($symbparm);
8730: return &symbread($map);
8731: }
8732: if ($space eq 'filename') {
8733: if ($symbparm) {
8734: return &clutter((&decode_symb($symbparm))[2]);
8735: }
8736: return &hreflocation('',$env{'request.filename'});
8737: }
8738:
8739: my ($section, $group, @groups);
8740: my ($courselevelm,$courselevel);
8741: if ($symbparm && defined($courseid) &&
8742: $courseid eq $env{'request.course.id'}) {
8743:
8744: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
8745:
8746: # ----------------------------------------------------- Cascading lookup scheme
8747: my $symbp=$symbparm;
8748: my $mapp=&deversion((&decode_symb($symbp))[0]);
8749:
8750: my $symbparm=$symbp.'.'.$spacequalifierrest;
8751: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8752:
8753: if (($env{'user.name'} eq $uname) &&
8754: ($env{'user.domain'} eq $udom)) {
8755: $section=$env{'request.course.sec'};
8756: @groups = split(/:/,$env{'request.course.groups'});
8757: @groups=&sort_course_groups($courseid,@groups);
8758: } else {
8759: if (! defined($usection)) {
8760: $section=&getsection($udom,$uname,$courseid);
8761: } else {
8762: $section = $usection;
8763: }
8764: @groups = &get_users_groups($udom,$uname,$courseid);
8765: }
8766:
8767: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8768: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8769: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8770:
8771: $courselevel=$courseid.'.'.$spacequalifierrest;
8772: my $courselevelr=$courseid.'.'.$symbparm;
8773: $courselevelm=$courseid.'.'.$mapparm;
8774:
8775: # ----------------------------------------------------------- first, check user
8776:
8777: my $userreply=&resdata($uname,$udom,'user',
8778: ([$courselevelr,'resource'],
8779: [$courselevelm,'map' ],
8780: [$courselevel, 'course' ]));
8781: if (defined($userreply)) { return &get_reply($userreply); }
8782:
8783: # ------------------------------------------------ second, check some of course
8784: my $coursereply;
8785: if (@groups > 0) {
8786: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8787: $mapparm,$spacequalifierrest);
8788: if (defined($coursereply)) { return &get_reply($coursereply); }
8789: }
8790:
8791: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8792: $env{'course.'.$courseid.'.domain'},
8793: 'course',
8794: ([$seclevelr, 'resource'],
8795: [$seclevelm, 'map' ],
8796: [$seclevel, 'course' ],
8797: [$courselevelr,'resource']));
8798: if (defined($coursereply)) { return &get_reply($coursereply); }
8799:
8800: # ------------------------------------------------------ third, check map parms
8801: my %parmhash=();
8802: my $thisparm='';
8803: if (tie(%parmhash,'GDBM_File',
8804: $env{'request.course.fn'}.'_parms.db',
8805: &GDBM_READER(),0640)) {
8806: $thisparm=$parmhash{$symbparm};
8807: untie(%parmhash);
8808: }
8809: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
8810: }
8811: # ------------------------------------------ fourth, look in resource metadata
8812:
8813: $spacequalifierrest=~s/\./\_/;
8814: my $filename;
8815: if (!$symbparm) { $symbparm=&symbread(); }
8816: if ($symbparm) {
8817: $filename=(&decode_symb($symbparm))[2];
8818: } else {
8819: $filename=$env{'request.filename'};
8820: }
8821: my $metadata=&metadata($filename,$spacequalifierrest);
8822: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8823: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
8824: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
8825:
8826: # ---------------------------------------------- fourth, look in rest of course
8827: if ($symbparm && defined($courseid) &&
8828: $courseid eq $env{'request.course.id'}) {
8829: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8830: $env{'course.'.$courseid.'.domain'},
8831: 'course',
8832: ([$courselevelm,'map' ],
8833: [$courselevel, 'course']));
8834: if (defined($coursereply)) { return &get_reply($coursereply); }
8835: }
8836: # ------------------------------------------------------------------ Cascade up
8837: unless ($space eq '0') {
8838: my @parts=split(/_/,$space);
8839: my $id=pop(@parts);
8840: my $part=join('_',@parts);
8841: if ($part eq '') { $part='0'; }
8842: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
8843: $symbparm,$udom,$uname,$section,1);
8844: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
8845: }
8846: if ($recurse) { return undef; }
8847: my $pack_def=&packages_tab_default($filename,$varname);
8848: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
8849: # ---------------------------------------------------- Any other user namespace
8850: } elsif ($realm eq 'environment') {
8851: # ----------------------------------------------------------------- environment
8852: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8853: return $env{'environment.'.$spacequalifierrest};
8854: } else {
8855: if ($uname eq 'anonymous' && $udom eq '') {
8856: return '';
8857: }
8858: my %returnhash=&userenvironment($udom,$uname,
8859: $spacequalifierrest);
8860: return $returnhash{$spacequalifierrest};
8861: }
8862: } elsif ($realm eq 'system') {
8863: # ----------------------------------------------------------------- system.time
8864: if ($space eq 'time') {
8865: return time;
8866: }
8867: } elsif ($realm eq 'server') {
8868: # ----------------------------------------------------------------- system.time
8869: if ($space eq 'name') {
8870: return $ENV{'SERVER_NAME'};
8871: }
8872: }
8873: return '';
8874: }
8875:
8876: sub get_reply {
8877: my ($reply_value) = @_;
8878: if (ref($reply_value) eq 'ARRAY') {
8879: if (wantarray) {
8880: return @$reply_value;
8881: }
8882: return $reply_value->[0];
8883: } else {
8884: return $reply_value;
8885: }
8886: }
8887:
8888: sub check_group_parms {
8889: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8890: my @groupitems = ();
8891: my $resultitem;
8892: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
8893: foreach my $group (@{$groups}) {
8894: foreach my $level (@levels) {
8895: my $item = $courseid.'.['.$group.'].'.$level->[0];
8896: push(@groupitems,[$item,$level->[1]]);
8897: }
8898: }
8899: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8900: $env{'course.'.$courseid.'.domain'},
8901: 'course',@groupitems);
8902: return $coursereply;
8903: }
8904:
8905: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
8906: my ($courseid,@groups) = @_;
8907: @groups = sort(@groups);
8908: return @groups;
8909: }
8910:
8911: sub packages_tab_default {
8912: my ($uri,$varname)=@_;
8913: my (undef,$part,$name)=split(/\./,$varname);
8914:
8915: my (@extension,@specifics,$do_default);
8916: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
8917: my ($pack_type,$pack_part)=split(/_/,$package,2);
8918: if ($pack_type eq 'default') {
8919: $do_default=1;
8920: } elsif ($pack_type eq 'extension') {
8921: push(@extension,[$package,$pack_type,$pack_part]);
8922: } elsif ($pack_part eq $part || $pack_type eq 'part') {
8923: # only look at packages defaults for packages that this id is
8924: push(@specifics,[$package,$pack_type,$pack_part]);
8925: }
8926: }
8927: # first look for a package that matches the requested part id
8928: foreach my $package (@specifics) {
8929: my (undef,$pack_type,$pack_part)=@{$package};
8930: next if ($pack_part ne $part);
8931: if (defined($packagetab{"$pack_type&$name&default"})) {
8932: return $packagetab{"$pack_type&$name&default"};
8933: }
8934: }
8935: # look for any possible matching non extension_ package
8936: foreach my $package (@specifics) {
8937: my (undef,$pack_type,$pack_part)=@{$package};
8938: if (defined($packagetab{"$pack_type&$name&default"})) {
8939: return $packagetab{"$pack_type&$name&default"};
8940: }
8941: if ($pack_type eq 'part') { $pack_part='0'; }
8942: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8943: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
8944: }
8945: }
8946: # look for any posible extension_ match
8947: foreach my $package (@extension) {
8948: my ($package,$pack_type)=@{$package};
8949: if (defined($packagetab{"$pack_type&$name&default"})) {
8950: return $packagetab{"$pack_type&$name&default"};
8951: }
8952: if (defined($packagetab{$package."&$name&default"})) {
8953: return $packagetab{$package."&$name&default"};
8954: }
8955: }
8956: # look for a global default setting
8957: if ($do_default && defined($packagetab{"default&$name&default"})) {
8958: return $packagetab{"default&$name&default"};
8959: }
8960: return undef;
8961: }
8962:
8963: sub add_prefix_and_part {
8964: my ($prefix,$part)=@_;
8965: my $keyroot;
8966: if (defined($prefix) && $prefix !~ /^__/) {
8967: # prefix that has a part already
8968: $keyroot=$prefix;
8969: } elsif (defined($prefix)) {
8970: # prefix that is missing a part
8971: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8972: } else {
8973: # no prefix at all
8974: if (defined($part)) { $keyroot='_'.$part; }
8975: }
8976: return $keyroot;
8977: }
8978:
8979: # ---------------------------------------------------------------- Get metadata
8980:
8981: my %metaentry;
8982: my %importedpartids;
8983: sub metadata {
8984: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
8985: $uri=&declutter($uri);
8986: # if it is a non metadata possible uri return quickly
8987: if (($uri eq '') ||
8988: (($uri =~ m|^/*adm/|) &&
8989: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
8990: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
8991: return undef;
8992: }
8993: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8994: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
8995: return undef;
8996: }
8997: my $filename=$uri;
8998: $uri=~s/\.meta$//;
8999: #
9000: # Is the metadata already cached?
9001: # Look at timestamp of caching
9002: # Everything is cached by the main uri, libraries are never directly cached
9003: #
9004: if (!defined($liburi)) {
9005: my ($result,$cached)=&is_cached_new('meta',$uri);
9006: if (defined($cached)) { return $result->{':'.$what}; }
9007: }
9008: {
9009: # Imported parts would go here
9010: my %importedids=();
9011: my @origfileimportpartids=();
9012: my $importedparts=0;
9013: #
9014: # Is this a recursive call for a library?
9015: #
9016: # if (! exists($metacache{$uri})) {
9017: # $metacache{$uri}={};
9018: # }
9019: my $cachetime = 60*60;
9020: if ($liburi) {
9021: $liburi=&declutter($liburi);
9022: $filename=$liburi;
9023: } else {
9024: &devalidate_cache_new('meta',$uri);
9025: undef(%metaentry);
9026: }
9027: my %metathesekeys=();
9028: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9029: my $metastring;
9030: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
9031: my $which = &hreflocation('','/'.($liburi || $uri));
9032: $metastring =
9033: &Apache::lonnet::ssi_body($which,
9034: ('grade_target' => 'meta'));
9035: $cachetime = 1; # only want this cached in the child not long term
9036: } elsif (($uri !~ m -^(editupload)/-) &&
9037: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9038: my $file=&filelocation('',&clutter($filename));
9039: #push(@{$metaentry{$uri.'.file'}},$file);
9040: $metastring=&getfile($file);
9041: }
9042: my $parser=HTML::LCParser->new(\$metastring);
9043: my $token;
9044: undef %metathesekeys;
9045: while ($token=$parser->get_token) {
9046: if ($token->[0] eq 'S') {
9047: if (defined($token->[2]->{'package'})) {
9048: #
9049: # This is a package - get package info
9050: #
9051: my $package=$token->[2]->{'package'};
9052: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9053: if (defined($token->[2]->{'id'})) {
9054: $keyroot.='_'.$token->[2]->{'id'};
9055: }
9056: if ($metaentry{':packages'}) {
9057: $metaentry{':packages'}.=','.$package.$keyroot;
9058: } else {
9059: $metaentry{':packages'}=$package.$keyroot;
9060: }
9061: foreach my $pack_entry (keys(%packagetab)) {
9062: my $part=$keyroot;
9063: $part=~s/^\_//;
9064: if ($pack_entry=~/^\Q$package\E\&/ ||
9065: $pack_entry=~/^\Q$package\E_0\&/) {
9066: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9067: # ignore package.tab specified default values
9068: # here &package_tab_default() will fetch those
9069: if ($subp eq 'default') { next; }
9070: my $value=$packagetab{$pack_entry};
9071: my $unikey;
9072: if ($pack =~ /_0$/) {
9073: $unikey='parameter_0_'.$name;
9074: $part=0;
9075: } else {
9076: $unikey='parameter'.$keyroot.'_'.$name;
9077: }
9078: if ($subp eq 'display') {
9079: $value.=' [Part: '.$part.']';
9080: }
9081: $metaentry{':'.$unikey.'.part'}=$part;
9082: $metathesekeys{$unikey}=1;
9083: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9084: $metaentry{':'.$unikey.'.'.$subp}=$value;
9085: }
9086: if (defined($metaentry{':'.$unikey.'.default'})) {
9087: $metaentry{':'.$unikey}=
9088: $metaentry{':'.$unikey.'.default'};
9089: }
9090: }
9091: }
9092: } else {
9093: #
9094: # This is not a package - some other kind of start tag
9095: #
9096: my $entry=$token->[1];
9097: my $unikey='';
9098:
9099: if ($entry eq 'import') {
9100: #
9101: # Importing a library here
9102: #
9103: my $location=$parser->get_text('/import');
9104: my $dir=$filename;
9105: $dir=~s|[^/]*$||;
9106: $location=&filelocation($dir,$location);
9107:
9108: my $importmode=$token->[2]->{'importmode'};
9109: if ($importmode eq 'problem') {
9110: # Import as problem/response
9111: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9112: } elsif ($importmode eq 'part') {
9113: # Import as part(s)
9114: $importedparts=1;
9115: # We need to get the original file and the imported file to get the part order correct
9116: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9117: # Load and inspect original file
9118: if ($#origfileimportpartids<0) {
9119: undef(%importedpartids);
9120: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9121: my $origfile=&getfile($origfilelocation);
9122: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9123: }
9124:
9125: # Load and inspect imported file
9126: my $impfile=&getfile($location);
9127: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9128: if ($#impfilepartids>=0) {
9129: # This problem had parts
9130: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9131: } else {
9132: # Importing by turning a single problem into a problem part
9133: # It gets the import-tags ID as part-ID
9134: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9135: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9136: }
9137: } else {
9138: # Normal import
9139: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9140: if (defined($token->[2]->{'id'})) {
9141: $unikey.='_'.$token->[2]->{'id'};
9142: }
9143: }
9144:
9145: if ($depthcount<20) {
9146: my $metadata =
9147: &metadata($uri,'keys', $location,$unikey,
9148: $depthcount+1);
9149: foreach my $meta (split(',',$metadata)) {
9150: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9151: $metathesekeys{$meta}=1;
9152: }
9153:
9154: }
9155: } else {
9156: #
9157: # Not importing, some other kind of non-package, non-library start tag
9158: #
9159: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9160: if (defined($token->[2]->{'id'})) {
9161: $unikey.='_'.$token->[2]->{'id'};
9162: }
9163: if (defined($token->[2]->{'name'})) {
9164: $unikey.='_'.$token->[2]->{'name'};
9165: }
9166: $metathesekeys{$unikey}=1;
9167: foreach my $param (@{$token->[3]}) {
9168: $metaentry{':'.$unikey.'.'.$param} =
9169: $token->[2]->{$param};
9170: }
9171: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9172: my $default=$metaentry{':'.$unikey.'.default'};
9173: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9174: # only ws inside the tag, and not in default, so use default
9175: # as value
9176: $metaentry{':'.$unikey}=$default;
9177: } elsif ( $internaltext =~ /\S/ ) {
9178: # something interesting inside the tag
9179: $metaentry{':'.$unikey}=$internaltext;
9180: } else {
9181: # no interesting values, don't set a default
9182: }
9183: # end of not-a-package not-a-library import
9184: }
9185: # end of not-a-package start tag
9186: }
9187: # the next is the end of "start tag"
9188: }
9189: }
9190: my ($extension) = ($uri =~ /\.(\w+)$/);
9191: $extension = lc($extension);
9192: if ($extension eq 'htm') { $extension='html'; }
9193:
9194: foreach my $key (keys(%packagetab)) {
9195: #no specific packages #how's our extension
9196: if ($key!~/^extension_\Q$extension\E&/) { next; }
9197: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9198: \%metathesekeys);
9199: }
9200:
9201: if (!exists($metaentry{':packages'})
9202: || $packagetab{"import_defaults&extension_$extension"}) {
9203: foreach my $key (keys(%packagetab)) {
9204: #no specific packages well let's get default then
9205: if ($key!~/^default&/) { next; }
9206: &metadata_create_package_def($uri,$key,'default',
9207: \%metathesekeys);
9208: }
9209: }
9210: # are there custom rights to evaluate
9211: if ($metaentry{':copyright'} eq 'custom') {
9212:
9213: #
9214: # Importing a rights file here
9215: #
9216: unless ($depthcount) {
9217: my $location=$metaentry{':customdistributionfile'};
9218: my $dir=$filename;
9219: $dir=~s|[^/]*$||;
9220: $location=&filelocation($dir,$location);
9221: my $rights_metadata =
9222: &metadata($uri,'keys',$location,'_rights',
9223: $depthcount+1);
9224: foreach my $rights (split(',',$rights_metadata)) {
9225: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9226: $metathesekeys{$rights}=1;
9227: }
9228: }
9229: }
9230: # uniqifiy package listing
9231: my %seen;
9232: my @uniq_packages =
9233: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9234: $metaentry{':packages'} = join(',',@uniq_packages);
9235:
9236: if ($importedparts) {
9237: # We had imported parts and need to rebuild partorder
9238: $metaentry{':partorder'}='';
9239: $metathesekeys{'partorder'}=1;
9240: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9241: if ($origfileimportpartids[$index] eq 'part') {
9242: # original part, part of the problem
9243: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9244: } else {
9245: # we have imported parts at this position
9246: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9247: }
9248: }
9249: $metaentry{':partorder'}=~s/^\,//;
9250: }
9251:
9252: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9253: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9254: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9255: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9256: # this is the end of "was not already recently cached
9257: }
9258: return $metaentry{':'.$what};
9259: }
9260:
9261: sub metadata_create_package_def {
9262: my ($uri,$key,$package,$metathesekeys)=@_;
9263: my ($pack,$name,$subp)=split(/\&/,$key);
9264: if ($subp eq 'default') { next; }
9265:
9266: if (defined($metaentry{':packages'})) {
9267: $metaentry{':packages'}.=','.$package;
9268: } else {
9269: $metaentry{':packages'}=$package;
9270: }
9271: my $value=$packagetab{$key};
9272: my $unikey;
9273: $unikey='parameter_0_'.$name;
9274: $metaentry{':'.$unikey.'.part'}=0;
9275: $$metathesekeys{$unikey}=1;
9276: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9277: $metaentry{':'.$unikey.'.'.$subp}=$value;
9278: }
9279: if (defined($metaentry{':'.$unikey.'.default'})) {
9280: $metaentry{':'.$unikey}=
9281: $metaentry{':'.$unikey.'.default'};
9282: }
9283: }
9284:
9285: sub metadata_generate_part0 {
9286: my ($metadata,$metacache,$uri) = @_;
9287: my %allnames;
9288: foreach my $metakey (keys(%$metadata)) {
9289: if ($metakey=~/^parameter\_(.*)/) {
9290: my $part=$$metacache{':'.$metakey.'.part'};
9291: my $name=$$metacache{':'.$metakey.'.name'};
9292: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9293: $allnames{$name}=$part;
9294: }
9295: }
9296: }
9297: foreach my $name (keys(%allnames)) {
9298: $$metadata{"parameter_0_$name"}=1;
9299: my $key=":parameter_0_$name";
9300: $$metacache{"$key.part"}='0';
9301: $$metacache{"$key.name"}=$name;
9302: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9303: $allnames{$name}.'_'.$name.
9304: '.type'};
9305: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9306: '.display'};
9307: my $expr='[Part: '.$allnames{$name}.']';
9308: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9309: $$metacache{"$key.display"}=$olddis;
9310: }
9311: }
9312:
9313: # ------------------------------------------------------ Devalidate title cache
9314:
9315: sub devalidate_title_cache {
9316: my ($url)=@_;
9317: if (!$env{'request.course.id'}) { return; }
9318: my $symb=&symbread($url);
9319: if (!$symb) { return; }
9320: my $key=$env{'request.course.id'}."\0".$symb;
9321: &devalidate_cache_new('title',$key);
9322: }
9323:
9324: # ------------------------------------------------- Get the title of a course
9325:
9326: sub current_course_title {
9327: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9328: }
9329: # ------------------------------------------------- Get the title of a resource
9330:
9331: sub gettitle {
9332: my $urlsymb=shift;
9333: my $symb=&symbread($urlsymb);
9334: if ($symb) {
9335: my $key=$env{'request.course.id'}."\0".$symb;
9336: my ($result,$cached)=&is_cached_new('title',$key);
9337: if (defined($cached)) {
9338: return $result;
9339: }
9340: my ($map,$resid,$url)=&decode_symb($symb);
9341: my $title='';
9342: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9343: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9344: } else {
9345: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9346: &GDBM_READER(),0640)) {
9347: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9348: $title=$bighash{'title_'.$mapid.'.'.$resid};
9349: untie(%bighash);
9350: }
9351: }
9352: $title=~s/\&colon\;/\:/gs;
9353: if ($title) {
9354: return &do_cache_new('title',$key,$title,600);
9355: }
9356: $urlsymb=$url;
9357: }
9358: my $title=&metadata($urlsymb,'title');
9359: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9360: return $title;
9361: }
9362:
9363: sub get_slot {
9364: my ($which,$cnum,$cdom)=@_;
9365: if (!$cnum || !$cdom) {
9366: (undef,my $courseid)=&whichuser();
9367: $cdom=$env{'course.'.$courseid.'.domain'};
9368: $cnum=$env{'course.'.$courseid.'.num'};
9369: }
9370: my $key=join("\0",'slots',$cdom,$cnum,$which);
9371: my %slotinfo;
9372: if (exists($remembered{$key})) {
9373: $slotinfo{$which} = $remembered{$key};
9374: } else {
9375: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9376: &Apache::lonhomework::showhash(%slotinfo);
9377: my ($tmp)=keys(%slotinfo);
9378: if ($tmp=~/^error:/) { return (); }
9379: $remembered{$key} = $slotinfo{$which};
9380: }
9381: if (ref($slotinfo{$which}) eq 'HASH') {
9382: return %{$slotinfo{$which}};
9383: }
9384: return $slotinfo{$which};
9385: }
9386: # ------------------------------------------------- Update symbolic store links
9387:
9388: sub symblist {
9389: my ($mapname,%newhash)=@_;
9390: $mapname=&deversion(&declutter($mapname));
9391: my %hash;
9392: if (($env{'request.course.fn'}) && (%newhash)) {
9393: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9394: &GDBM_WRCREAT(),0640)) {
9395: foreach my $url (keys(%newhash)) {
9396: next if ($url eq 'last_known'
9397: && $env{'form.no_update_last_known'});
9398: $hash{declutter($url)}=&encode_symb($mapname,
9399: $newhash{$url}->[1],
9400: $newhash{$url}->[0]);
9401: }
9402: if (untie(%hash)) {
9403: return 'ok';
9404: }
9405: }
9406: }
9407: return 'error';
9408: }
9409:
9410: # --------------------------------------------------------------- Verify a symb
9411:
9412: sub symbverify {
9413: my ($symb,$thisurl)=@_;
9414: my $thisfn=$thisurl;
9415: $thisfn=&declutter($thisfn);
9416: # direct jump to resource in page or to a sequence - will construct own symbs
9417: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9418: # check URL part
9419: my ($map,$resid,$url)=&decode_symb($symb);
9420:
9421: unless ($url eq $thisfn) { return 0; }
9422:
9423: $symb=&symbclean($symb);
9424: $thisurl=&deversion($thisurl);
9425: $thisfn=&deversion($thisfn);
9426:
9427: my %bighash;
9428: my $okay=0;
9429:
9430: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9431: &GDBM_READER(),0640)) {
9432: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9433: $thisurl =~ s/\?.+$//;
9434: }
9435: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9436: unless ($ids) {
9437: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9438: $ids=$bighash{$idkey};
9439: }
9440: if ($ids) {
9441: # ------------------------------------------------------------------- Has ID(s)
9442: foreach my $id (split(/\,/,$ids)) {
9443: my ($mapid,$resid)=split(/\./,$id);
9444: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9445: $symb =~ s/\?.+$//;
9446: }
9447: if (
9448: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9449: eq $symb) {
9450: if (($env{'request.role.adv'}) ||
9451: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9452: ($thisurl eq '/adm/navmaps')) {
9453: $okay=1;
9454: }
9455: }
9456: }
9457: }
9458: untie(%bighash);
9459: }
9460: return $okay;
9461: }
9462:
9463: # --------------------------------------------------------------- Clean-up symb
9464:
9465: sub symbclean {
9466: my $symb=shift;
9467: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9468: # remove version from map
9469: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9470:
9471: # remove version from URL
9472: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9473:
9474: # remove wrapper
9475:
9476: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9477: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9478: return $symb;
9479: }
9480:
9481: # ---------------------------------------------- Split symb to find map and url
9482:
9483: sub encode_symb {
9484: my ($map,$resid,$url)=@_;
9485: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9486: }
9487:
9488: sub decode_symb {
9489: my $symb=shift;
9490: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9491: my ($map,$resid,$url)=split(/___/,$symb);
9492: return (&fixversion($map),$resid,&fixversion($url));
9493: }
9494:
9495: sub fixversion {
9496: my $fn=shift;
9497: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9498: my %bighash;
9499: my $uri=&clutter($fn);
9500: my $key=$env{'request.course.id'}.'_'.$uri;
9501: # is this cached?
9502: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9503: if (defined($cached)) { return $result; }
9504: # unfortunately not cached, or expired
9505: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9506: &GDBM_READER(),0640)) {
9507: if ($bighash{'version_'.$uri}) {
9508: my $version=$bighash{'version_'.$uri};
9509: unless (($version eq 'mostrecent') ||
9510: ($version==&getversion($uri))) {
9511: $uri=~s/\.(\w+)$/\.$version\.$1/;
9512: }
9513: }
9514: untie %bighash;
9515: }
9516: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9517: }
9518:
9519: sub deversion {
9520: my $url=shift;
9521: $url=~s/\.\d+\.(\w+)$/\.$1/;
9522: return $url;
9523: }
9524:
9525: # ------------------------------------------------------ Return symb list entry
9526:
9527: sub symbread {
9528: my ($thisfn,$donotrecurse)=@_;
9529: my $cache_str='request.symbread.cached.'.$thisfn;
9530: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9531: # no filename provided? try from environment
9532: unless ($thisfn) {
9533: if ($env{'request.symb'}) {
9534: return $env{$cache_str}=&symbclean($env{'request.symb'});
9535: }
9536: $thisfn=$env{'request.filename'};
9537: }
9538: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9539: # is that filename actually a symb? Verify, clean, and return
9540: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9541: if (&symbverify($thisfn,$1)) {
9542: return $env{$cache_str}=&symbclean($thisfn);
9543: }
9544: }
9545: $thisfn=declutter($thisfn);
9546: my %hash;
9547: my %bighash;
9548: my $syval='';
9549: if (($env{'request.course.fn'}) && ($thisfn)) {
9550: my $targetfn = $thisfn;
9551: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9552: $targetfn = 'adm/wrapper/'.$thisfn;
9553: }
9554: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9555: $targetfn=$1;
9556: }
9557: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9558: &GDBM_READER(),0640)) {
9559: $syval=$hash{$targetfn};
9560: untie(%hash);
9561: }
9562: # ---------------------------------------------------------- There was an entry
9563: if ($syval) {
9564: #unless ($syval=~/\_\d+$/) {
9565: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9566: #&appenv({'request.ambiguous' => $thisfn});
9567: #return $env{$cache_str}='';
9568: #}
9569: #$syval.=$1;
9570: #}
9571: } else {
9572: # ------------------------------------------------------- Was not in symb table
9573: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9574: &GDBM_READER(),0640)) {
9575: # ---------------------------------------------- Get ID(s) for current resource
9576: my $ids=$bighash{'ids_'.&clutter($thisfn)};
9577: unless ($ids) {
9578: $ids=$bighash{'ids_/'.$thisfn};
9579: }
9580: unless ($ids) {
9581: # alias?
9582: $ids=$bighash{'mapalias_'.$thisfn};
9583: }
9584: if ($ids) {
9585: # ------------------------------------------------------------------- Has ID(s)
9586: my @possibilities=split(/\,/,$ids);
9587: if ($#possibilities==0) {
9588: # ----------------------------------------------- There is only one possibility
9589: my ($mapid,$resid)=split(/\./,$ids);
9590: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9591: $resid,$thisfn);
9592: } elsif (!$donotrecurse) {
9593: # ------------------------------------------ There is more than one possibility
9594: my $realpossible=0;
9595: foreach my $id (@possibilities) {
9596: my $file=$bighash{'src_'.$id};
9597: if (&allowed('bre',$file)) {
9598: my ($mapid,$resid)=split(/\./,$id);
9599: if ($bighash{'map_type_'.$mapid} ne 'page') {
9600: $realpossible++;
9601: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9602: $resid,$thisfn);
9603: }
9604: }
9605: }
9606: if ($realpossible!=1) { $syval=''; }
9607: } else {
9608: $syval='';
9609: }
9610: }
9611: untie(%bighash)
9612: }
9613: }
9614: if ($syval) {
9615: return $env{$cache_str}=$syval;
9616: }
9617: }
9618: &appenv({'request.ambiguous' => $thisfn});
9619: return $env{$cache_str}='';
9620: }
9621:
9622: # ---------------------------------------------------------- Return random seed
9623:
9624: sub numval {
9625: my $txt=shift;
9626: $txt=~tr/A-J/0-9/;
9627: $txt=~tr/a-j/0-9/;
9628: $txt=~tr/K-T/0-9/;
9629: $txt=~tr/k-t/0-9/;
9630: $txt=~tr/U-Z/0-5/;
9631: $txt=~tr/u-z/0-5/;
9632: $txt=~s/\D//g;
9633: if ($_64bit) { if ($txt > 2**32) { return -1; } }
9634: return int($txt);
9635: }
9636:
9637: sub numval2 {
9638: my $txt=shift;
9639: $txt=~tr/A-J/0-9/;
9640: $txt=~tr/a-j/0-9/;
9641: $txt=~tr/K-T/0-9/;
9642: $txt=~tr/k-t/0-9/;
9643: $txt=~tr/U-Z/0-5/;
9644: $txt=~tr/u-z/0-5/;
9645: $txt=~s/\D//g;
9646: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9647: my $total;
9648: foreach my $val (@txts) { $total+=$val; }
9649: if ($_64bit) { if ($total > 2**32) { return -1; } }
9650: return int($total);
9651: }
9652:
9653: sub numval3 {
9654: use integer;
9655: my $txt=shift;
9656: $txt=~tr/A-J/0-9/;
9657: $txt=~tr/a-j/0-9/;
9658: $txt=~tr/K-T/0-9/;
9659: $txt=~tr/k-t/0-9/;
9660: $txt=~tr/U-Z/0-5/;
9661: $txt=~tr/u-z/0-5/;
9662: $txt=~s/\D//g;
9663: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9664: my $total;
9665: foreach my $val (@txts) { $total+=$val; }
9666: if ($_64bit) { $total=(($total<<32)>>32); }
9667: return $total;
9668: }
9669:
9670: sub digest {
9671: my ($data)=@_;
9672: my $digest=&Digest::MD5::md5($data);
9673: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9674: my ($e,$f);
9675: {
9676: use integer;
9677: $e=($a+$b);
9678: $f=($c+$d);
9679: if ($_64bit) {
9680: $e=(($e<<32)>>32);
9681: $f=(($f<<32)>>32);
9682: }
9683: }
9684: if (wantarray) {
9685: return ($e,$f);
9686: } else {
9687: my $g;
9688: {
9689: use integer;
9690: $g=($e+$f);
9691: if ($_64bit) {
9692: $g=(($g<<32)>>32);
9693: }
9694: }
9695: return $g;
9696: }
9697: }
9698:
9699: sub latest_rnd_algorithm_id {
9700: return '64bit5';
9701: }
9702:
9703: sub get_rand_alg {
9704: my ($courseid)=@_;
9705: if (!$courseid) { $courseid=(&whichuser())[1]; }
9706: if ($courseid) {
9707: return $env{"course.$courseid.rndseed"};
9708: }
9709: return &latest_rnd_algorithm_id();
9710: }
9711:
9712: sub validCODE {
9713: my ($CODE)=@_;
9714: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9715: return 0;
9716: }
9717:
9718: sub getCODE {
9719: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
9720: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9721: defined($Apache::lonhomework::parsing_a_task) ) &&
9722: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
9723: return $Apache::lonhomework::history{'resource.CODE'};
9724: }
9725: return undef;
9726: }
9727: #
9728: # Determines the random seed for a specific context:
9729: #
9730: # parameters:
9731: # symb - in course context the symb for the seed.
9732: # course_id - The course id of the form domain_coursenum.
9733: # domain - Domain for the user.
9734: # course - Course for the user.
9735: # cenv - environment of the course.
9736: #
9737: # NOTE:
9738: # All parameters are picked out of the environment if missing
9739: # or not defined.
9740: # If a symb cannot be determined the current time is used instead.
9741: #
9742: # For a given well defined symb, courside, domain, username,
9743: # and course environment, the seed is reproducible.
9744: #
9745: sub rndseed {
9746: my ($symb,$courseid,$domain,$username, $cenv)=@_;
9747: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
9748: if (!defined($symb)) {
9749: unless ($symb=$wsymb) { return time; }
9750: }
9751: if (!$courseid) { $courseid=$wcourseid; }
9752: if (!$domain) { $domain=$wdomain; }
9753: if (!$username) { $username=$wusername }
9754:
9755: my $which;
9756: if (defined($cenv->{'rndseed'})) {
9757: $which = $cenv->{'rndseed'};
9758: } else {
9759: $which =&get_rand_alg($courseid);
9760: }
9761:
9762: if (defined(&getCODE())) {
9763:
9764: if ($which eq '64bit5') {
9765: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9766: } elsif ($which eq '64bit4') {
9767: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9768: } else {
9769: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9770: }
9771: } elsif ($which eq '64bit5') {
9772: return &rndseed_64bit5($symb,$courseid,$domain,$username);
9773: } elsif ($which eq '64bit4') {
9774: return &rndseed_64bit4($symb,$courseid,$domain,$username);
9775: } elsif ($which eq '64bit3') {
9776: return &rndseed_64bit3($symb,$courseid,$domain,$username);
9777: } elsif ($which eq '64bit2') {
9778: return &rndseed_64bit2($symb,$courseid,$domain,$username);
9779: } elsif ($which eq '64bit') {
9780: return &rndseed_64bit($symb,$courseid,$domain,$username);
9781: }
9782: return &rndseed_32bit($symb,$courseid,$domain,$username);
9783: }
9784:
9785: sub rndseed_32bit {
9786: my ($symb,$courseid,$domain,$username)=@_;
9787: {
9788: use integer;
9789: my $symbchck=unpack("%32C*",$symb) << 27;
9790: my $symbseed=numval($symb) << 22;
9791: my $namechck=unpack("%32C*",$username) << 17;
9792: my $nameseed=numval($username) << 12;
9793: my $domainseed=unpack("%32C*",$domain) << 7;
9794: my $courseseed=unpack("%32C*",$courseid);
9795: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
9796: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9797: #&logthis("rndseed :$num:$symb");
9798: if ($_64bit) { $num=(($num<<32)>>32); }
9799: return $num;
9800: }
9801: }
9802:
9803: sub rndseed_64bit {
9804: my ($symb,$courseid,$domain,$username)=@_;
9805: {
9806: use integer;
9807: my $symbchck=unpack("%32S*",$symb) << 21;
9808: my $symbseed=numval($symb) << 10;
9809: my $namechck=unpack("%32S*",$username);
9810:
9811: my $nameseed=numval($username) << 21;
9812: my $domainseed=unpack("%32S*",$domain) << 10;
9813: my $courseseed=unpack("%32S*",$courseid);
9814:
9815: my $num1=$symbchck+$symbseed+$namechck;
9816: my $num2=$nameseed+$domainseed+$courseseed;
9817: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9818: #&logthis("rndseed :$num:$symb");
9819: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9820: return "$num1,$num2";
9821: }
9822: }
9823:
9824: sub rndseed_64bit2 {
9825: my ($symb,$courseid,$domain,$username)=@_;
9826: {
9827: use integer;
9828: # strings need to be an even # of cahracters long, it it is odd the
9829: # last characters gets thrown away
9830: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9831: my $symbseed=numval($symb) << 10;
9832: my $namechck=unpack("%32S*",$username.' ');
9833:
9834: my $nameseed=numval($username) << 21;
9835: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9836: my $courseseed=unpack("%32S*",$courseid.' ');
9837:
9838: my $num1=$symbchck+$symbseed+$namechck;
9839: my $num2=$nameseed+$domainseed+$courseseed;
9840: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9841: #&logthis("rndseed :$num:$symb");
9842: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9843: return "$num1,$num2";
9844: }
9845: }
9846:
9847: sub rndseed_64bit3 {
9848: my ($symb,$courseid,$domain,$username)=@_;
9849: {
9850: use integer;
9851: # strings need to be an even # of cahracters long, it it is odd the
9852: # last characters gets thrown away
9853: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9854: my $symbseed=numval2($symb) << 10;
9855: my $namechck=unpack("%32S*",$username.' ');
9856:
9857: my $nameseed=numval2($username) << 21;
9858: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9859: my $courseseed=unpack("%32S*",$courseid.' ');
9860:
9861: my $num1=$symbchck+$symbseed+$namechck;
9862: my $num2=$nameseed+$domainseed+$courseseed;
9863: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9864: #&logthis("rndseed :$num1:$num2:$_64bit");
9865: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9866:
9867: return "$num1:$num2";
9868: }
9869: }
9870:
9871: sub rndseed_64bit4 {
9872: my ($symb,$courseid,$domain,$username)=@_;
9873: {
9874: use integer;
9875: # strings need to be an even # of cahracters long, it it is odd the
9876: # last characters gets thrown away
9877: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9878: my $symbseed=numval3($symb) << 10;
9879: my $namechck=unpack("%32S*",$username.' ');
9880:
9881: my $nameseed=numval3($username) << 21;
9882: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9883: my $courseseed=unpack("%32S*",$courseid.' ');
9884:
9885: my $num1=$symbchck+$symbseed+$namechck;
9886: my $num2=$nameseed+$domainseed+$courseseed;
9887: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9888: #&logthis("rndseed :$num1:$num2:$_64bit");
9889: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
9890:
9891: return "$num1:$num2";
9892: }
9893: }
9894:
9895: sub rndseed_64bit5 {
9896: my ($symb,$courseid,$domain,$username)=@_;
9897: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9898: return "$num1:$num2";
9899: }
9900:
9901: sub rndseed_CODE_64bit {
9902: my ($symb,$courseid,$domain,$username)=@_;
9903: {
9904: use integer;
9905: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9906: my $symbseed=numval2($symb);
9907: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9908: my $CODEseed=numval(&getCODE());
9909: my $courseseed=unpack("%32S*",$courseid.' ');
9910: my $num1=$symbseed+$CODEchck;
9911: my $num2=$CODEseed+$courseseed+$symbchck;
9912: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9913: #&logthis("rndseed :$num1:$num2:$symb");
9914: if ($_64bit) { $num1=(($num1<<32)>>32); }
9915: if ($_64bit) { $num2=(($num2<<32)>>32); }
9916: return "$num1:$num2";
9917: }
9918: }
9919:
9920: sub rndseed_CODE_64bit4 {
9921: my ($symb,$courseid,$domain,$username)=@_;
9922: {
9923: use integer;
9924: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9925: my $symbseed=numval3($symb);
9926: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9927: my $CODEseed=numval3(&getCODE());
9928: my $courseseed=unpack("%32S*",$courseid.' ');
9929: my $num1=$symbseed+$CODEchck;
9930: my $num2=$CODEseed+$courseseed+$symbchck;
9931: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9932: #&logthis("rndseed :$num1:$num2:$symb");
9933: if ($_64bit) { $num1=(($num1<<32)>>32); }
9934: if ($_64bit) { $num2=(($num2<<32)>>32); }
9935: return "$num1:$num2";
9936: }
9937: }
9938:
9939: sub rndseed_CODE_64bit5 {
9940: my ($symb,$courseid,$domain,$username)=@_;
9941: my $code = &getCODE();
9942: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9943: return "$num1:$num2";
9944: }
9945:
9946: sub setup_random_from_rndseed {
9947: my ($rndseed)=@_;
9948: if ($rndseed =~/([,:])/) {
9949: my ($num1,$num2)=split(/[,:]/,$rndseed);
9950: &Math::Random::random_set_seed(abs($num1),abs($num2));
9951: } else {
9952: &Math::Random::random_set_seed_from_phrase($rndseed);
9953: }
9954: }
9955:
9956: sub latest_receipt_algorithm_id {
9957: return 'receipt3';
9958: }
9959:
9960: sub recunique {
9961: my $fucourseid=shift;
9962: my $unique;
9963: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9964: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9965: $unique=$env{"course.$fucourseid.internal.encseed"};
9966: } else {
9967: $unique=$perlvar{'lonReceipt'};
9968: }
9969: return unpack("%32C*",$unique);
9970: }
9971:
9972: sub recprefix {
9973: my $fucourseid=shift;
9974: my $prefix;
9975: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9976: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
9977: $prefix=$env{"course.$fucourseid.internal.encpref"};
9978: } else {
9979: $prefix=$perlvar{'lonHostID'};
9980: }
9981: return unpack("%32C*",$prefix);
9982: }
9983:
9984: sub ireceipt {
9985: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
9986:
9987: my $return =&recprefix($fucourseid).'-';
9988:
9989: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9990: $env{'request.state'} eq 'construct') {
9991: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9992: return $return;
9993: }
9994:
9995: my $cuname=unpack("%32C*",$funame);
9996: my $cudom=unpack("%32C*",$fudom);
9997: my $cucourseid=unpack("%32C*",$fucourseid);
9998: my $cusymb=unpack("%32C*",$fusymb);
9999: my $cunique=&recunique($fucourseid);
10000: my $cpart=unpack("%32S*",$part);
10001: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10002:
10003: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10004:
10005: $return.= ($cunique%$cuname+
10006: $cunique%$cudom+
10007: $cusymb%$cuname+
10008: $cusymb%$cudom+
10009: $cucourseid%$cuname+
10010: $cucourseid%$cudom+
10011: $cpart%$cuname+
10012: $cpart%$cudom);
10013: } else {
10014: $return.= ($cunique%$cuname+
10015: $cunique%$cudom+
10016: $cusymb%$cuname+
10017: $cusymb%$cudom+
10018: $cucourseid%$cuname+
10019: $cucourseid%$cudom);
10020: }
10021: return $return;
10022: }
10023:
10024: sub receipt {
10025: my ($part)=@_;
10026: my ($symb,$courseid,$domain,$name) = &whichuser();
10027: return &ireceipt($name,$domain,$courseid,$symb,$part);
10028: }
10029:
10030: sub whichuser {
10031: my ($passedsymb)=@_;
10032: my ($symb,$courseid,$domain,$name,$publicuser);
10033: if (defined($env{'form.grade_symb'})) {
10034: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10035: my $allowed=&allowed('vgr',$tmp_courseid);
10036: if (!$allowed &&
10037: exists($env{'request.course.sec'}) &&
10038: $env{'request.course.sec'} !~ /^\s*$/) {
10039: $allowed=&allowed('vgr',$tmp_courseid.
10040: '/'.$env{'request.course.sec'});
10041: }
10042: if ($allowed) {
10043: ($symb)=&get_env_multiple('form.grade_symb');
10044: $courseid=$tmp_courseid;
10045: ($domain)=&get_env_multiple('form.grade_domain');
10046: ($name)=&get_env_multiple('form.grade_username');
10047: return ($symb,$courseid,$domain,$name,$publicuser);
10048: }
10049: }
10050: if (!$passedsymb) {
10051: $symb=&symbread();
10052: } else {
10053: $symb=$passedsymb;
10054: }
10055: $courseid=$env{'request.course.id'};
10056: $domain=$env{'user.domain'};
10057: $name=$env{'user.name'};
10058: if ($name eq 'public' && $domain eq 'public') {
10059: if (!defined($env{'form.username'})) {
10060: $env{'form.username'}.=time.rand(10000000);
10061: }
10062: $name.=$env{'form.username'};
10063: }
10064: return ($symb,$courseid,$domain,$name,$publicuser);
10065:
10066: }
10067:
10068: # ------------------------------------------------------------ Serves up a file
10069: # returns either the contents of the file or
10070: # -1 if the file doesn't exist
10071: #
10072: # if the target is a file that was uploaded via DOCS,
10073: # a check will be made to see if a current copy exists on the local server,
10074: # if it does this will be served, otherwise a copy will be retrieved from
10075: # the home server for the course and stored in /home/httpd/html/userfiles on
10076: # the local server.
10077:
10078: sub getfile {
10079: my ($file) = @_;
10080: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10081: &repcopy($file);
10082: return &readfile($file);
10083: }
10084:
10085: sub repcopy_userfile {
10086: my ($file)=@_;
10087: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10088: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
10089: my ($cdom,$cnum,$filename) =
10090: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10091: my $uri="/uploaded/$cdom/$cnum/$filename";
10092: if (-e "$file") {
10093: # we already have a local copy, check it out
10094: my @fileinfo = stat($file);
10095: my $rtncode;
10096: my $info;
10097: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10098: if ($lwpresp ne 'ok') {
10099: # there is no such file anymore, even though we had a local copy
10100: if ($rtncode eq '404') {
10101: unlink($file);
10102: }
10103: return -1;
10104: }
10105: if ($info < $fileinfo[9]) {
10106: # nice, the file we have is up-to-date, just say okay
10107: return 'ok';
10108: } else {
10109: # the file is outdated, get rid of it
10110: unlink($file);
10111: }
10112: }
10113: # one way or the other, at this point, we don't have the file
10114: # construct the correct path for the file
10115: my @parts = ($cdom,$cnum);
10116: if ($filename =~ m|^(.+)/[^/]+$|) {
10117: push @parts, split(/\//,$1);
10118: }
10119: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10120: foreach my $part (@parts) {
10121: $path .= '/'.$part;
10122: if (!-e $path) {
10123: mkdir($path,0770);
10124: }
10125: }
10126: # now the path exists for sure
10127: # get a user agent
10128: my $ua=new LWP::UserAgent;
10129: my $transferfile=$file.'.in.transfer';
10130: # FIXME: this should flock
10131: if (-e $transferfile) { return 'ok'; }
10132: my $request;
10133: $uri=~s/^\///;
10134: my $homeserver = &homeserver($cnum,$cdom);
10135: my $protocol = $protocol{$homeserver};
10136: $protocol = 'http' if ($protocol ne 'https');
10137: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10138: my $response=$ua->request($request,$transferfile);
10139: # did it work?
10140: if ($response->is_error()) {
10141: unlink($transferfile);
10142: &logthis("Userfile repcopy failed for $uri");
10143: return -1;
10144: }
10145: # worked, rename the transfer file
10146: rename($transferfile,$file);
10147: return 'ok';
10148: }
10149:
10150: sub tokenwrapper {
10151: my $uri=shift;
10152: $uri=~s|^https?\://([^/]+)||;
10153: $uri=~s|^/||;
10154: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10155: my $token=$1;
10156: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10157: if ($udom && $uname && $file) {
10158: $file=~s|(\?\.*)*$||;
10159: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10160: my $homeserver = &homeserver($uname,$udom);
10161: my $protocol = $protocol{$homeserver};
10162: $protocol = 'http' if ($protocol ne 'https');
10163: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10164: (($uri=~/\?/)?'&':'?').'token='.$token.
10165: '&tokenissued='.$perlvar{'lonHostID'};
10166: } else {
10167: return '/adm/notfound.html';
10168: }
10169: }
10170:
10171: # call with reqtype HEAD: get last modification time
10172: # call with reqtype GET: get the file contents
10173: # Do not call this with reqtype GET for large files! It loads everything into memory
10174: #
10175: sub getuploaded {
10176: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10177: $uri=~s/^\///;
10178: my $homeserver = &homeserver($cnum,$cdom);
10179: my $protocol = $protocol{$homeserver};
10180: $protocol = 'http' if ($protocol ne 'https');
10181: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10182: my $ua=new LWP::UserAgent;
10183: my $request=new HTTP::Request($reqtype,$uri);
10184: my $response=$ua->request($request);
10185: $$rtncode = $response->code;
10186: if (! $response->is_success()) {
10187: return 'failed';
10188: }
10189: if ($reqtype eq 'HEAD') {
10190: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10191: } elsif ($reqtype eq 'GET') {
10192: $$info = $response->content;
10193: }
10194: return 'ok';
10195: }
10196:
10197: sub readfile {
10198: my $file = shift;
10199: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10200: my $fh;
10201: open($fh,"<$file");
10202: my $a='';
10203: while (my $line = <$fh>) { $a .= $line; }
10204: return $a;
10205: }
10206:
10207: sub filelocation {
10208: my ($dir,$file) = @_;
10209: my $location;
10210: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10211:
10212: if ($file =~ m-^/adm/-) {
10213: $file=~s-^/adm/wrapper/-/-;
10214: $file=~s-^/adm/coursedocs/showdoc/-/-;
10215: }
10216:
10217: if ($file=~m:^/~:) { # is a contruction space reference
10218: $location = $file;
10219: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
10220: } elsif ($file=~m{^/home/$match_username/public_html/}) {
10221: # is a correct contruction space reference
10222: $location = $file;
10223: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10224: $location = $file;
10225: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10226: my ($udom,$uname,$filename)=
10227: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10228: my $home=&homeserver($uname,$udom);
10229: my $is_me=0;
10230: my @ids=¤t_machine_ids();
10231: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10232: if ($is_me) {
10233: $location=propath($udom,$uname).'/userfiles/'.$filename;
10234: } else {
10235: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10236: $udom.'/'.$uname.'/'.$filename;
10237: }
10238: } elsif ($file =~ m-^/adm/-) {
10239: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10240: } else {
10241: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10242: $file=~s:^/res/:/:;
10243: if ( !( $file =~ m:^/:) ) {
10244: $location = $dir. '/'.$file;
10245: } else {
10246: $location = '/home/httpd/html/res'.$file;
10247: }
10248: }
10249: $location=~s://+:/:g; # remove duplicate /
10250: while ($location=~m{/\.\./}) {
10251: if ($location =~ m{/[^/]+/\.\./}) {
10252: $location=~ s{/[^/]+/\.\./}{/}g;
10253: } else {
10254: $location=~ s{/\.\./}{/}g;
10255: }
10256: } #remove dir/..
10257: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10258: return $location;
10259: }
10260:
10261: sub hreflocation {
10262: my ($dir,$file)=@_;
10263: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10264: $file=filelocation($dir,$file);
10265: } elsif ($file=~m-^/adm/-) {
10266: $file=~s-^/adm/wrapper/-/-;
10267: $file=~s-^/adm/coursedocs/showdoc/-/-;
10268: }
10269: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10270: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10271: } elsif ($file=~m-/home/($match_username)/public_html/-) {
10272: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
10273: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10274: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
10275: -/uploaded/$1/$2/-x;
10276: }
10277: if ($file=~ m{^/userfiles/}) {
10278: $file =~ s{^/userfiles/}{/uploaded/};
10279: }
10280: return $file;
10281: }
10282:
10283: sub current_machine_domains {
10284: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10285: }
10286:
10287: sub machine_domains {
10288: my ($hostname) = @_;
10289: my @domains;
10290: my %hostname = &all_hostnames();
10291: while( my($id, $name) = each(%hostname)) {
10292: # &logthis("-$id-$name-$hostname-");
10293: if ($hostname eq $name) {
10294: push(@domains,&host_domain($id));
10295: }
10296: }
10297: return @domains;
10298: }
10299:
10300: sub current_machine_ids {
10301: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10302: }
10303:
10304: sub machine_ids {
10305: my ($hostname) = @_;
10306: $hostname ||= &hostname($perlvar{'lonHostID'});
10307: my @ids;
10308: my %name_to_host = &all_names();
10309: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10310: return @{ $name_to_host{$hostname} };
10311: }
10312: return;
10313: }
10314:
10315: sub additional_machine_domains {
10316: my @domains;
10317: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10318: while( my $line = <$fh>) {
10319: $line =~ s/\s//g;
10320: push(@domains,$line);
10321: }
10322: return @domains;
10323: }
10324:
10325: sub default_login_domain {
10326: my $domain = $perlvar{'lonDefDomain'};
10327: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10328: foreach my $posdom (¤t_machine_domains(),
10329: &additional_machine_domains()) {
10330: if (lc($posdom) eq lc($testdomain)) {
10331: $domain=$posdom;
10332: last;
10333: }
10334: }
10335: return $domain;
10336: }
10337:
10338: # ------------------------------------------------------------- Declutters URLs
10339:
10340: sub declutter {
10341: my $thisfn=shift;
10342: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10343: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10344: $thisfn=~s/^\///;
10345: $thisfn=~s|^adm/wrapper/||;
10346: $thisfn=~s|^adm/coursedocs/showdoc/||;
10347: $thisfn=~s/^res\///;
10348: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10349: $thisfn=~s/\?.+$//;
10350: }
10351: return $thisfn;
10352: }
10353:
10354: # ------------------------------------------------------------- Clutter up URLs
10355:
10356: sub clutter {
10357: my $thisfn='/'.&declutter(shift);
10358: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10359: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10360: $thisfn='/res'.$thisfn;
10361: }
10362: if ($thisfn !~m|^/adm|) {
10363: if ($thisfn =~ m|^/ext/|) {
10364: $thisfn='/adm/wrapper'.$thisfn;
10365: } else {
10366: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10367: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10368: if ($embstyle eq 'ssi'
10369: || ($embstyle eq 'hdn')
10370: || ($embstyle eq 'rat')
10371: || ($embstyle eq 'prv')
10372: || ($embstyle eq 'ign')) {
10373: #do nothing with these
10374: } elsif (($embstyle eq 'img')
10375: || ($embstyle eq 'emb')
10376: || ($embstyle eq 'wrp')) {
10377: $thisfn='/adm/wrapper'.$thisfn;
10378: } elsif ($embstyle eq 'unk'
10379: && $thisfn!~/\.(sequence|page)$/) {
10380: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10381: } else {
10382: # &logthis("Got a blank emb style");
10383: }
10384: }
10385: }
10386: return $thisfn;
10387: }
10388:
10389: sub clutter_with_no_wrapper {
10390: my $uri = &clutter(shift);
10391: if ($uri =~ m-^/adm/-) {
10392: $uri =~ s-^/adm/wrapper/-/-;
10393: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10394: }
10395: return $uri;
10396: }
10397:
10398: sub freeze_escape {
10399: my ($value)=@_;
10400: if (ref($value)) {
10401: $value=&nfreeze($value);
10402: return '__FROZEN__'.&escape($value);
10403: }
10404: return &escape($value);
10405: }
10406:
10407:
10408: sub thaw_unescape {
10409: my ($value)=@_;
10410: if ($value =~ /^__FROZEN__/) {
10411: substr($value,0,10,undef);
10412: $value=&unescape($value);
10413: return &thaw($value);
10414: }
10415: return &unescape($value);
10416: }
10417:
10418: sub correct_line_ends {
10419: my ($result)=@_;
10420: $$result =~s/\r\n/\n/mg;
10421: $$result =~s/\r/\n/mg;
10422: }
10423: # ================================================================ Main Program
10424:
10425: sub goodbye {
10426: &logthis("Starting Shut down");
10427: #not converted to using infrastruture and probably shouldn't be
10428: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10429: #converted
10430: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10431: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10432: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10433: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10434: #1.1 only
10435: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10436: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10437: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10438: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10439: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10440: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10441: &logthis(sprintf("%-20s is %s",'hits',$hits));
10442: &flushcourselogs();
10443: &logthis("Shutting down");
10444: }
10445:
10446: sub get_dns {
10447: my ($url,$func,$ignore_cache) = @_;
10448: if (!$ignore_cache) {
10449: my ($content,$cached)=
10450: &Apache::lonnet::is_cached_new('dns',$url);
10451: if ($cached) {
10452: &$func($content);
10453: return;
10454: }
10455: }
10456:
10457: my %alldns;
10458: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10459: foreach my $dns (<$config>) {
10460: next if ($dns !~ /^\^(\S*)/x);
10461: my $line = $1;
10462: my ($host,$protocol) = split(/:/,$line);
10463: if ($protocol ne 'https') {
10464: $protocol = 'http';
10465: }
10466: $alldns{$host} = $protocol;
10467: }
10468: while (%alldns) {
10469: my ($dns) = keys(%alldns);
10470: my $ua=new LWP::UserAgent;
10471: $ua->timeout(30);
10472: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10473: my $response=$ua->request($request);
10474: delete($alldns{$dns});
10475: next if ($response->is_error());
10476: my @content = split("\n",$response->content);
10477: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10478: &$func(\@content);
10479: return;
10480: }
10481: close($config);
10482: my $which = (split('/',$url))[3];
10483: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10484: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10485: my @content = <$config>;
10486: &$func(\@content);
10487: return;
10488: }
10489: # ------------------------------------------------------------ Read domain file
10490: {
10491: my $loaded;
10492: my %domain;
10493:
10494: sub parse_domain_tab {
10495: my ($lines) = @_;
10496: foreach my $line (@$lines) {
10497: next if ($line =~ /^(\#|\s*$ )/x);
10498:
10499: chomp($line);
10500: my ($name,@elements) = split(/:/,$line,9);
10501: my %this_domain;
10502: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10503: 'lang_def', 'city', 'longi', 'lati',
10504: 'primary') {
10505: $this_domain{$field} = shift(@elements);
10506: }
10507: $domain{$name} = \%this_domain;
10508: }
10509: }
10510:
10511: sub reset_domain_info {
10512: undef($loaded);
10513: undef(%domain);
10514: }
10515:
10516: sub load_domain_tab {
10517: my ($ignore_cache) = @_;
10518: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10519: my $fh;
10520: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10521: my @lines = <$fh>;
10522: &parse_domain_tab(\@lines);
10523: }
10524: close($fh);
10525: $loaded = 1;
10526: }
10527:
10528: sub domain {
10529: &load_domain_tab() if (!$loaded);
10530:
10531: my ($name,$what) = @_;
10532: return if ( !exists($domain{$name}) );
10533:
10534: if (!$what) {
10535: return $domain{$name}{'description'};
10536: }
10537: return $domain{$name}{$what};
10538: }
10539:
10540: sub domain_info {
10541: &load_domain_tab() if (!$loaded);
10542: return %domain;
10543: }
10544:
10545: }
10546:
10547:
10548: # ------------------------------------------------------------- Read hosts file
10549: {
10550: my %hostname;
10551: my %hostdom;
10552: my %libserv;
10553: my $loaded;
10554: my %name_to_host;
10555: my %internetdom;
10556: my %LC_dns_serv;
10557:
10558: sub parse_hosts_tab {
10559: my ($file) = @_;
10560: foreach my $configline (@$file) {
10561: next if ($configline =~ /^(\#|\s*$ )/x);
10562: chomp($configline);
10563: if ($configline =~ /^\^/) {
10564: if ($configline =~ /^\^([\w.\-]+)/) {
10565: $LC_dns_serv{$1} = 1;
10566: }
10567: next;
10568: }
10569: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10570: $name=~s/\s//g;
10571: if ($id && $domain && $role && $name) {
10572: $hostname{$id}=$name;
10573: push(@{$name_to_host{$name}}, $id);
10574: $hostdom{$id}=$domain;
10575: if ($role eq 'library') { $libserv{$id}=$name; }
10576: if (defined($protocol)) {
10577: if ($protocol eq 'https') {
10578: $protocol{$id} = $protocol;
10579: } else {
10580: $protocol{$id} = 'http';
10581: }
10582: } else {
10583: $protocol{$id} = 'http';
10584: }
10585: if (defined($intdom)) {
10586: $internetdom{$id} = $intdom;
10587: }
10588: }
10589: }
10590: }
10591:
10592: sub reset_hosts_info {
10593: &purge_remembered();
10594: &reset_domain_info();
10595: &reset_hosts_ip_info();
10596: undef(%name_to_host);
10597: undef(%hostname);
10598: undef(%hostdom);
10599: undef(%libserv);
10600: undef($loaded);
10601: }
10602:
10603: sub load_hosts_tab {
10604: my ($ignore_cache) = @_;
10605: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
10606: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10607: my @config = <$config>;
10608: &parse_hosts_tab(\@config);
10609: close($config);
10610: $loaded=1;
10611: }
10612:
10613: sub hostname {
10614: &load_hosts_tab() if (!$loaded);
10615:
10616: my ($lonid) = @_;
10617: return $hostname{$lonid};
10618: }
10619:
10620: sub all_hostnames {
10621: &load_hosts_tab() if (!$loaded);
10622:
10623: return %hostname;
10624: }
10625:
10626: sub all_names {
10627: &load_hosts_tab() if (!$loaded);
10628:
10629: return %name_to_host;
10630: }
10631:
10632: sub all_host_domain {
10633: &load_hosts_tab() if (!$loaded);
10634: return %hostdom;
10635: }
10636:
10637: sub is_library {
10638: &load_hosts_tab() if (!$loaded);
10639:
10640: return exists($libserv{$_[0]});
10641: }
10642:
10643: sub all_library {
10644: &load_hosts_tab() if (!$loaded);
10645:
10646: return %libserv;
10647: }
10648:
10649: sub unique_library {
10650: #2x reverse removes all hostnames that appear more than once
10651: my %unique = reverse &all_library();
10652: return reverse %unique;
10653: }
10654:
10655: sub get_servers {
10656: &load_hosts_tab() if (!$loaded);
10657:
10658: my ($domain,$type) = @_;
10659: my %possible_hosts = ($type eq 'library') ? %libserv
10660: : %hostname;
10661: my %result;
10662: if (ref($domain) eq 'ARRAY') {
10663: while ( my ($host,$hostname) = each(%possible_hosts)) {
10664: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
10665: $result{$host} = $hostname;
10666: }
10667: }
10668: } else {
10669: while ( my ($host,$hostname) = each(%possible_hosts)) {
10670: if ($hostdom{$host} eq $domain) {
10671: $result{$host} = $hostname;
10672: }
10673: }
10674: }
10675: return %result;
10676: }
10677:
10678: sub get_unique_servers {
10679: my %unique = reverse &get_servers(@_);
10680: return reverse %unique;
10681: }
10682:
10683: sub host_domain {
10684: &load_hosts_tab() if (!$loaded);
10685:
10686: my ($lonid) = @_;
10687: return $hostdom{$lonid};
10688: }
10689:
10690: sub all_domains {
10691: &load_hosts_tab() if (!$loaded);
10692:
10693: my %seen;
10694: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10695: return @uniq;
10696: }
10697:
10698: sub internet_dom {
10699: &load_hosts_tab() if (!$loaded);
10700:
10701: my ($lonid) = @_;
10702: return $internetdom{$lonid};
10703: }
10704:
10705: sub is_LC_dns {
10706: &load_hosts_tab() if (!$loaded);
10707:
10708: my ($hostname) = @_;
10709: return exists($LC_dns_serv{$hostname});
10710: }
10711:
10712: }
10713:
10714: {
10715: my %iphost;
10716: my %name_to_ip;
10717: my %lonid_to_ip;
10718:
10719: sub get_hosts_from_ip {
10720: my ($ip) = @_;
10721: my %iphosts = &get_iphost();
10722: if (ref($iphosts{$ip})) {
10723: return @{$iphosts{$ip}};
10724: }
10725: return;
10726: }
10727:
10728: sub reset_hosts_ip_info {
10729: undef(%iphost);
10730: undef(%name_to_ip);
10731: undef(%lonid_to_ip);
10732: }
10733:
10734: sub get_host_ip {
10735: my ($lonid) = @_;
10736: if (exists($lonid_to_ip{$lonid})) {
10737: return $lonid_to_ip{$lonid};
10738: }
10739: my $name=&hostname($lonid);
10740: my $ip = gethostbyname($name);
10741: return if (!$ip || length($ip) ne 4);
10742: $ip=inet_ntoa($ip);
10743: $name_to_ip{$name} = $ip;
10744: $lonid_to_ip{$lonid} = $ip;
10745: return $ip;
10746: }
10747:
10748: sub get_iphost {
10749: my ($ignore_cache) = @_;
10750:
10751: if (!$ignore_cache) {
10752: if (%iphost) {
10753: return %iphost;
10754: }
10755: my ($ip_info,$cached)=
10756: &Apache::lonnet::is_cached_new('iphost','iphost');
10757: if ($cached) {
10758: %iphost = %{$ip_info->[0]};
10759: %name_to_ip = %{$ip_info->[1]};
10760: %lonid_to_ip = %{$ip_info->[2]};
10761: return %iphost;
10762: }
10763: }
10764:
10765: # get yesterday's info for fallback
10766: my %old_name_to_ip;
10767: my ($ip_info,$cached)=
10768: &Apache::lonnet::is_cached_new('iphost','iphost');
10769: if ($cached) {
10770: %old_name_to_ip = %{$ip_info->[1]};
10771: }
10772:
10773: my %name_to_host = &all_names();
10774: foreach my $name (keys(%name_to_host)) {
10775: my $ip;
10776: if (!exists($name_to_ip{$name})) {
10777: $ip = gethostbyname($name);
10778: if (!$ip || length($ip) ne 4) {
10779: if (defined($old_name_to_ip{$name})) {
10780: $ip = $old_name_to_ip{$name};
10781: &logthis("Can't find $name defaulting to old $ip");
10782: } else {
10783: &logthis("Name $name no IP found");
10784: next;
10785: }
10786: } else {
10787: $ip=inet_ntoa($ip);
10788: }
10789: $name_to_ip{$name} = $ip;
10790: } else {
10791: $ip = $name_to_ip{$name};
10792: }
10793: foreach my $id (@{ $name_to_host{$name} }) {
10794: $lonid_to_ip{$id} = $ip;
10795: }
10796: push(@{$iphost{$ip}},@{$name_to_host{$name}});
10797: }
10798: &Apache::lonnet::do_cache_new('iphost','iphost',
10799: [\%iphost,\%name_to_ip,\%lonid_to_ip],
10800: 48*60*60);
10801:
10802: return %iphost;
10803: }
10804:
10805: #
10806: # Given a DNS returns the loncapa host name for that DNS
10807: #
10808: sub host_from_dns {
10809: my ($dns) = @_;
10810: my @hosts;
10811: my $ip;
10812:
10813: if (exists($name_to_ip{$dns})) {
10814: $ip = $name_to_ip{$dns};
10815: }
10816: if (!$ip) {
10817: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10818: if (length($ip) == 4) {
10819: $ip = &IO::Socket::inet_ntoa($ip);
10820: }
10821: }
10822: if ($ip) {
10823: @hosts = get_hosts_from_ip($ip);
10824: return $hosts[0];
10825: }
10826: return undef;
10827: }
10828:
10829: sub get_internet_names {
10830: my ($lonid) = @_;
10831: return if ($lonid eq '');
10832: my ($idnref,$cached)=
10833: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10834: if ($cached) {
10835: return $idnref;
10836: }
10837: my $ip = &get_host_ip($lonid);
10838: my @hosts = &get_hosts_from_ip($ip);
10839: my %iphost = &get_iphost();
10840: my (@idns,%seen);
10841: foreach my $id (@hosts) {
10842: my $dom = &host_domain($id);
10843: my $prim_id = &domain($dom,'primary');
10844: my $prim_ip = &get_host_ip($prim_id);
10845: next if ($seen{$prim_ip});
10846: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10847: foreach my $id (@{$iphost{$prim_ip}}) {
10848: my $intdom = &internet_dom($id);
10849: unless (grep(/^\Q$intdom\E$/,@idns)) {
10850: push(@idns,$intdom);
10851: }
10852: }
10853: }
10854: $seen{$prim_ip} = 1;
10855: }
10856: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10857: }
10858:
10859: }
10860:
10861: sub all_loncaparevs {
10862: 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);
10863: }
10864:
10865: BEGIN {
10866:
10867: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10868: unless ($readit) {
10869: {
10870: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10871: %perlvar = (%perlvar,%{$configvars});
10872: }
10873:
10874:
10875: # ------------------------------------------------------ Read spare server file
10876: {
10877: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
10878:
10879: while (my $configline=<$config>) {
10880: chomp($configline);
10881: if ($configline) {
10882: my ($host,$type) = split(':',$configline,2);
10883: if (!defined($type) || $type eq '') { $type = 'default' };
10884: push(@{ $spareid{$type} }, $host);
10885: }
10886: }
10887: close($config);
10888: }
10889: # ------------------------------------------------------------ Read permissions
10890: {
10891: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
10892:
10893: while (my $configline=<$config>) {
10894: chomp($configline);
10895: if ($configline) {
10896: my ($role,$perm)=split(/ /,$configline);
10897: if ($perm ne '') { $pr{$role}=$perm; }
10898: }
10899: }
10900: close($config);
10901: }
10902:
10903: # -------------------------------------------- Read plain texts for permissions
10904: {
10905: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
10906:
10907: while (my $configline=<$config>) {
10908: chomp($configline);
10909: if ($configline) {
10910: my ($short,@plain)=split(/:/,$configline);
10911: %{$prp{$short}} = ();
10912: if (@plain > 0) {
10913: $prp{$short}{'std'} = $plain[0];
10914: for (my $i=1; $i<@plain; $i++) {
10915: $prp{$short}{'alt'.$i} = $plain[$i];
10916: }
10917: }
10918: }
10919: }
10920: close($config);
10921: }
10922:
10923: # ---------------------------------------------------------- Read package table
10924: {
10925: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
10926:
10927: while (my $configline=<$config>) {
10928: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
10929: chomp($configline);
10930: my ($short,$plain)=split(/:/,$configline);
10931: my ($pack,$name)=split(/\&/,$short);
10932: if ($plain ne '') {
10933: $packagetab{$pack.'&'.$name.'&name'}=$name;
10934: $packagetab{$short}=$plain;
10935: }
10936: }
10937: close($config);
10938: }
10939:
10940: # ---------------------------------------------------------- Read loncaparev table
10941: {
10942: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10943: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10944: while (my $configline=<$config>) {
10945: chomp($configline);
10946: my ($hostid,$loncaparev)=split(/:/,$configline);
10947: $loncaparevs{$hostid}=$loncaparev;
10948: }
10949: close($config);
10950: }
10951: }
10952: }
10953:
10954: # ---------------------------------------------------------- Read serverhostID table
10955: {
10956: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10957: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10958: while (my $configline=<$config>) {
10959: chomp($configline);
10960: my ($name,$id)=split(/:/,$configline);
10961: $serverhomeIDs{$name}=$id;
10962: }
10963: close($config);
10964: }
10965: }
10966: }
10967:
10968: {
10969: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10970: if (-e $file) {
10971: my $parser = HTML::LCParser->new($file);
10972: while (my $token = $parser->get_token()) {
10973: if ($token->[0] eq 'S') {
10974: my $item = $token->[1];
10975: my $name = $token->[2]{'name'};
10976: my $value = $token->[2]{'value'};
10977: if ($item ne '' && $name ne '' && $value ne '') {
10978: my $release = $parser->get_text();
10979: $release =~ s/(^\s*|\s*$ )//gx;
10980: $needsrelease{$item.':'.$name.':'.$value} = $release;
10981: }
10982: }
10983: }
10984: }
10985: }
10986:
10987: # ------------- set up temporary directory
10988: {
10989: $tmpdir = LONCAPA::tempdir();
10990:
10991: }
10992:
10993: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10994: 'compress_threshold'=> 20_000,
10995: });
10996:
10997: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
10998: $dumpcount=0;
10999: $locknum=0;
11000:
11001: &logtouch();
11002: &logthis('<font color="yellow">INFO: Read configuration</font>');
11003: $readit=1;
11004: {
11005: use integer;
11006: my $test=(2**32)+1;
11007: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11008: &logthis(" Detected 64bit platform ($_64bit)");
11009: }
11010: }
11011: }
11012:
11013: 1;
11014: __END__
11015:
11016: =pod
11017:
11018: =head1 NAME
11019:
11020: Apache::lonnet - Subroutines to ask questions about things in the network.
11021:
11022: =head1 SYNOPSIS
11023:
11024: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11025:
11026: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11027:
11028: Common parameters:
11029:
11030: =over 4
11031:
11032: =item *
11033:
11034: $uname : an internal username (if $cname expecting a course Id specifically)
11035:
11036: =item *
11037:
11038: $udom : a domain (if $cdom expecting a course's domain specifically)
11039:
11040: =item *
11041:
11042: $symb : a resource instance identifier
11043:
11044: =item *
11045:
11046: $namespace : the name of a .db file that contains the data needed or
11047: being set.
11048:
11049: =back
11050:
11051: =head1 OVERVIEW
11052:
11053: lonnet provides subroutines which interact with the
11054: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11055: about classes, users, and resources.
11056:
11057: For many of these objects you can also use this to store data about
11058: them or modify them in various ways.
11059:
11060: =head2 Symbs
11061:
11062: To identify a specific instance of a resource, LON-CAPA uses symbols
11063: or "symbs"X<symb>. These identifiers are built from the URL of the
11064: map, the resource number of the resource in the map, and the URL of
11065: the resource itself. The latter is somewhat redundant, but might help
11066: if maps change.
11067:
11068: An example is
11069:
11070: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11071:
11072: The respective map entry is
11073:
11074: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11075: title="Problem 2">
11076: </resource>
11077:
11078: Symbs are used by the random number generator, as well as to store and
11079: restore data specific to a certain instance of for example a problem.
11080:
11081: =head2 Storing And Retrieving Data
11082:
11083: X<store()>X<cstore()>X<restore()>Three of the most important functions
11084: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11085: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11086: is is the non-critical message twin of cstore. These functions are for
11087: handlers to store a perl hash to a user's permanent data space in an
11088: easy manner, and to retrieve it again on another call. It is expected
11089: that a handler would use this once at the beginning to retrieve data,
11090: and then again once at the end to send only the new data back.
11091:
11092: The data is stored in the user's data directory on the user's
11093: homeserver under the ID of the course.
11094:
11095: The hash that is returned by restore will have all of the previous
11096: value for all of the elements of the hash.
11097:
11098: Example:
11099:
11100: #creating a hash
11101: my %hash;
11102: $hash{'foo'}='bar';
11103:
11104: #storing it
11105: &Apache::lonnet::cstore(\%hash);
11106:
11107: #changing a value
11108: $hash{'foo'}='notbar';
11109:
11110: #adding a new value
11111: $hash{'bar'}='foo';
11112: &Apache::lonnet::cstore(\%hash);
11113:
11114: #retrieving the hash
11115: my %history=&Apache::lonnet::restore();
11116:
11117: #print the hash
11118: foreach my $key (sort(keys(%history))) {
11119: print("\%history{$key} = $history{$key}");
11120: }
11121:
11122: Will print out:
11123:
11124: %history{1:foo} = bar
11125: %history{1:keys} = foo:timestamp
11126: %history{1:timestamp} = 990455579
11127: %history{2:bar} = foo
11128: %history{2:foo} = notbar
11129: %history{2:keys} = foo:bar:timestamp
11130: %history{2:timestamp} = 990455580
11131: %history{bar} = foo
11132: %history{foo} = notbar
11133: %history{timestamp} = 990455580
11134: %history{version} = 2
11135:
11136: Note that the special hash entries C<keys>, C<version> and
11137: C<timestamp> were added to the hash. C<version> will be equal to the
11138: total number of versions of the data that have been stored. The
11139: C<timestamp> attribute will be the UNIX time the hash was
11140: stored. C<keys> is available in every historical section to list which
11141: keys were added or changed at a specific historical revision of a
11142: hash.
11143:
11144: B<Warning>: do not store the hash that restore returns directly. This
11145: will cause a mess since it will restore the historical keys as if the
11146: were new keys. I.E. 1:foo will become 1:1:foo etc.
11147:
11148: Calling convention:
11149:
11150: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11151: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11152:
11153: For more detailed information, see lonnet specific documentation.
11154:
11155: =head1 RETURN MESSAGES
11156:
11157: =over 4
11158:
11159: =item * B<con_lost>: unable to contact remote host
11160:
11161: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11162: when the connection is brought back up
11163:
11164: =item * B<con_failed>: unable to contact remote host and unable to save message
11165: for later delivery
11166:
11167: =item * B<error:>: an error a occurred, a description of the error follows the :
11168:
11169: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11170: that was requested
11171:
11172: =back
11173:
11174: =head1 PUBLIC SUBROUTINES
11175:
11176: =head2 Session Environment Functions
11177:
11178: =over 4
11179:
11180: =item *
11181: X<appenv()>
11182: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11183: the user envirnoment file, and will be restored for each access this
11184: user makes during this session, also modifies the %env for the current
11185: process. Optional rolesarrayref - if defined contains a reference to an array
11186: of roles which are exempt from the restriction on modifying user.role entries
11187: in the user's environment.db and in %env.
11188:
11189: =item *
11190: X<delenv()>
11191: B<delenv($delthis,$regexp)>: removes all items from the session
11192: environment file that begin with $delthis. If the
11193: optional second arg - $regexp - is true, $delthis is treated as a
11194: regular expression, otherwise \Q$delthis\E is used.
11195: The values are also deleted from the current processes %env.
11196:
11197: =item * get_env_multiple($name)
11198:
11199: gets $name from the %env hash, it seemlessly handles the cases where multiple
11200: values may be defined and end up as an array ref.
11201:
11202: returns an array of values
11203:
11204: =back
11205:
11206: =head2 User Information
11207:
11208: =over 4
11209:
11210: =item *
11211: X<queryauthenticate()>
11212: B<queryauthenticate($uname,$udom)>: try to determine user's current
11213: authentication scheme
11214:
11215: =item *
11216: X<authenticate()>
11217: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11218: authenticate user from domain's lib servers (first use the current
11219: one). C<$upass> should be the users password.
11220: $checkdefauth is optional (value is 1 if a check should be made to
11221: authenticate user using default authentication method, and allow
11222: account creation if username does not have account in the domain).
11223: $clientcancheckhost is optional (value is 1 if checking whether the
11224: server can host will occur on the client side in lonauth.pm).
11225:
11226: =item *
11227: X<homeserver()>
11228: B<homeserver($uname,$udom)>: find the server which has
11229: the user's directory and files (there must be only one), this caches
11230: the answer, and also caches if there is a borken connection.
11231:
11232: =item *
11233: X<idget()>
11234: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11235: (IDs are a unique resource in a domain, there must be only 1 ID per
11236: username, and only 1 username per ID in a specific domain) (returns
11237: hash: id=>name,id=>name)
11238:
11239: =item *
11240: X<idrget()>
11241: B<idrget($udom,@unames)>: find the IDs behind a list of
11242: usernames (returns hash: name=>id,name=>id)
11243:
11244: =item *
11245: X<idput()>
11246: B<idput($udom,%ids)>: store away a list of names and associated IDs
11247:
11248: =item *
11249: X<rolesinit()>
11250: B<rolesinit($udom,$username,$authhost)>: get user privileges
11251:
11252: =item *
11253: X<getsection()>
11254: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11255: course $cname, return section name/number or '' for "not in course"
11256: and '-1' for "no section"
11257:
11258: =item *
11259: X<userenvironment()>
11260: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11261: passed in @what from the requested user's environment, returns a hash
11262:
11263: =item *
11264: X<userlog_query()>
11265: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11266: activity.log file. %filters defines filters applied when parsing the
11267: log file. These can be start or end timestamps, or the type of action
11268: - log to look for Login or Logout events, check for Checkin or
11269: Checkout, role for role selection. The response is in the form
11270: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11271: escaped strings of the action recorded in the activity.log file.
11272:
11273: =back
11274:
11275: =head2 User Roles
11276:
11277: =over 4
11278:
11279: =item *
11280:
11281: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11282: F: full access
11283: U,I,K: authentication modes (cxx only)
11284: '': forbidden
11285: 1: user needs to choose course
11286: 2: browse allowed
11287: A: passphrase authentication needed
11288:
11289: =item *
11290:
11291: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11292: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11293: and course level
11294:
11295: =item *
11296:
11297: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11298: (rolesplain.tab); plain text explanation of a user role term.
11299: $type is Course (default) or Community.
11300: If $forcedefault evaluates to true, text returned will be default
11301: text for $type. Otherwise, if this is a course, the text returned
11302: will be a custom name for the role (if defined in the course's
11303: environment). If no custom name is defined the default is returned.
11304:
11305: =item *
11306:
11307: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11308: All arguments are optional. Returns a hash of a roles, either for
11309: co-author/assistant author roles for a user's Construction Space
11310: (default), or if $context is 'userroles', roles for the user himself,
11311: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11312: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11313: For each key, value is set to colon-separated start and end times for
11314: the role. If no username and domain are specified, will default to
11315: current user/domain. Types, roles, and roledoms are references to arrays
11316: of role statuses (active, future or previous), roles
11317: (e.g., cc,in, st etc.) and domains of the roles which can be used
11318: to restrict the list of roles reported. If no array ref is
11319: provided for types, will default to return only active roles.
11320:
11321: =back
11322:
11323: =head2 User Modification
11324:
11325: =over 4
11326:
11327: =item *
11328:
11329: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11330: user for the level given by URL. Optional start and end dates (leave empty
11331: string or zero for "no date")
11332:
11333: =item *
11334:
11335: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11336: change a users, password, possible return values are: ok,
11337: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11338: refused
11339:
11340: =item *
11341:
11342: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11343:
11344: =item *
11345:
11346: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11347: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11348:
11349: will update user information (firstname,middlename,lastname,generation,
11350: permanentemail), and if forceid is true, student/employee ID also.
11351: A user's institutional affiliation(s) can also be updated.
11352: User information fields will not be overwritten with empty entries
11353: unless the field is included in the $candelete array reference.
11354: This array is included when a single user is modified via "Manage Users",
11355: or when Autoupdate.pl is run by cron in a domain.
11356:
11357: =item *
11358:
11359: modifystudent
11360:
11361: modify a student's enrollment and identification information.
11362: The course id is resolved based on the current users environment.
11363: This means the envoking user must be a course coordinator or otherwise
11364: associated with a course.
11365:
11366: This call is essentially a wrapper for lonnet::modifyuser and
11367: lonnet::modify_student_enrollment
11368:
11369: Inputs:
11370:
11371: =over 4
11372:
11373: =item B<$udom> Student's loncapa domain
11374:
11375: =item B<$uname> Student's loncapa login name
11376:
11377: =item B<$uid> Student/Employee ID
11378:
11379: =item B<$umode> Student's authentication mode
11380:
11381: =item B<$upass> Student's password
11382:
11383: =item B<$first> Student's first name
11384:
11385: =item B<$middle> Student's middle name
11386:
11387: =item B<$last> Student's last name
11388:
11389: =item B<$gene> Student's generation
11390:
11391: =item B<$usec> Student's section in course
11392:
11393: =item B<$end> Unix time of the roles expiration
11394:
11395: =item B<$start> Unix time of the roles start date
11396:
11397: =item B<$forceid> If defined, allow $uid to be changed
11398:
11399: =item B<$desiredhome> server to use as home server for student
11400:
11401: =item B<$email> Student's permanent e-mail address
11402:
11403: =item B<$type> Type of enrollment (auto or manual)
11404:
11405: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11406:
11407: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11408:
11409: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11410:
11411: =item B<$context> role change context (shown in User Management Logs display in a course)
11412:
11413: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11414:
11415: =back
11416:
11417: =item *
11418:
11419: modify_student_enrollment
11420:
11421: Change a students enrollment status in a class. The environment variable
11422: 'role.request.course' must be defined for this function to proceed.
11423:
11424: Inputs:
11425:
11426: =over 4
11427:
11428: =item $udom, students domain
11429:
11430: =item $uname, students name
11431:
11432: =item $uid, students user id
11433:
11434: =item $first, students first name
11435:
11436: =item $middle
11437:
11438: =item $last
11439:
11440: =item $gene
11441:
11442: =item $usec
11443:
11444: =item $end
11445:
11446: =item $start
11447:
11448: =item $type
11449:
11450: =item $locktype
11451:
11452: =item $cid
11453:
11454: =item $selfenroll
11455:
11456: =item $context
11457:
11458: =back
11459:
11460:
11461: =item *
11462:
11463: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11464: custom role; give a custom role to a user for the level given by URL. Specify
11465: name and domain of role author, and role name
11466:
11467: =item *
11468:
11469: revokerole($udom,$uname,$url,$role) : revoke a role for url
11470:
11471: =item *
11472:
11473: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11474:
11475: =back
11476:
11477: =head2 Course Infomation
11478:
11479: =over 4
11480:
11481: =item *
11482:
11483: coursedescription($courseid,$options) : returns a hash of information about the
11484: specified course id, including all environment settings for the
11485: course, the description of the course will be in the hash under the
11486: key 'description'
11487:
11488: $options is an optional parameter that if supplied is a hash reference that controls
11489: what how this function works. It has the following key/values:
11490:
11491: =over 4
11492:
11493: =item freshen_cache
11494:
11495: If defined, and the environment cache for the course is valid, it is
11496: returned in the returned hash.
11497:
11498: =item one_time
11499:
11500: If defined, the last cache time is set to _now_
11501:
11502: =item user
11503:
11504: If defined, the supplied username is used instead of the current user.
11505:
11506:
11507: =back
11508:
11509: =item *
11510:
11511: resdata($name,$domain,$type,@which) : request for current parameter
11512: setting for a specific $type, where $type is either 'course' or 'user',
11513: @what should be a list of parameters to ask about. This routine caches
11514: answers for 5 minutes.
11515:
11516: =item *
11517:
11518: get_courseresdata($courseid, $domain) : dump the entire course resource
11519: data base, returning a hash that is keyed by the resource name and has
11520: values that are the resource value. I believe that the timestamps and
11521: versions are also returned.
11522:
11523:
11524: =back
11525:
11526: =head2 Course Modification
11527:
11528: =over 4
11529:
11530: =item *
11531:
11532: writecoursepref($courseid,%prefs) : write preferences (environment
11533: database) for a course
11534:
11535: =item *
11536:
11537: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11538:
11539: =item *
11540:
11541: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11542:
11543: =back
11544:
11545: =head2 Resource Subroutines
11546:
11547: =over 4
11548:
11549: =item *
11550:
11551: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
11552:
11553: =item *
11554:
11555: repcopy($filename) : subscribes to the requested file, and attempts to
11556: replicate from the owning library server, Might return
11557: 'unavailable', 'not_found', 'forbidden', 'ok', or
11558: 'bad_request', also attempts to grab the metadata for the
11559: resource. Expects the local filesystem pathname
11560: (/home/httpd/html/res/....)
11561:
11562: =back
11563:
11564: =head2 Resource Information
11565:
11566: =over 4
11567:
11568: =item *
11569:
11570: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11571: a vairety of different possible values, $varname should be a request
11572: string, and the other parameters can be used to specify who and what
11573: one is asking about.
11574:
11575: Possible values for $varname are environment.lastname (or other item
11576: from the envirnment hash), user.name (or someother aspect about the
11577: user), resource.0.maxtries (or some other part and parameter of a
11578: resource)
11579:
11580: =item *
11581:
11582: directcondval($number) : get current value of a condition; reads from a state
11583: string
11584:
11585: =item *
11586:
11587: condval($condidx) : value of condition index based on state
11588:
11589: =item *
11590:
11591: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11592: resource's metadata, $what should be either a specific key, or either
11593: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11594: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11595:
11596: this function automatically caches all requests
11597:
11598: =item *
11599:
11600: metadata_query($query,$custom,$customshow) : make a metadata query against the
11601: network of library servers; returns file handle of where SQL and regex results
11602: will be stored for query
11603:
11604: =item *
11605:
11606: symbread($filename) : return symbolic list entry (filename argument optional);
11607: returns the data handle
11608:
11609: =item *
11610:
11611: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
11612: a possible symb for the URL in $thisfn, and if is an encryypted
11613: resource that the user accessed using /enc/ returns a 1 on success, 0
11614: on failure, user must be in a course, as it assumes the existance of
11615: the course initial hash, and uses $env('request.course.id'}
11616:
11617:
11618: =item *
11619:
11620: symbclean($symb) : removes versions numbers from a symb, returns the
11621: cleaned symb
11622:
11623: =item *
11624:
11625: is_on_map($uri) : checks if the $uri is somewhere on the current
11626: course map, user must be in a course for it to work.
11627:
11628: =item *
11629:
11630: numval($salt) : return random seed value (addend for rndseed)
11631:
11632: =item *
11633:
11634: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11635: a random seed, all arguments are optional, if they aren't sent it uses the
11636: environment to derive them. Note: if symb isn't sent and it can't get one
11637: from &symbread it will use the current time as its return value
11638:
11639: =item *
11640:
11641: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11642: unfakeable, receipt
11643:
11644: =item *
11645:
11646: receipt() : API to ireceipt working off of env values; given out to users
11647:
11648: =item *
11649:
11650: countacc($url) : count the number of accesses to a given URL
11651:
11652: =item *
11653:
11654: 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
11655:
11656: =item *
11657:
11658: 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)
11659:
11660: =item *
11661:
11662: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
11663:
11664: =item *
11665:
11666: devalidate($symb) : devalidate temporary spreadsheet calculations,
11667: forcing spreadsheet to reevaluate the resource scores next time.
11668:
11669: =back
11670:
11671: =head2 Storing/Retreiving Data
11672:
11673: =over 4
11674:
11675: =item *
11676:
11677: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11678: for this url; hashref needs to be given and should be a \%hashname; the
11679: remaining args aren't required and if they aren't passed or are '' they will
11680: be derived from the env
11681:
11682: =item *
11683:
11684: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11685: uses critical subroutine
11686:
11687: =item *
11688:
11689: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11690: all args are optional
11691:
11692: =item *
11693:
11694: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11695: dumps the complete (or key matching regexp) namespace into a hash
11696: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11697: normally &store()ed into
11698:
11699: $range should be either an integer '100' (give me the first 100
11700: matching records)
11701: or be two integers sperated by a - with no spaces
11702: '30-50' (give me the 30th through the 50th matching
11703: records)
11704:
11705:
11706: =item *
11707:
11708: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11709: replaces a &store() version of data with a replacement set of data
11710: for a particular resource in a namespace passed in the $storehash hash
11711: reference
11712:
11713: =item *
11714:
11715: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11716: works very similar to store/cstore, but all data is stored in a
11717: temporary location and can be reset using tmpreset, $storehash should
11718: be a hash reference, returns nothing on success
11719:
11720: =item *
11721:
11722: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11723: similar to restore, but all data is stored in a temporary location and
11724: can be reset using tmpreset. Returns a hash of values on success,
11725: error string otherwise.
11726:
11727: =item *
11728:
11729: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11730: deltes all keys for $symb form the temporary storage hash.
11731:
11732: =item *
11733:
11734: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11735: reference filled in from namesp ($udom and $uname are optional)
11736:
11737: =item *
11738:
11739: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11740: namesp ($udom and $uname are optional)
11741:
11742: =item *
11743:
11744: dump($namespace,$udom,$uname,$regexp,$range) :
11745: dumps the complete (or key matching regexp) namespace into a hash
11746: ($udom, $uname, $regexp, $range are optional)
11747:
11748: $range should be either an integer '100' (give me the first 100
11749: matching records)
11750: or be two integers sperated by a - with no spaces
11751: '30-50' (give me the 30th through the 50th matching
11752: records)
11753: =item *
11754:
11755: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11756: $store can be a scalar, an array reference, or if the amount to be
11757: incremented is > 1, a hash reference.
11758:
11759: ($udom and $uname are optional)
11760:
11761: =item *
11762:
11763: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11764: ($udom and $uname are optional)
11765:
11766: =item *
11767:
11768: cput($namespace,$storehash,$udom,$uname) : critical put
11769: ($udom and $uname are optional)
11770:
11771: =item *
11772:
11773: newput($namespace,$storehash,$udom,$uname) :
11774:
11775: Attempts to store the items in the $storehash, but only if they don't
11776: currently exist, if this succeeds you can be certain that you have
11777: successfully created a new key value pair in the $namespace db.
11778:
11779:
11780: Args:
11781: $namespace: name of database to store values to
11782: $storehash: hashref to store to the db
11783: $udom: (optional) domain of user containing the db
11784: $uname: (optional) name of user caontaining the db
11785:
11786: Returns:
11787: 'ok' -> succeeded in storing all keys of $storehash
11788: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11789: least <key> already existed in the db (other
11790: requested keys may also already exist)
11791: 'error: <msg>' -> unable to tie the DB or other error occurred
11792: 'con_lost' -> unable to contact request server
11793: 'refused' -> action was not allowed by remote machine
11794:
11795:
11796: =item *
11797:
11798: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11799: reference filled in from namesp (encrypts the return communication)
11800: ($udom and $uname are optional)
11801:
11802: =item *
11803:
11804: log($udom,$name,$home,$message) : write to permanent log for user; use
11805: critical subroutine
11806:
11807: =item *
11808:
11809: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11810: array reference filled in from namespace found in domain level on either
11811: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
11812:
11813: =item *
11814:
11815: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11816: domain level either on specified domain server ($uhome) or primary domain
11817: server ($udom and $uhome are optional)
11818:
11819: =item *
11820:
11821: get_domain_defaults($target_domain) : returns hash with defaults for
11822: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11823: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11824: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11825: Values are retrieved from cache (if current), or from domain's configuration.db
11826: (if available), or lastly from values in lonTabs/dns_domain,tab,
11827: or lonTabs/domain.tab.
11828:
11829: %domdefaults = &get_auth_defaults($target_domain);
11830:
11831: =back
11832:
11833: =head2 Network Status Functions
11834:
11835: =over 4
11836:
11837: =item *
11838:
11839: dirlist($uri) : return directory list based on URI
11840:
11841: =item *
11842:
11843: spareserver() : find server with least workload from spare.tab
11844:
11845:
11846: =item *
11847:
11848: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11849: if there is no corresponding loncapa host.
11850:
11851: =back
11852:
11853:
11854: =head2 Apache Request
11855:
11856: =over 4
11857:
11858: =item *
11859:
11860: ssi($url,%hash) : server side include, does a complete request cycle on url to
11861: localhost, posts hash
11862:
11863: =back
11864:
11865: =head2 Data to String to Data
11866:
11867: =over 4
11868:
11869: =item *
11870:
11871: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11872: and '&' separators, supports elements that are arrayrefs and hashrefs
11873:
11874: =item *
11875:
11876: hashref2str($hashref) : convert a hashref into a string complete with
11877: escaping and '=' and '&' separators, supports elements that are
11878: arrayrefs and hashrefs
11879:
11880: =item *
11881:
11882: arrayref2str($arrayref) : convert an arrayref into a string complete
11883: with escaping and '&' separators, supports elements that are arrayrefs
11884: and hashrefs
11885:
11886: =item *
11887:
11888: str2hash($string) : convert string to hash using unescaping and
11889: splitting on '=' and '&', supports elements that are arrayrefs and
11890: hashrefs
11891:
11892: =item *
11893:
11894: str2array($string) : convert string to hash using unescaping and
11895: splitting on '&', supports elements that are arrayrefs and hashrefs
11896:
11897: =back
11898:
11899: =head2 Logging Routines
11900:
11901:
11902: These routines allow one to make log messages in the lonnet.log and
11903: lonnet.perm logfiles.
11904:
11905: =over 4
11906:
11907: =item *
11908:
11909: logtouch() : make sure the logfile, lonnet.log, exists
11910:
11911: =item *
11912:
11913: logthis() : append message to the normal lonnet.log file, it gets
11914: preiodically rolled over and deleted.
11915:
11916: =item *
11917:
11918: logperm() : append a permanent message to lonnet.perm.log, this log
11919: file never gets deleted by any automated portion of the system, only
11920: messages of critical importance should go in here.
11921:
11922:
11923: =back
11924:
11925: =head2 General File Helper Routines
11926:
11927: =over 4
11928:
11929: =item *
11930:
11931: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11932: (a) files in /uploaded
11933: (i) If a local copy of the file exists -
11934: compares modification date of local copy with last-modified date for
11935: definitive version stored on home server for course. If local copy is
11936: stale, requests a new version from the home server and stores it.
11937: If the original has been removed from the home server, then local copy
11938: is unlinked.
11939: (ii) If local copy does not exist -
11940: requests the file from the home server and stores it.
11941:
11942: If $caller is 'uploadrep':
11943: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11944: for request for files originally uploaded via DOCS.
11945: - returns 'ok' if fresh local copy now available, -1 otherwise.
11946:
11947: Otherwise:
11948: This indicates a call from the content generation phase of the request.
11949: - returns the entire contents of the file or -1.
11950:
11951: (b) files in /res
11952: - returns the entire contents of a file or -1;
11953: it properly subscribes to and replicates the file if neccessary.
11954:
11955:
11956: =item *
11957:
11958: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11959: reference
11960:
11961: returns either a stat() list of data about the file or an empty list
11962: if the file doesn't exist or couldn't find out about it (connection
11963: problems or user unknown)
11964:
11965: =item *
11966:
11967: filelocation($dir,$file) : returns file system location of a file
11968: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11969: directory that relative $file lookups are to looked in ($dir of /a/dir
11970: and a file of ../bob will become /a/bob)
11971:
11972: =item *
11973:
11974: hreflocation($dir,$file) : returns file system location or a URL; same as
11975: filelocation except for hrefs
11976:
11977: =item *
11978:
11979: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11980:
11981: =back
11982:
11983: =head2 Usererfile file routines (/uploaded*)
11984:
11985: =over 4
11986:
11987: =item *
11988:
11989: userfileupload(): main rotine for putting a file in a user or course's
11990: filespace, arguments are,
11991:
11992: formname - required - this is the name of the element in $env where the
11993: filename, and the contents of the file to create/modifed exist
11994: the filename is in $env{'form.'.$formname.'.filename'} and the
11995: contents of the file is located in $env{'form.'.$formname}
11996: context - if coursedoc, store the file in the course of the active role
11997: of the current user;
11998: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11999: if 'canceloverwrite': delete file in tmp/overwrites directory
12000: subdir - required - subdirectory to put the file in under ../userfiles/
12001: if undefined, it will be placed in "unknown"
12002:
12003: (This routine calls clean_filename() to remove any dangerous
12004: characters from the filename, and then calls finuserfileupload() to
12005: complete the transaction)
12006:
12007: returns either the url of the uploaded file (/uploaded/....) if successful
12008: and /adm/notfound.html if unsuccessful
12009:
12010: =item *
12011:
12012: clean_filename(): routine for cleaing a filename up for storage in
12013: userfile space, argument is:
12014:
12015: filename - proposed filename
12016:
12017: returns: the new clean filename
12018:
12019: =item *
12020:
12021: finishuserfileupload(): routine that creates and sends the file to
12022: userspace, probably shouldn't be called directly
12023:
12024: docuname: username or courseid of destination for the file
12025: docudom: domain of user/course of destination for the file
12026: formname: same as for userfileupload()
12027: fname: filename (including subdirectories) for the file
12028: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12029: allfiles: reference to hash used to store objects found by parser
12030: codebase: reference to hash used for codebases of java objects found by parser
12031: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12032: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12033: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12034: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12035: context: if 'overwrite', will move the uploaded file from its temporary location to
12036: userfiles to facilitate overwriting a previously uploaded file with same name.
12037: mimetype: reference to scalar to accommodate mime type determined
12038: from File::MMagic if $parser = parse.
12039:
12040: returns either the url of the uploaded file (/uploaded/....) if successful
12041: and /adm/notfound.html if unsuccessful (or an error message if context
12042: was 'overwrite').
12043:
12044:
12045: =item *
12046:
12047: renameuserfile(): renames an existing userfile to a new name
12048:
12049: Args:
12050: docuname: username or courseid of destination for the file
12051: docudom: domain of user/course of destination for the file
12052: old: current file name (including any subdirs under userfiles)
12053: new: desired file name (including any subdirs under userfiles)
12054:
12055: =item *
12056:
12057: mkdiruserfile(): creates a directory is a userfiles dir
12058:
12059: Args:
12060: docuname: username or courseid of destination for the file
12061: docudom: domain of user/course of destination for the file
12062: dir: dir to create (including any subdirs under userfiles)
12063:
12064: =item *
12065:
12066: removeuserfile(): removes a file that exists in userfiles
12067:
12068: Args:
12069: docuname: username or courseid of destination for the file
12070: docudom: domain of user/course of destination for the file
12071: fname: filname to delete (including any subdirs under userfiles)
12072:
12073: =item *
12074:
12075: removeuploadedurl(): convience function for removeuserfile()
12076:
12077: Args:
12078: url: a full /uploaded/... url to delete
12079:
12080: =item *
12081:
12082: get_portfile_permissions():
12083: Args:
12084: domain: domain of user or course contain the portfolio files
12085: user: name of user or num of course contain the portfolio files
12086: Returns:
12087: hashref of a dump of the proper file_permissions.db
12088:
12089:
12090: =item *
12091:
12092: get_access_controls():
12093:
12094: Args:
12095: current_permissions: the hash ref returned from get_portfile_permissions()
12096: group: (optional) the group you want the files associated with
12097: file: (optional) the file you want access info on
12098:
12099: Returns:
12100: a hash (keys are file names) of hashes containing
12101: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12102: values are XML containing access control settings (see below)
12103:
12104: Internal notes:
12105:
12106: access controls are stored in file_permissions.db as key=value pairs.
12107: key -> path to file/file_name\0uniqueID:scope_end_start
12108: where scope -> public,guest,course,group,domains or users.
12109: end -> UNIX time for end of access (0 -> no end date)
12110: start -> UNIX time for start of access
12111:
12112: value -> XML description of access control
12113: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12114: <start></start>
12115: <end></end>
12116:
12117: <password></password> for scope type = guest
12118:
12119: <domain></domain> for scope type = course or group
12120: <number></number>
12121: <roles id="">
12122: <role></role>
12123: <access></access>
12124: <section></section>
12125: <group></group>
12126: </roles>
12127:
12128: <dom></dom> for scope type = domains
12129:
12130: <users> for scope type = users
12131: <user>
12132: <uname></uname>
12133: <udom></udom>
12134: </user>
12135: </users>
12136: </scope>
12137:
12138: Access data is also aggregated for each file in an additional key=value pair:
12139: key -> path to file/file_name\0accesscontrol
12140: value -> reference to hash
12141: hash contains key = value pairs
12142: where key = uniqueID:scope_end_start
12143: value = UNIX time record was last updated
12144:
12145: Used to improve speed of look-ups of access controls for each file.
12146:
12147: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12148:
12149: modify_access_controls():
12150:
12151: Modifies access controls for a portfolio file
12152: Args
12153: 1. file name
12154: 2. reference to hash of required changes,
12155: 3. domain
12156: 4. username
12157: where domain,username are the domain of the portfolio owner
12158: (either a user or a course)
12159:
12160: Returns:
12161: 1. result of additions or updates ('ok' or 'error', with error message).
12162: 2. result of deletions ('ok' or 'error', with error message).
12163: 3. reference to hash of any new or updated access controls.
12164: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12165: key = integer (inbound ID)
12166: value = uniqueID
12167:
12168: =back
12169:
12170: =head2 HTTP Helper Routines
12171:
12172: =over 4
12173:
12174: =item *
12175:
12176: escape() : unpack non-word characters into CGI-compatible hex codes
12177:
12178: =item *
12179:
12180: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12181:
12182: =back
12183:
12184: =head1 PRIVATE SUBROUTINES
12185:
12186: =head2 Underlying communication routines (Shouldn't call)
12187:
12188: =over 4
12189:
12190: =item *
12191:
12192: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12193:
12194: =item *
12195:
12196: reply() : uses subreply to send a message to remote machine, logs all failures
12197:
12198: =item *
12199:
12200: critical() : passes a critical message to another server; if cannot
12201: get through then place message in connection buffer directory and
12202: returns con_delayed, if incapable of saving message, returns
12203: con_failed
12204:
12205: =item *
12206:
12207: reconlonc() : tries to reconnect lonc client processes.
12208:
12209: =back
12210:
12211: =head2 Resource Access Logging
12212:
12213: =over 4
12214:
12215: =item *
12216:
12217: flushcourselogs() : flush (save) buffer logs and access logs
12218:
12219: =item *
12220:
12221: courselog($what) : save message for course in hash
12222:
12223: =item *
12224:
12225: courseacclog($what) : save message for course using &courselog(). Perform
12226: special processing for specific resource types (problems, exams, quizzes, etc).
12227:
12228: =item *
12229:
12230: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12231: as a PerlChildExitHandler
12232:
12233: =back
12234:
12235: =head2 Other
12236:
12237: =over 4
12238:
12239: =item *
12240:
12241: symblist($mapname,%newhash) : update symbolic storage links
12242:
12243: =back
12244:
12245: =cut
12246:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>