File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1277:
download - view:
text,
annotated -
select for diffs
Sat Mar 7 23:17:21 2015 UTC (9 years, 4 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Additional Course/Community defaults for JSME Molecule Editor and Math
Previewer (can be overridden in a course by CC), and for disabling submit
button after student submission, with/without timeout, setby course container
type (can be overriden for specific course by a DC).
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1277 2015/03/07 23:17:21 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:
79: use Encode;
80:
81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
88: %courseownerbuf, %coursetypebuf,$locknum);
89:
90: use IO::Socket;
91: use GDBM_File;
92: use HTML::LCParser;
93: use Fcntl qw(:flock);
94: use Storable qw(thaw nfreeze);
95: use Time::HiRes qw( gettimeofday tv_interval );
96: use Cache::Memcached;
97: use Digest::MD5;
98: use Math::Random;
99: use File::MMagic;
100: use LONCAPA qw(:DEFAULT :match);
101: use LONCAPA::Configuration;
102: use LONCAPA::lonmetadata;
103: use LONCAPA::Lond;
104:
105: use File::Copy;
106:
107: my $readit;
108: my $max_connection_retries = 10; # Or some such value.
109:
110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
115:
116: # ------------------------------------ Logging (parameters, docs, slots, roles)
117: {
118: my $logid;
119: sub write_log {
120: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if ($context eq 'course') {
122: if (($cnum eq '') || ($cdom eq '')) {
123: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
124: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
125: }
126: }
127: $logid ++;
128: my $now = time();
129: my $id=$now.'00000'.$$.'00000'.$logid;
130: my $logentry = {
131: $id => {
132: 'exe_uname' => $env{'user.name'},
133: 'exe_udom' => $env{'user.domain'},
134: 'exe_time' => $now,
135: 'exe_ip' => $ENV{'REMOTE_ADDR'},
136: 'delflag' => $delflag,
137: 'logentry' => $storehash,
138: 'uname' => $uname,
139: 'udom' => $udom,
140: }
141: };
142: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
143: }
144: }
145:
146: sub logtouch {
147: my $execdir=$perlvar{'lonDaemons'};
148: unless (-e "$execdir/logs/lonnet.log") {
149: open(my $fh,">>$execdir/logs/lonnet.log");
150: close $fh;
151: }
152: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
153: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
154: }
155:
156: sub logthis {
157: my $message=shift;
158: my $execdir=$perlvar{'lonDaemons'};
159: my $now=time;
160: my $local=localtime($now);
161: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
162: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
163: print $fh $logstring;
164: close($fh);
165: }
166: return 1;
167: }
168:
169: sub logperm {
170: my $message=shift;
171: my $execdir=$perlvar{'lonDaemons'};
172: my $now=time;
173: my $local=localtime($now);
174: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
175: print $fh "$now:$message:$local\n";
176: close($fh);
177: }
178: return 1;
179: }
180:
181: sub create_connection {
182: my ($hostname,$lonid) = @_;
183: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
184: Type => SOCK_STREAM,
185: Timeout => 10);
186: return 0 if (!$client);
187: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
188: my $result = <$client>;
189: chomp($result);
190: return 1 if ($result eq 'done');
191: return 0;
192: }
193:
194: sub get_server_timezone {
195: my ($cnum,$cdom) = @_;
196: my $home=&homeserver($cnum,$cdom);
197: if ($home ne 'no_host') {
198: my $cachetime = 24*3600;
199: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
200: if (defined($cached)) {
201: return $timezone;
202: } else {
203: my $timezone = &reply('servertimezone',$home);
204: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
205: }
206: }
207: }
208:
209: sub get_server_distarch {
210: my ($lonhost,$ignore_cache) = @_;
211: if (defined($lonhost)) {
212: if (!defined(&hostname($lonhost))) {
213: return;
214: }
215: my $cachetime = 12*3600;
216: if (!$ignore_cache) {
217: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
218: if (defined($cached)) {
219: return $distarch;
220: }
221: }
222: my $rep = &reply('serverdistarch',$lonhost);
223: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
224: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
225: $rep eq '') {
226: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
227: }
228: }
229: return;
230: }
231:
232: sub get_server_loncaparev {
233: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
234: if (defined($lonhost)) {
235: if (!defined(&hostname($lonhost))) {
236: undef($lonhost);
237: }
238: }
239: if (!defined($lonhost)) {
240: if (defined(&domain($dom,'primary'))) {
241: $lonhost=&domain($dom,'primary');
242: if ($lonhost eq 'no_host') {
243: undef($lonhost);
244: }
245: }
246: }
247: if (defined($lonhost)) {
248: my $cachetime = 12*3600;
249: if (!$ignore_cache) {
250: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
251: if (defined($cached)) {
252: return $loncaparev;
253: }
254: }
255: my ($answer,$loncaparev);
256: my @ids=¤t_machine_ids();
257: if (grep(/^\Q$lonhost\E$/,@ids)) {
258: $answer = $perlvar{'lonVersion'};
259: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
260: $loncaparev = $1;
261: }
262: } else {
263: $answer = &reply('serverloncaparev',$lonhost);
264: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
265: if ($caller eq 'loncron') {
266: my $ua=new LWP::UserAgent;
267: $ua->timeout(4);
268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
283: $loncaparev = $1;
284: }
285: }
286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
287: }
288: }
289:
290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
324: my ($response,$cached);
325: unless ($ignore_cache) {
326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
327: }
328: if (defined($cached)) {
329: $returnhash{$what} = $response;
330: } else {
331: $whatneeded{$what} = 1;
332: }
333: }
334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
344: my @pairs=split(/\&/,$rep);
345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
351: }
352: }
353: }
354: }
355: return ($result,\%returnhash);
356: }
357:
358: sub remote_devalidate_cache {
359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: my $response = &reply('devalidatecache:'.&escape($cachestr),$lonhost);
364: return $response;
365: }
366:
367: # -------------------------------------------------- Non-critical communication
368: sub subreply {
369: my ($cmd,$server)=@_;
370: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
371: #
372: # With loncnew process trimming, there's a timing hole between lonc server
373: # process exit and the master server picking up the listen on the AF_UNIX
374: # socket. In that time interval, a lock file will exist:
375:
376: my $lockfile=$peerfile.".lock";
377: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
378: sleep(1);
379: }
380: # At this point, either a loncnew parent is listening or an old lonc
381: # or loncnew child is listening so we can connect or everything's dead.
382: #
383: # We'll give the connection a few tries before abandoning it. If
384: # connection is not possible, we'll con_lost back to the client.
385: #
386: my $client;
387: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
388: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
389: Type => SOCK_STREAM,
390: Timeout => 10);
391: if ($client) {
392: last; # Connected!
393: } else {
394: &create_connection(&hostname($server),$server);
395: }
396: sleep(1); # Try again later if failed connection.
397: }
398: my $answer;
399: if ($client) {
400: print $client "sethost:$server:$cmd\n";
401: $answer=<$client>;
402: if (!$answer) { $answer="con_lost"; }
403: chomp($answer);
404: } else {
405: $answer = 'con_lost'; # Failed connection.
406: }
407: return $answer;
408: }
409:
410: sub reply {
411: my ($cmd,$server)=@_;
412: unless (defined(&hostname($server))) { return 'no_such_host'; }
413: my $answer=subreply($cmd,$server);
414: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
415: &logthis("<font color=\"blue\">WARNING:".
416: " $cmd to $server returned $answer</font>");
417: }
418: return $answer;
419: }
420:
421: # ----------------------------------------------------------- Send USR1 to lonc
422:
423: sub reconlonc {
424: my ($lonid) = @_;
425: my $hostname = &hostname($lonid);
426: if ($lonid) {
427: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
428: if ($hostname && -e $peerfile) {
429: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
430: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
431: Type => SOCK_STREAM,
432: Timeout => 10);
433: if ($client) {
434: print $client ("reset_retries\n");
435: my $answer=<$client>;
436: #reset just this one.
437: }
438: }
439: return;
440: }
441:
442: &logthis("Trying to reconnect lonc");
443: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
444: if (open(my $fh,"<$loncfile")) {
445: my $loncpid=<$fh>;
446: chomp($loncpid);
447: if (kill 0 => $loncpid) {
448: &logthis("lonc at pid $loncpid responding, sending USR1");
449: kill USR1 => $loncpid;
450: sleep 1;
451: } else {
452: &logthis(
453: "<font color=\"blue\">WARNING:".
454: " lonc at pid $loncpid not responding, giving up</font>");
455: }
456: } else {
457: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
458: }
459: }
460:
461: # ------------------------------------------------------ Critical communication
462:
463: sub critical {
464: my ($cmd,$server)=@_;
465: unless (&hostname($server)) {
466: &logthis("<font color=\"blue\">WARNING:".
467: " Critical message to unknown server ($server)</font>");
468: return 'no_such_host';
469: }
470: my $answer=reply($cmd,$server);
471: if ($answer eq 'con_lost') {
472: &reconlonc("$perlvar{'lonSockDir'}/$server");
473: my $answer=reply($cmd,$server);
474: if ($answer eq 'con_lost') {
475: my $now=time;
476: my $middlename=$cmd;
477: $middlename=substr($middlename,0,16);
478: $middlename=~s/\W//g;
479: my $dfilename=
480: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
481: $dumpcount++;
482: {
483: my $dfh;
484: if (open($dfh,">$dfilename")) {
485: print $dfh "$cmd\n";
486: close($dfh);
487: }
488: }
489: sleep 2;
490: my $wcmd='';
491: {
492: my $dfh;
493: if (open($dfh,"<$dfilename")) {
494: $wcmd=<$dfh>;
495: close($dfh);
496: }
497: }
498: chomp($wcmd);
499: if ($wcmd eq $cmd) {
500: &logthis("<font color=\"blue\">WARNING: ".
501: "Connection buffer $dfilename: $cmd</font>");
502: &logperm("D:$server:$cmd");
503: return 'con_delayed';
504: } else {
505: &logthis("<font color=\"red\">CRITICAL:"
506: ." Critical connection failed: $server $cmd</font>");
507: &logperm("F:$server:$cmd");
508: return 'con_failed';
509: }
510: }
511: }
512: return $answer;
513: }
514:
515: # ------------------------------------------- check if return value is an error
516:
517: sub error {
518: my ($result) = @_;
519: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
520: if ($2 == 2) { return undef; }
521: return $1;
522: }
523: return undef;
524: }
525:
526: sub convert_and_load_session_env {
527: my ($lonidsdir,$handle)=@_;
528: my @profile;
529: {
530: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
531: if (!$opened) {
532: return 0;
533: }
534: flock($idf,LOCK_SH);
535: @profile=<$idf>;
536: close($idf);
537: }
538: my %temp_env;
539: foreach my $line (@profile) {
540: if ($line !~ m/=/) {
541: return 0;
542: }
543: chomp($line);
544: my ($envname,$envvalue)=split(/=/,$line,2);
545: $temp_env{&unescape($envname)} = &unescape($envvalue);
546: }
547: unlink("$lonidsdir/$handle.id");
548: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
549: 0640)) {
550: %disk_env = %temp_env;
551: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
552: untie(%disk_env);
553: }
554: return 1;
555: }
556:
557: # ------------------------------------------- Transfer profile into environment
558: my $env_loaded;
559: sub transfer_profile_to_env {
560: my ($lonidsdir,$handle,$force_transfer) = @_;
561: if (!$force_transfer && $env_loaded) { return; }
562:
563: if (!defined($lonidsdir)) {
564: $lonidsdir = $perlvar{'lonIDsDir'};
565: }
566: if (!defined($handle)) {
567: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
568: }
569:
570: my $convert;
571: {
572: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
573: if (!$opened) {
574: return;
575: }
576: flock($idf,LOCK_SH);
577: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
578: &GDBM_READER(),0640)) {
579: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
580: untie(%disk_env);
581: } else {
582: $convert = 1;
583: }
584: }
585: if ($convert) {
586: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
587: &logthis("Failed to load session, or convert session.");
588: }
589: }
590:
591: my %remove;
592: while ( my $envname = each(%env) ) {
593: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
594: if ($time < time-300) {
595: $remove{$key}++;
596: }
597: }
598: }
599:
600: $env{'user.environment'} = "$lonidsdir/$handle.id";
601: $env_loaded=1;
602: foreach my $expired_key (keys(%remove)) {
603: &delenv($expired_key);
604: }
605: }
606:
607: # ---------------------------------------------------- Check for valid session
608: sub check_for_valid_session {
609: my ($r,$name,$userhashref) = @_;
610: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
611: if ($name eq '') {
612: $name = 'lonID';
613: }
614: my $lonid=$cookies{$name};
615: return undef if (!$lonid);
616:
617: my $handle=&LONCAPA::clean_handle($lonid->value);
618: my $lonidsdir;
619: if ($name eq 'lonDAV') {
620: $lonidsdir=$r->dir_config('lonDAVsessDir');
621: } else {
622: $lonidsdir=$r->dir_config('lonIDsDir');
623: }
624: return undef if (!-e "$lonidsdir/$handle.id");
625:
626: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
627: return undef if (!$opened);
628:
629: flock($idf,LOCK_SH);
630: my %disk_env;
631: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
632: &GDBM_READER(),0640)) {
633: return undef;
634: }
635:
636: if (!defined($disk_env{'user.name'})
637: || !defined($disk_env{'user.domain'})) {
638: return undef;
639: }
640:
641: if (ref($userhashref) eq 'HASH') {
642: $userhashref->{'name'} = $disk_env{'user.name'};
643: $userhashref->{'domain'} = $disk_env{'user.domain'};
644: }
645:
646: return $handle;
647: }
648:
649: sub timed_flock {
650: my ($file,$lock_type) = @_;
651: my $failed=0;
652: eval {
653: local $SIG{__DIE__}='DEFAULT';
654: local $SIG{ALRM}=sub {
655: $failed=1;
656: die("failed lock");
657: };
658: alarm(13);
659: flock($file,$lock_type);
660: alarm(0);
661: };
662: if ($failed) {
663: return undef;
664: } else {
665: return 1;
666: }
667: }
668:
669: # ---------------------------------------------------------- Append Environment
670:
671: sub appenv {
672: my ($newenv,$roles) = @_;
673: if (ref($newenv) eq 'HASH') {
674: foreach my $key (keys(%{$newenv})) {
675: my $refused = 0;
676: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
677: $refused = 1;
678: if (ref($roles) eq 'ARRAY') {
679: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
680: if (grep(/^\Q$role\E$/,@{$roles})) {
681: $refused = 0;
682: }
683: }
684: }
685: if ($refused) {
686: &logthis("<font color=\"blue\">WARNING: ".
687: "Attempt to modify environment ".$key." to ".$newenv->{$key}
688: .'</font>');
689: delete($newenv->{$key});
690: } else {
691: $env{$key}=$newenv->{$key};
692: }
693: }
694: my $opened = open(my $env_file,'+<',$env{'user.environment'});
695: if ($opened
696: && &timed_flock($env_file,LOCK_EX)
697: &&
698: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
699: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
700: while (my ($key,$value) = each(%{$newenv})) {
701: $disk_env{$key} = $value;
702: }
703: untie(%disk_env);
704: }
705: }
706: return 'ok';
707: }
708: # ----------------------------------------------------- Delete from Environment
709:
710: sub delenv {
711: my ($delthis,$regexp,$roles) = @_;
712: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
713: my $refused = 1;
714: if (ref($roles) eq 'ARRAY') {
715: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
716: if (grep(/^\Q$role\E$/,@{$roles})) {
717: $refused = 0;
718: }
719: }
720: if ($refused) {
721: &logthis("<font color=\"blue\">WARNING: ".
722: "Attempt to delete from environment ".$delthis);
723: return 'error';
724: }
725: }
726: my $opened = open(my $env_file,'+<',$env{'user.environment'});
727: if ($opened
728: && &timed_flock($env_file,LOCK_EX)
729: &&
730: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
731: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
732: foreach my $key (keys(%disk_env)) {
733: if ($regexp) {
734: if ($key=~/^$delthis/) {
735: delete($env{$key});
736: delete($disk_env{$key});
737: }
738: } else {
739: if ($key=~/^\Q$delthis\E/) {
740: delete($env{$key});
741: delete($disk_env{$key});
742: }
743: }
744: }
745: untie(%disk_env);
746: }
747: return 'ok';
748: }
749:
750: sub get_env_multiple {
751: my ($name) = @_;
752: my @values;
753: if (defined($env{$name})) {
754: # exists is it an array
755: if (ref($env{$name})) {
756: @values=@{ $env{$name} };
757: } else {
758: $values[0]=$env{$name};
759: }
760: }
761: return(@values);
762: }
763:
764: # ------------------------------------------------------------------- Locking
765:
766: sub set_lock {
767: my ($text)=@_;
768: $locknum++;
769: my $id=$$.'-'.$locknum;
770: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
771: 'session.lock.'.$id => $text});
772: return $id;
773: }
774:
775: sub get_locks {
776: my $num=0;
777: my %texts=();
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if ($lock=~/\w/) {
780: $num++;
781: $texts{$lock}=$env{'session.lock.'.$lock};
782: }
783: }
784: return ($num,%texts);
785: }
786:
787: sub remove_lock {
788: my ($id)=@_;
789: my $newlocks='';
790: foreach my $lock (split(/\,/,$env{'session.locks'})) {
791: if (($lock=~/\w/) && ($lock ne $id)) {
792: $newlocks.=','.$lock;
793: }
794: }
795: &appenv({'session.locks' => $newlocks});
796: &delenv('session.lock.'.$id);
797: }
798:
799: sub remove_all_locks {
800: my $activelocks=$env{'session.locks'};
801: foreach my $lock (split(/\,/,$env{'session.locks'})) {
802: if ($lock=~/\w/) {
803: &remove_lock($lock);
804: }
805: }
806: }
807:
808:
809: # ------------------------------------------ Find out current server userload
810: sub userload {
811: my $numusers=0;
812: {
813: opendir(LONIDS,$perlvar{'lonIDsDir'});
814: my $filename;
815: my $curtime=time;
816: while ($filename=readdir(LONIDS)) {
817: next if ($filename eq '.' || $filename eq '..');
818: next if ($filename =~ /publicuser_\d+\.id/);
819: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
820: if ($curtime-$mtime < 1800) { $numusers++; }
821: }
822: closedir(LONIDS);
823: }
824: my $userloadpercent=0;
825: my $maxuserload=$perlvar{'lonUserLoadLim'};
826: if ($maxuserload) {
827: $userloadpercent=100*$numusers/$maxuserload;
828: }
829: $userloadpercent=sprintf("%.2f",$userloadpercent);
830: return $userloadpercent;
831: }
832:
833: # ------------------------------ Find server with least workload from spare.tab
834:
835: sub spareserver {
836: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
837: my $spare_server;
838: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
839: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
840: : $userloadpercent;
841: my ($uint_dom,$remotesessions);
842: if (($udom ne '') && (&domain($udom) ne '')) {
843: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
844: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
845: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
846: $remotesessions = $udomdefaults{'remotesessions'};
847: }
848: my $spareshash = &this_host_spares($udom);
849: if (ref($spareshash) eq 'HASH') {
850: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
851: foreach my $try_server (@{ $spareshash->{'primary'} }) {
852: if ($uint_dom) {
853: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
854: $try_server));
855: }
856: ($spare_server, $lowest_load) =
857: &compare_server_load($try_server, $spare_server, $lowest_load);
858: }
859: }
860:
861: my $found_server = ($spare_server ne '' && $lowest_load < 100);
862:
863: if (!$found_server) {
864: if (ref($spareshash->{'default'}) eq 'ARRAY') {
865: foreach my $try_server (@{ $spareshash->{'default'} }) {
866: if ($uint_dom) {
867: next unless (&spare_can_host($udom,$uint_dom,
868: $remotesessions,$try_server));
869: }
870: ($spare_server, $lowest_load) =
871: &compare_server_load($try_server, $spare_server, $lowest_load);
872: }
873: }
874: }
875: }
876:
877: if (!$want_server_name) {
878: my $protocol = 'http';
879: if ($protocol{$spare_server} eq 'https') {
880: $protocol = $protocol{$spare_server};
881: }
882: if (defined($spare_server)) {
883: my $hostname = &hostname($spare_server);
884: if (defined($hostname)) {
885: $spare_server = $protocol.'://'.$hostname;
886: }
887: }
888: }
889: return $spare_server;
890: }
891:
892: sub compare_server_load {
893: my ($try_server, $spare_server, $lowest_load, $required) = @_;
894:
895: if ($required) {
896: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
897: my $remoterev = &get_server_loncaparev(undef,$try_server);
898: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
899: if (($major eq '' && $minor eq '') ||
900: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
901: return ($spare_server,$lowest_load);
902: }
903: }
904:
905: my $loadans = &reply('load', $try_server);
906: my $userloadans = &reply('userload',$try_server);
907:
908: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
909: return ($spare_server, $lowest_load); #didn't get a number from the server
910: }
911:
912: my $load;
913: if ($loadans =~ /\d/) {
914: if ($userloadans =~ /\d/) {
915: #both are numbers, pick the bigger one
916: $load = ($loadans > $userloadans) ? $loadans
917: : $userloadans;
918: } else {
919: $load = $loadans;
920: }
921: } else {
922: $load = $userloadans;
923: }
924:
925: if (($load =~ /\d/) && ($load < $lowest_load)) {
926: $spare_server = $try_server;
927: $lowest_load = $load;
928: }
929: return ($spare_server,$lowest_load);
930: }
931:
932: # --------------------------- ask offload servers if user already has a session
933: sub find_existing_session {
934: my ($udom,$uname) = @_;
935: my $spareshash = &this_host_spares($udom);
936: if (ref($spareshash) eq 'HASH') {
937: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
938: foreach my $try_server (@{ $spareshash->{'primary'} }) {
939: return $try_server if (&has_user_session($try_server, $udom, $uname));
940: }
941: }
942: if (ref($spareshash->{'default'}) eq 'ARRAY') {
943: foreach my $try_server (@{ $spareshash->{'default'} }) {
944: return $try_server if (&has_user_session($try_server, $udom, $uname));
945: }
946: }
947: }
948: return;
949: }
950:
951: # -------------------------------- ask if server already has a session for user
952: sub has_user_session {
953: my ($lonid,$udom,$uname) = @_;
954: my $result = &reply(join(':','userhassession',
955: map {&escape($_)} ($udom,$uname)),$lonid);
956: return 1 if ($result eq 'ok');
957:
958: return 0;
959: }
960:
961: # --------- determine least loaded server in a user's domain which allows login
962:
963: sub choose_server {
964: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
965: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
966: my %servers = &get_servers($udom);
967: my $lowest_load = 30000;
968: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
969: if ($skiploadbal) {
970: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
971: unless (defined($cached)) {
972: my $cachetime = 60*60*24;
973: my %domconfig =
974: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
975: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
976: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
977: $cachetime);
978: }
979: }
980: }
981: foreach my $lonhost (keys(%servers)) {
982: if ($skiploadbal) {
983: if (ref($balancers) eq 'HASH') {
984: next if (exists($balancers->{$lonhost}));
985: }
986: }
987: my $loginvia;
988: if ($checkloginvia) {
989: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
990: if ($loginvia) {
991: my ($server,$path) = split(/:/,$loginvia);
992: ($login_host, $lowest_load) =
993: &compare_server_load($server, $login_host, $lowest_load, $required);
994: if ($login_host eq $server) {
995: $portal_path = $path;
996: $isredirect = 1;
997: }
998: } else {
999: ($login_host, $lowest_load) =
1000: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1001: if ($login_host eq $lonhost) {
1002: $portal_path = '';
1003: $isredirect = '';
1004: }
1005: }
1006: } else {
1007: ($login_host, $lowest_load) =
1008: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1009: }
1010: }
1011: if ($login_host ne '') {
1012: $hostname = &hostname($login_host);
1013: }
1014: return ($login_host,$hostname,$portal_path,$isredirect);
1015: }
1016:
1017: # --------------------------------------------- Try to change a user's password
1018:
1019: sub changepass {
1020: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1021: $currentpass = &escape($currentpass);
1022: $newpass = &escape($newpass);
1023: my $lonhost = $perlvar{'lonHostID'};
1024: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1025: $server);
1026: if (! $answer) {
1027: &logthis("No reply on password change request to $server ".
1028: "by $uname in domain $udom.");
1029: } elsif ($answer =~ "^ok") {
1030: &logthis("$uname in $udom successfully changed their password ".
1031: "on $server.");
1032: } elsif ($answer =~ "^pwchange_failure") {
1033: &logthis("$uname in $udom was unable to change their password ".
1034: "on $server. The action was blocked by either lcpasswd ".
1035: "or pwchange");
1036: } elsif ($answer =~ "^non_authorized") {
1037: &logthis("$uname in $udom did not get their password correct when ".
1038: "attempting to change it on $server.");
1039: } elsif ($answer =~ "^auth_mode_error") {
1040: &logthis("$uname in $udom attempted to change their password despite ".
1041: "not being locally or internally authenticated on $server.");
1042: } elsif ($answer =~ "^unknown_user") {
1043: &logthis("$uname in $udom attempted to change their password ".
1044: "on $server but were unable to because $server is not ".
1045: "their home server.");
1046: } elsif ($answer =~ "^refused") {
1047: &logthis("$server refused to change $uname in $udom password because ".
1048: "it was sent an unencrypted request to change the password.");
1049: } elsif ($answer =~ "invalid_client") {
1050: &logthis("$server refused to change $uname in $udom password because ".
1051: "it was a reset by e-mail originating from an invalid server.");
1052: }
1053: return $answer;
1054: }
1055:
1056: # ----------------------- Try to determine user's current authentication scheme
1057:
1058: sub queryauthenticate {
1059: my ($uname,$udom)=@_;
1060: my $uhome=&homeserver($uname,$udom);
1061: if (!$uhome) {
1062: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1063: return 'no_host';
1064: }
1065: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1066: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1067: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1068: }
1069: return $answer;
1070: }
1071:
1072: # --------- Try to authenticate user from domain's lib servers (first this one)
1073:
1074: sub authenticate {
1075: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1076: $upass=&escape($upass);
1077: $uname= &LONCAPA::clean_username($uname);
1078: my $uhome=&homeserver($uname,$udom,1);
1079: my $newhome;
1080: if ((!$uhome) || ($uhome eq 'no_host')) {
1081: # Maybe the machine was offline and only re-appeared again recently?
1082: &reconlonc();
1083: # One more
1084: $uhome=&homeserver($uname,$udom,1);
1085: if (($uhome eq 'no_host') && $checkdefauth) {
1086: if (defined(&domain($udom,'primary'))) {
1087: $newhome=&domain($udom,'primary');
1088: }
1089: if ($newhome ne '') {
1090: $uhome = $newhome;
1091: }
1092: }
1093: if ((!$uhome) || ($uhome eq 'no_host')) {
1094: &logthis("User $uname at $udom is unknown in authenticate");
1095: return 'no_host';
1096: }
1097: }
1098: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1099: if ($answer eq 'authorized') {
1100: if ($newhome) {
1101: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1102: return 'no_account_on_host';
1103: } else {
1104: &logthis("User $uname at $udom authorized by $uhome");
1105: return $uhome;
1106: }
1107: }
1108: if ($answer eq 'non_authorized') {
1109: &logthis("User $uname at $udom rejected by $uhome");
1110: return 'no_host';
1111: }
1112: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1113: return 'no_host';
1114: }
1115:
1116: sub can_host_session {
1117: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1118: my $canhost = 1;
1119: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1120: if (ref($remotesessions) eq 'HASH') {
1121: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1122: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1123: $canhost = 0;
1124: } else {
1125: $canhost = 1;
1126: }
1127: }
1128: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1129: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1130: $canhost = 1;
1131: } else {
1132: $canhost = 0;
1133: }
1134: }
1135: if ($canhost) {
1136: if ($remotesessions->{'version'} ne '') {
1137: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1138: if ($reqmajor ne '' && $reqminor ne '') {
1139: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1140: my $major = $1;
1141: my $minor = $2;
1142: if (($major < $reqmajor ) ||
1143: (($major == $reqmajor) && ($minor < $reqminor))) {
1144: $canhost = 0;
1145: }
1146: } else {
1147: $canhost = 0;
1148: }
1149: }
1150: }
1151: }
1152: }
1153: if ($canhost) {
1154: if (ref($hostedsessions) eq 'HASH') {
1155: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1156: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1157: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1158: if (($uint_dom ne '') &&
1159: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1160: $canhost = 0;
1161: } else {
1162: $canhost = 1;
1163: }
1164: }
1165: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1166: if (($uint_dom ne '') &&
1167: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1168: $canhost = 1;
1169: } else {
1170: $canhost = 0;
1171: }
1172: }
1173: }
1174: }
1175: return $canhost;
1176: }
1177:
1178: sub spare_can_host {
1179: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1180: my $canhost=1;
1181: my @intdoms;
1182: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1183: if (ref($internet_names) eq 'ARRAY') {
1184: @intdoms = @{$internet_names};
1185: }
1186: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1187: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1188: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1189: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1190: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1191: $canhost = &can_host_session($udom,$try_server,$remoterev,
1192: $remotesessions,
1193: $defdomdefaults{'hostedsessions'});
1194: }
1195: return $canhost;
1196: }
1197:
1198: sub this_host_spares {
1199: my ($dom) = @_;
1200: my ($dom_in_use,$lonhost_in_use,$result);
1201: my @hosts = ¤t_machine_ids();
1202: foreach my $lonhost (@hosts) {
1203: if (&host_domain($lonhost) eq $dom) {
1204: $dom_in_use = $dom;
1205: $lonhost_in_use = $lonhost;
1206: last;
1207: }
1208: }
1209: if ($dom_in_use ne '') {
1210: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1211: }
1212: if (ref($result) ne 'HASH') {
1213: $lonhost_in_use = $perlvar{'lonHostID'};
1214: $dom_in_use = &host_domain($lonhost_in_use);
1215: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1216: if (ref($result) ne 'HASH') {
1217: $result = \%spareid;
1218: }
1219: }
1220: return $result;
1221: }
1222:
1223: sub spares_for_offload {
1224: my ($dom_in_use,$lonhost_in_use) = @_;
1225: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1226: if (defined($cached)) {
1227: return $result;
1228: } else {
1229: my $cachetime = 60*60*24;
1230: my %domconfig =
1231: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1232: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1233: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1234: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1235: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1236: }
1237: }
1238: }
1239: }
1240: return;
1241: }
1242:
1243: sub get_lonbalancer_config {
1244: my ($servers) = @_;
1245: my ($currbalancer,$currtargets);
1246: if (ref($servers) eq 'HASH') {
1247: foreach my $server (keys(%{$servers})) {
1248: my %what = (
1249: spareid => 1,
1250: perlvar => 1,
1251: );
1252: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1253: if ($result eq 'ok') {
1254: if (ref($returnhash) eq 'HASH') {
1255: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1256: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1257: $currbalancer = $server;
1258: $currtargets = {};
1259: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1260: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1261: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1262: }
1263: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1264: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1265: }
1266: }
1267: last;
1268: }
1269: }
1270: }
1271: }
1272: }
1273: }
1274: return ($currbalancer,$currtargets);
1275: }
1276:
1277: sub check_loadbalancing {
1278: my ($uname,$udom) = @_;
1279: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1280: $rule_in_effect,$offloadto,$otherserver);
1281: my $lonhost = $perlvar{'lonHostID'};
1282: my @hosts = ¤t_machine_ids();
1283: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1284: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1285: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1286: my $serverhomedom = &host_domain($lonhost);
1287:
1288: my $cachetime = 60*60*24;
1289:
1290: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1291: $dom_in_use = $udom;
1292: $homeintdom = 1;
1293: } else {
1294: $dom_in_use = $serverhomedom;
1295: }
1296: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1297: unless (defined($cached)) {
1298: my %domconfig =
1299: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1300: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1301: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1302: }
1303: }
1304: if (ref($result) eq 'HASH') {
1305: ($is_balancer,$currtargets,$currrules) =
1306: &check_balancer_result($result,@hosts);
1307: if ($is_balancer) {
1308: if (ref($currrules) eq 'HASH') {
1309: if ($homeintdom) {
1310: if ($uname ne '') {
1311: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1312: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1313: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1314: $rule_in_effect = $currrules->{'_LC_author'};
1315: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1316: $rule_in_effect = $currrules->{'_LC_adv'}
1317: }
1318: }
1319: if ($rule_in_effect eq '') {
1320: my %userenv = &userenvironment($udom,$uname,'inststatus');
1321: if ($userenv{'inststatus'} ne '') {
1322: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1323: my ($othertitle,$usertypes,$types) =
1324: &Apache::loncommon::sorted_inst_types($udom);
1325: if (ref($types) eq 'ARRAY') {
1326: foreach my $type (@{$types}) {
1327: if (grep(/^\Q$type\E$/,@statuses)) {
1328: if (exists($currrules->{$type})) {
1329: $rule_in_effect = $currrules->{$type};
1330: }
1331: }
1332: }
1333: }
1334: } else {
1335: if (exists($currrules->{'default'})) {
1336: $rule_in_effect = $currrules->{'default'};
1337: }
1338: }
1339: }
1340: } else {
1341: if (exists($currrules->{'default'})) {
1342: $rule_in_effect = $currrules->{'default'};
1343: }
1344: }
1345: } else {
1346: if ($currrules->{'_LC_external'} ne '') {
1347: $rule_in_effect = $currrules->{'_LC_external'};
1348: }
1349: }
1350: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1351: $uname,$udom);
1352: }
1353: }
1354: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1355: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1356: unless (defined($cached)) {
1357: my %domconfig =
1358: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1359: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1360: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1361: }
1362: }
1363: if (ref($result) eq 'HASH') {
1364: ($is_balancer,$currtargets,$currrules) =
1365: &check_balancer_result($result,@hosts);
1366: if ($is_balancer) {
1367: if (ref($currrules) eq 'HASH') {
1368: if ($currrules->{'_LC_internetdom'} ne '') {
1369: $rule_in_effect = $currrules->{'_LC_internetdom'};
1370: }
1371: }
1372: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1373: $uname,$udom);
1374: }
1375: } else {
1376: if ($perlvar{'lonBalancer'} eq 'yes') {
1377: $is_balancer = 1;
1378: $offloadto = &this_host_spares($dom_in_use);
1379: }
1380: }
1381: } else {
1382: if ($perlvar{'lonBalancer'} eq 'yes') {
1383: $is_balancer = 1;
1384: $offloadto = &this_host_spares($dom_in_use);
1385: }
1386: }
1387: if ($is_balancer) {
1388: my $lowest_load = 30000;
1389: if (ref($offloadto) eq 'HASH') {
1390: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1391: foreach my $try_server (@{$offloadto->{'primary'}}) {
1392: ($otherserver,$lowest_load) =
1393: &compare_server_load($try_server,$otherserver,$lowest_load);
1394: }
1395: }
1396: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1397:
1398: if (!$found_server) {
1399: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1400: foreach my $try_server (@{$offloadto->{'default'}}) {
1401: ($otherserver,$lowest_load) =
1402: &compare_server_load($try_server,$otherserver,$lowest_load);
1403: }
1404: }
1405: }
1406: } elsif (ref($offloadto) eq 'ARRAY') {
1407: if (@{$offloadto} == 1) {
1408: $otherserver = $offloadto->[0];
1409: } elsif (@{$offloadto} > 1) {
1410: foreach my $try_server (@{$offloadto}) {
1411: ($otherserver,$lowest_load) =
1412: &compare_server_load($try_server,$otherserver,$lowest_load);
1413: }
1414: }
1415: }
1416: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1417: $is_balancer = 0;
1418: if ($uname ne '' && $udom ne '') {
1419: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1420:
1421: &appenv({'user.loadbalexempt' => $lonhost,
1422: 'user.loadbalcheck.time' => time});
1423: }
1424: }
1425: }
1426: }
1427: return ($is_balancer,$otherserver);
1428: }
1429:
1430: sub check_balancer_result {
1431: my ($result,@hosts) = @_;
1432: my ($is_balancer,$currtargets,$currrules);
1433: if (ref($result) eq 'HASH') {
1434: if ($result->{'lonhost'} ne '') {
1435: my $currbalancer = $result->{'lonhost'};
1436: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1437: $is_balancer = 1;
1438: $currtargets = $result->{'targets'};
1439: $currrules = $result->{'rules'};
1440: }
1441: } else {
1442: foreach my $key (keys(%{$result})) {
1443: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1444: (ref($result->{$key}) eq 'HASH')) {
1445: $is_balancer = 1;
1446: $currrules = $result->{$key}{'rules'};
1447: $currtargets = $result->{$key}{'targets'};
1448: last;
1449: }
1450: }
1451: }
1452: }
1453: return ($is_balancer,$currtargets,$currrules);
1454: }
1455:
1456: sub get_loadbalancer_targets {
1457: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1458: my $offloadto;
1459: if ($rule_in_effect eq 'none') {
1460: return [$perlvar{'lonHostID'}];
1461: } elsif ($rule_in_effect eq '') {
1462: $offloadto = $currtargets;
1463: } else {
1464: if ($rule_in_effect eq 'homeserver') {
1465: my $homeserver = &homeserver($uname,$udom);
1466: if ($homeserver ne 'no_host') {
1467: $offloadto = [$homeserver];
1468: }
1469: } elsif ($rule_in_effect eq 'externalbalancer') {
1470: my %domconfig =
1471: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1472: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1473: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1474: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1475: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1476: }
1477: }
1478: } else {
1479: my %servers = &internet_dom_servers($udom);
1480: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1481: if (&hostname($remotebalancer) ne '') {
1482: $offloadto = [$remotebalancer];
1483: }
1484: }
1485: } elsif (&hostname($rule_in_effect) ne '') {
1486: $offloadto = [$rule_in_effect];
1487: }
1488: }
1489: return $offloadto;
1490: }
1491:
1492: sub internet_dom_servers {
1493: my ($dom) = @_;
1494: my (%uniqservers,%servers);
1495: my $primaryserver = &hostname(&domain($dom,'primary'));
1496: my @machinedoms = &machine_domains($primaryserver);
1497: foreach my $mdom (@machinedoms) {
1498: my %currservers = %servers;
1499: my %server = &get_servers($mdom);
1500: %servers = (%currservers,%server);
1501: }
1502: my %by_hostname;
1503: foreach my $id (keys(%servers)) {
1504: push(@{$by_hostname{$servers{$id}}},$id);
1505: }
1506: foreach my $hostname (sort(keys(%by_hostname))) {
1507: if (@{$by_hostname{$hostname}} > 1) {
1508: my $match = 0;
1509: foreach my $id (@{$by_hostname{$hostname}}) {
1510: if (&host_domain($id) eq $dom) {
1511: $uniqservers{$id} = $hostname;
1512: $match = 1;
1513: }
1514: }
1515: unless ($match) {
1516: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1517: }
1518: } else {
1519: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1520: }
1521: }
1522: return %uniqservers;
1523: }
1524:
1525: # ---------------------- Find the homebase for a user from domain's lib servers
1526:
1527: my %homecache;
1528: sub homeserver {
1529: my ($uname,$udom,$ignoreBadCache)=@_;
1530: my $index="$uname:$udom";
1531:
1532: if (exists($homecache{$index})) { return $homecache{$index}; }
1533:
1534: my %servers = &get_servers($udom,'library');
1535: foreach my $tryserver (keys(%servers)) {
1536: next if ($ignoreBadCache ne 'true' &&
1537: exists($badServerCache{$tryserver}));
1538:
1539: my $answer=reply("home:$udom:$uname",$tryserver);
1540: if ($answer eq 'found') {
1541: delete($badServerCache{$tryserver});
1542: return $homecache{$index}=$tryserver;
1543: } elsif ($answer eq 'no_host') {
1544: $badServerCache{$tryserver}=1;
1545: }
1546: }
1547: return 'no_host';
1548: }
1549:
1550: # ------------------------------------- Find the usernames behind a list of IDs
1551:
1552: sub idget {
1553: my ($udom,@ids)=@_;
1554: my %returnhash=();
1555:
1556: my %servers = &get_servers($udom,'library');
1557: foreach my $tryserver (keys(%servers)) {
1558: my $idlist=join('&',@ids);
1559: $idlist=~tr/A-Z/a-z/;
1560: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1561: my @answer=();
1562: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1563: @answer=split(/\&/,$reply);
1564: } ;
1565: my $i;
1566: for ($i=0;$i<=$#ids;$i++) {
1567: if ($answer[$i]) {
1568: $returnhash{$ids[$i]}=$answer[$i];
1569: }
1570: }
1571: }
1572: return %returnhash;
1573: }
1574:
1575: # ------------------------------------- Find the IDs behind a list of usernames
1576:
1577: sub idrget {
1578: my ($udom,@unames)=@_;
1579: my %returnhash=();
1580: foreach my $uname (@unames) {
1581: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1582: }
1583: return %returnhash;
1584: }
1585:
1586: # ------------------------------- Store away a list of names and associated IDs
1587:
1588: sub idput {
1589: my ($udom,%ids)=@_;
1590: my %servers=();
1591: foreach my $uname (keys(%ids)) {
1592: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1593: my $uhom=&homeserver($uname,$udom);
1594: if ($uhom ne 'no_host') {
1595: my $id=&escape($ids{$uname});
1596: $id=~tr/A-Z/a-z/;
1597: my $esc_unam=&escape($uname);
1598: if ($servers{$uhom}) {
1599: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1600: } else {
1601: $servers{$uhom}=$id.'='.$esc_unam;
1602: }
1603: }
1604: }
1605: foreach my $server (keys(%servers)) {
1606: &critical('idput:'.$udom.':'.$servers{$server},$server);
1607: }
1608: }
1609:
1610: # ---------------------------------------- Delete unwanted IDs from ids.db file
1611:
1612: sub iddel {
1613: my ($udom,$idshashref,$uhome)=@_;
1614: my %result=();
1615: unless (ref($idshashref) eq 'HASH') {
1616: return %result;
1617: }
1618: my %servers=();
1619: while (my ($id,$uname) = each(%{$idshashref})) {
1620: my $uhom;
1621: if ($uhome) {
1622: $uhom = $uhome;
1623: } else {
1624: $uhom=&homeserver($uname,$udom);
1625: }
1626: if ($uhom ne 'no_host') {
1627: if ($servers{$uhom}) {
1628: $servers{$uhom}.='&'.&escape($id);
1629: } else {
1630: $servers{$uhom}=&escape($id);
1631: }
1632: }
1633: }
1634: foreach my $server (keys(%servers)) {
1635: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1636: }
1637: return %result;
1638: }
1639:
1640: # ------------------------------dump from db file owned by domainconfig user
1641: sub dump_dom {
1642: my ($namespace, $udom, $regexp) = @_;
1643:
1644: $udom ||= $env{'user.domain'};
1645:
1646: return () unless $udom;
1647:
1648: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1649: }
1650:
1651: # ------------------------------------------ get items from domain db files
1652:
1653: sub get_dom {
1654: my ($namespace,$storearr,$udom,$uhome)=@_;
1655: return if ($udom eq 'public');
1656: my $items='';
1657: foreach my $item (@$storearr) {
1658: $items.=&escape($item).'&';
1659: }
1660: $items=~s/\&$//;
1661: if (!$udom) {
1662: $udom=$env{'user.domain'};
1663: return if ($udom eq 'public');
1664: if (defined(&domain($udom,'primary'))) {
1665: $uhome=&domain($udom,'primary');
1666: } else {
1667: undef($uhome);
1668: }
1669: } else {
1670: if (!$uhome) {
1671: if (defined(&domain($udom,'primary'))) {
1672: $uhome=&domain($udom,'primary');
1673: }
1674: }
1675: }
1676: if ($udom && $uhome && ($uhome ne 'no_host')) {
1677: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1678: my %returnhash;
1679: if ($rep eq '' || $rep =~ /^error: 2 /) {
1680: return %returnhash;
1681: }
1682: my @pairs=split(/\&/,$rep);
1683: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1684: return @pairs;
1685: }
1686: my $i=0;
1687: foreach my $item (@$storearr) {
1688: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1689: $i++;
1690: }
1691: return %returnhash;
1692: } else {
1693: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1694: }
1695: }
1696:
1697: # -------------------------------------------- put items in domain db files
1698:
1699: sub put_dom {
1700: my ($namespace,$storehash,$udom,$uhome)=@_;
1701: if (!$udom) {
1702: $udom=$env{'user.domain'};
1703: if (defined(&domain($udom,'primary'))) {
1704: $uhome=&domain($udom,'primary');
1705: } else {
1706: undef($uhome);
1707: }
1708: } else {
1709: if (!$uhome) {
1710: if (defined(&domain($udom,'primary'))) {
1711: $uhome=&domain($udom,'primary');
1712: }
1713: }
1714: }
1715: if ($udom && $uhome && ($uhome ne 'no_host')) {
1716: my $items='';
1717: foreach my $item (keys(%$storehash)) {
1718: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1719: }
1720: $items=~s/\&$//;
1721: return &reply("putdom:$udom:$namespace:$items",$uhome);
1722: } else {
1723: &logthis("put_dom failed - no homeserver and/or domain");
1724: }
1725: }
1726:
1727: # --------------------- newput for items in db file owned by domainconfig user
1728: sub newput_dom {
1729: my ($namespace,$storehash,$udom) = @_;
1730: my $result;
1731: if (!$udom) {
1732: $udom=$env{'user.domain'};
1733: }
1734: if ($udom) {
1735: my $uname = &get_domainconfiguser($udom);
1736: $result = &newput($namespace,$storehash,$udom,$uname);
1737: }
1738: return $result;
1739: }
1740:
1741: # --------------------- delete for items in db file owned by domainconfig user
1742: sub del_dom {
1743: my ($namespace,$storearr,$udom)=@_;
1744: if (ref($storearr) eq 'ARRAY') {
1745: if (!$udom) {
1746: $udom=$env{'user.domain'};
1747: }
1748: if ($udom) {
1749: my $uname = &get_domainconfiguser($udom);
1750: return &del($namespace,$storearr,$udom,$uname);
1751: }
1752: }
1753: }
1754:
1755: # ----------------------------------construct domainconfig user for a domain
1756: sub get_domainconfiguser {
1757: my ($udom) = @_;
1758: return $udom.'-domainconfig';
1759: }
1760:
1761: sub retrieve_inst_usertypes {
1762: my ($udom) = @_;
1763: my (%returnhash,@order);
1764: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1765: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1766: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1767: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1768: } else {
1769: if (defined(&domain($udom,'primary'))) {
1770: my $uhome=&domain($udom,'primary');
1771: my $rep=&reply("inst_usertypes:$udom",$uhome);
1772: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1773: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1774: return (\%returnhash,\@order);
1775: }
1776: my ($hashitems,$orderitems) = split(/:/,$rep);
1777: my @pairs=split(/\&/,$hashitems);
1778: foreach my $item (@pairs) {
1779: my ($key,$value)=split(/=/,$item,2);
1780: $key = &unescape($key);
1781: next if ($key =~ /^error: 2 /);
1782: $returnhash{$key}=&thaw_unescape($value);
1783: }
1784: my @esc_order = split(/\&/,$orderitems);
1785: foreach my $item (@esc_order) {
1786: push(@order,&unescape($item));
1787: }
1788: } else {
1789: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1790: }
1791: return (\%returnhash,\@order);
1792: }
1793: }
1794:
1795: sub is_domainimage {
1796: my ($url) = @_;
1797: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1798: if (&domain($1) ne '') {
1799: return '1';
1800: }
1801: }
1802: return;
1803: }
1804:
1805: sub inst_directory_query {
1806: my ($srch) = @_;
1807: my $udom = $srch->{'srchdomain'};
1808: my %results;
1809: my $homeserver = &domain($udom,'primary');
1810: my $outcome;
1811: if ($homeserver ne '') {
1812: my $queryid=&reply("querysend:instdirsearch:".
1813: &escape($srch->{'srchby'}).':'.
1814: &escape($srch->{'srchterm'}).':'.
1815: &escape($srch->{'srchtype'}),$homeserver);
1816: my $host=&hostname($homeserver);
1817: if ($queryid !~/^\Q$host\E\_/) {
1818: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1819: return;
1820: }
1821: my $response = &get_query_reply($queryid);
1822: my $maxtries = 5;
1823: my $tries = 1;
1824: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1825: $response = &get_query_reply($queryid);
1826: $tries ++;
1827: }
1828:
1829: if (!&error($response) && $response ne 'refused') {
1830: if ($response eq 'unavailable') {
1831: $outcome = $response;
1832: } else {
1833: $outcome = 'ok';
1834: my @matches = split(/\n/,$response);
1835: foreach my $match (@matches) {
1836: my ($key,$value) = split(/=/,$match);
1837: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1838: }
1839: }
1840: }
1841: }
1842: return ($outcome,%results);
1843: }
1844:
1845: sub usersearch {
1846: my ($srch) = @_;
1847: my $dom = $srch->{'srchdomain'};
1848: my %results;
1849: my %libserv = &all_library();
1850: my $query = 'usersearch';
1851: foreach my $tryserver (keys(%libserv)) {
1852: if (&host_domain($tryserver) eq $dom) {
1853: my $host=&hostname($tryserver);
1854: my $queryid=
1855: &reply("querysend:".&escape($query).':'.
1856: &escape($srch->{'srchby'}).':'.
1857: &escape($srch->{'srchtype'}).':'.
1858: &escape($srch->{'srchterm'}),$tryserver);
1859: if ($queryid !~/^\Q$host\E\_/) {
1860: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1861: next;
1862: }
1863: my $reply = &get_query_reply($queryid);
1864: my $maxtries = 1;
1865: my $tries = 1;
1866: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1867: $reply = &get_query_reply($queryid);
1868: $tries ++;
1869: }
1870: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1871: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1872: } else {
1873: my @matches;
1874: if ($reply =~ /\n/) {
1875: @matches = split(/\n/,$reply);
1876: } else {
1877: @matches = split(/\&/,$reply);
1878: }
1879: foreach my $match (@matches) {
1880: my ($uname,$udom,%userhash);
1881: foreach my $entry (split(/:/,$match)) {
1882: my ($key,$value) =
1883: map {&unescape($_);} split(/=/,$entry);
1884: $userhash{$key} = $value;
1885: if ($key eq 'username') {
1886: $uname = $value;
1887: } elsif ($key eq 'domain') {
1888: $udom = $value;
1889: }
1890: }
1891: $results{$uname.':'.$udom} = \%userhash;
1892: }
1893: }
1894: }
1895: }
1896: return %results;
1897: }
1898:
1899: sub get_instuser {
1900: my ($udom,$uname,$id) = @_;
1901: my $homeserver = &domain($udom,'primary');
1902: my ($outcome,%results);
1903: if ($homeserver ne '') {
1904: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1905: &escape($id).':'.&escape($udom),$homeserver);
1906: my $host=&hostname($homeserver);
1907: if ($queryid !~/^\Q$host\E\_/) {
1908: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1909: return;
1910: }
1911: my $response = &get_query_reply($queryid);
1912: my $maxtries = 5;
1913: my $tries = 1;
1914: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1915: $response = &get_query_reply($queryid);
1916: $tries ++;
1917: }
1918: if (!&error($response) && $response ne 'refused') {
1919: if ($response eq 'unavailable') {
1920: $outcome = $response;
1921: } else {
1922: $outcome = 'ok';
1923: my @matches = split(/\n/,$response);
1924: foreach my $match (@matches) {
1925: my ($key,$value) = split(/=/,$match);
1926: $results{&unescape($key)} = &thaw_unescape($value);
1927: }
1928: }
1929: }
1930: }
1931: my %userinfo;
1932: if (ref($results{$uname}) eq 'HASH') {
1933: %userinfo = %{$results{$uname}};
1934: }
1935: return ($outcome,%userinfo);
1936: }
1937:
1938: sub inst_rulecheck {
1939: my ($udom,$uname,$id,$item,$rules) = @_;
1940: my %returnhash;
1941: if ($udom ne '') {
1942: if (ref($rules) eq 'ARRAY') {
1943: @{$rules} = map {&escape($_);} (@{$rules});
1944: my $rulestr = join(':',@{$rules});
1945: my $homeserver=&domain($udom,'primary');
1946: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1947: my $response;
1948: if ($item eq 'username') {
1949: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1950: ':'.&escape($uname).':'.$rulestr,
1951: $homeserver));
1952: } elsif ($item eq 'id') {
1953: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1954: ':'.&escape($id).':'.$rulestr,
1955: $homeserver));
1956: } elsif ($item eq 'selfcreate') {
1957: $response=&unescape(&reply('instselfcreatecheck:'.
1958: &escape($udom).':'.&escape($uname).
1959: ':'.$rulestr,$homeserver));
1960: }
1961: if ($response ne 'refused') {
1962: my @pairs=split(/\&/,$response);
1963: foreach my $item (@pairs) {
1964: my ($key,$value)=split(/=/,$item,2);
1965: $key = &unescape($key);
1966: next if ($key =~ /^error: 2 /);
1967: $returnhash{$key}=&thaw_unescape($value);
1968: }
1969: }
1970: }
1971: }
1972: }
1973: return %returnhash;
1974: }
1975:
1976: sub inst_userrules {
1977: my ($udom,$check) = @_;
1978: my (%ruleshash,@ruleorder);
1979: if ($udom ne '') {
1980: my $homeserver=&domain($udom,'primary');
1981: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1982: my $response;
1983: if ($check eq 'id') {
1984: $response=&reply('instidrules:'.&escape($udom),
1985: $homeserver);
1986: } elsif ($check eq 'email') {
1987: $response=&reply('instemailrules:'.&escape($udom),
1988: $homeserver);
1989: } else {
1990: $response=&reply('instuserrules:'.&escape($udom),
1991: $homeserver);
1992: }
1993: if (($response ne 'refused') && ($response ne 'error') &&
1994: ($response ne 'unknown_cmd') &&
1995: ($response ne 'no_such_host')) {
1996: my ($hashitems,$orderitems) = split(/:/,$response);
1997: my @pairs=split(/\&/,$hashitems);
1998: foreach my $item (@pairs) {
1999: my ($key,$value)=split(/=/,$item,2);
2000: $key = &unescape($key);
2001: next if ($key =~ /^error: 2 /);
2002: $ruleshash{$key}=&thaw_unescape($value);
2003: }
2004: my @esc_order = split(/\&/,$orderitems);
2005: foreach my $item (@esc_order) {
2006: push(@ruleorder,&unescape($item));
2007: }
2008: }
2009: }
2010: }
2011: return (\%ruleshash,\@ruleorder);
2012: }
2013:
2014: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2015:
2016: sub get_domain_defaults {
2017: my ($domain,$ignore_cache) = @_;
2018: return if (($domain eq '') || ($domain eq 'public'));
2019: my $cachetime = 60*60*24;
2020: unless ($ignore_cache) {
2021: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2022: if (defined($cached)) {
2023: if (ref($result) eq 'HASH') {
2024: return %{$result};
2025: }
2026: }
2027: }
2028: my %domdefaults;
2029: my %domconfig =
2030: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2031: 'requestcourses','inststatus',
2032: 'coursedefaults','usersessions',
2033: 'requestauthor','selfenrollment',
2034: 'coursecategories'],$domain);
2035: my @coursetypes = ('official','unofficial','community','textbook');
2036: if (ref($domconfig{'defaults'}) eq 'HASH') {
2037: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2038: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2039: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2040: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2041: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2042: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2043: } else {
2044: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2045: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2046: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2047: }
2048: if (ref($domconfig{'quotas'}) eq 'HASH') {
2049: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2050: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2051: } else {
2052: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2053: }
2054: my @usertools = ('aboutme','blog','webdav','portfolio');
2055: foreach my $item (@usertools) {
2056: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2057: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2058: }
2059: }
2060: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2061: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2062: }
2063: }
2064: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2065: foreach my $item ('official','unofficial','community','textbook') {
2066: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2067: }
2068: }
2069: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2070: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2071: }
2072: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2073: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2074: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2075: }
2076: }
2077: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2078: $domdefaults{'canuse_pdfforms'} = $domconfig{'coursedefaults'}{'canuse_pdfforms'};
2079: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2080: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2081: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2082: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2083: }
2084: foreach my $type (@coursetypes) {
2085: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2086: unless ($type eq 'community') {
2087: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2088: }
2089: }
2090: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2091: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2092: }
2093: if ($domdefaults{'postsubmit'} eq 'on') {
2094: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2095: $domdefaults{$type.'postsubtimeout'} =
2096: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2097: }
2098: }
2099: }
2100: }
2101: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2102: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2103: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2104: }
2105: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2106: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2107: }
2108: }
2109: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2110: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2111: my @settings = ('types','registered','enroll_dates','access_dates','section',
2112: 'approval','limit');
2113: foreach my $type (@coursetypes) {
2114: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2115: my @mgrdc = ();
2116: foreach my $item (@settings) {
2117: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2118: push(@mgrdc,$item);
2119: }
2120: }
2121: if (@mgrdc) {
2122: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2123: }
2124: }
2125: }
2126: }
2127: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2128: foreach my $type (@coursetypes) {
2129: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2130: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2131: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2132: }
2133: }
2134: }
2135: }
2136: }
2137: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2138: $domdefaults{'catauth'} = 'std';
2139: $domdefaults{'catunauth'} = 'std';
2140: if ($domconfig{'coursecategories'}{'auth'}) {
2141: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2142: }
2143: if ($domconfig{'coursecategories'}{'unauth'}) {
2144: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2145: }
2146: }
2147: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2148: return %domdefaults;
2149: }
2150:
2151: # --------------------------------------------------- Assign a key to a student
2152:
2153: sub assign_access_key {
2154: #
2155: # a valid key looks like uname:udom#comments
2156: # comments are being appended
2157: #
2158: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2159: $kdom=
2160: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2161: $knum=
2162: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2163: $cdom=
2164: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2165: $cnum=
2166: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2167: $udom=$env{'user.name'} unless (defined($udom));
2168: $uname=$env{'user.domain'} unless (defined($uname));
2169: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2170: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2171: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2172: # assigned to this person
2173: # - this should not happen,
2174: # unless something went wrong
2175: # the first time around
2176: # ready to assign
2177: $logentry=$1.'; '.$logentry;
2178: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2179: $kdom,$knum) eq 'ok') {
2180: # key now belongs to user
2181: my $envkey='key.'.$cdom.'_'.$cnum;
2182: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2183: &appenv({'environment.'.$envkey => $ckey});
2184: return 'ok';
2185: } else {
2186: return
2187: 'error: Count not permanently assign key, will need to be re-entered later.';
2188: }
2189: } else {
2190: return 'error: Could not assign key, try again later.';
2191: }
2192: } elsif (!$existing{$ckey}) {
2193: # the key does not exist
2194: return 'error: The key does not exist';
2195: } else {
2196: # the key is somebody else's
2197: return 'error: The key is already in use';
2198: }
2199: }
2200:
2201: # ------------------------------------------ put an additional comment on a key
2202:
2203: sub comment_access_key {
2204: #
2205: # a valid key looks like uname:udom#comments
2206: # comments are being appended
2207: #
2208: my ($ckey,$cdom,$cnum,$logentry)=@_;
2209: $cdom=
2210: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2211: $cnum=
2212: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2213: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2214: if ($existing{$ckey}) {
2215: $existing{$ckey}.='; '.$logentry;
2216: # ready to assign
2217: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2218: $cdom,$cnum) eq 'ok') {
2219: return 'ok';
2220: } else {
2221: return 'error: Count not store comment.';
2222: }
2223: } else {
2224: # the key does not exist
2225: return 'error: The key does not exist';
2226: }
2227: }
2228:
2229: # ------------------------------------------------------ Generate a set of keys
2230:
2231: sub generate_access_keys {
2232: my ($number,$cdom,$cnum,$logentry)=@_;
2233: $cdom=
2234: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2235: $cnum=
2236: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2237: unless (&allowed('mky',$cdom)) { return 0; }
2238: unless (($cdom) && ($cnum)) { return 0; }
2239: if ($number>10000) { return 0; }
2240: sleep(2); # make sure don't get same seed twice
2241: srand(time()^($$+($$<<15))); # from "Programming Perl"
2242: my $total=0;
2243: for (my $i=1;$i<=$number;$i++) {
2244: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2245: sprintf("%lx",int(100000*rand)).'-'.
2246: sprintf("%lx",int(100000*rand));
2247: $newkey=~s/1/g/g; # folks mix up 1 and l
2248: $newkey=~s/0/h/g; # and also 0 and O
2249: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2250: if ($existing{$newkey}) {
2251: $i--;
2252: } else {
2253: if (&put('accesskeys',
2254: { $newkey => '# generated '.localtime().
2255: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2256: '; '.$logentry },
2257: $cdom,$cnum) eq 'ok') {
2258: $total++;
2259: }
2260: }
2261: }
2262: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2263: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2264: return $total;
2265: }
2266:
2267: # ------------------------------------------------------- Validate an accesskey
2268:
2269: sub validate_access_key {
2270: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2271: $cdom=
2272: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2273: $cnum=
2274: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2275: $udom=$env{'user.domain'} unless (defined($udom));
2276: $uname=$env{'user.name'} unless (defined($uname));
2277: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2278: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2279: }
2280:
2281: # ------------------------------------- Find the section of student in a course
2282: sub devalidate_getsection_cache {
2283: my ($udom,$unam,$courseid)=@_;
2284: my $hashid="$udom:$unam:$courseid";
2285: &devalidate_cache_new('getsection',$hashid);
2286: }
2287:
2288: sub courseid_to_courseurl {
2289: my ($courseid) = @_;
2290: #already url style courseid
2291: return $courseid if ($courseid =~ m{^/});
2292:
2293: if (exists($env{'course.'.$courseid.'.num'})) {
2294: my $cnum = $env{'course.'.$courseid.'.num'};
2295: my $cdom = $env{'course.'.$courseid.'.domain'};
2296: return "/$cdom/$cnum";
2297: }
2298:
2299: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2300: if (exists($courseinfo{'num'})) {
2301: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2302: }
2303:
2304: return undef;
2305: }
2306:
2307: sub getsection {
2308: my ($udom,$unam,$courseid)=@_;
2309: my $cachetime=1800;
2310:
2311: my $hashid="$udom:$unam:$courseid";
2312: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2313: if (defined($cached)) { return $result; }
2314:
2315: my %Pending;
2316: my %Expired;
2317: #
2318: # Each role can either have not started yet (pending), be active,
2319: # or have expired.
2320: #
2321: # If there is an active role, we are done.
2322: #
2323: # If there is more than one role which has not started yet,
2324: # choose the one which will start sooner
2325: # If there is one role which has not started yet, return it.
2326: #
2327: # If there is more than one expired role, choose the one which ended last.
2328: # If there is a role which has expired, return it.
2329: #
2330: $courseid = &courseid_to_courseurl($courseid);
2331: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2332: foreach my $key (keys(%roleshash)) {
2333: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2334: my $section=$1;
2335: if ($key eq $courseid.'_st') { $section=''; }
2336: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2337: my $now=time;
2338: if (defined($end) && $end && ($now > $end)) {
2339: $Expired{$end}=$section;
2340: next;
2341: }
2342: if (defined($start) && $start && ($now < $start)) {
2343: $Pending{$start}=$section;
2344: next;
2345: }
2346: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2347: }
2348: #
2349: # Presumedly there will be few matching roles from the above
2350: # loop and the sorting time will be negligible.
2351: if (scalar(keys(%Pending))) {
2352: my ($time) = sort {$a <=> $b} keys(%Pending);
2353: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2354: }
2355: if (scalar(keys(%Expired))) {
2356: my @sorted = sort {$a <=> $b} keys(%Expired);
2357: my $time = pop(@sorted);
2358: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2359: }
2360: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2361: }
2362:
2363: sub save_cache {
2364: &purge_remembered();
2365: #&Apache::loncommon::validate_page();
2366: undef(%env);
2367: undef($env_loaded);
2368: }
2369:
2370: my $to_remember=-1;
2371: my %remembered;
2372: my %accessed;
2373: my $kicks=0;
2374: my $hits=0;
2375: sub make_key {
2376: my ($name,$id) = @_;
2377: if (length($id) > 65
2378: && length(&escape($id)) > 200) {
2379: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2380: }
2381: return &escape($name.':'.$id);
2382: }
2383:
2384: sub devalidate_cache_new {
2385: my ($name,$id,$debug) = @_;
2386: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2387: $id=&make_key($name,$id);
2388: $memcache->delete($id);
2389: delete($remembered{$id});
2390: delete($accessed{$id});
2391: }
2392:
2393: sub is_cached_new {
2394: my ($name,$id,$debug) = @_;
2395: $id=&make_key($name,$id);
2396: if (exists($remembered{$id})) {
2397: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2398: $accessed{$id}=[&gettimeofday()];
2399: $hits++;
2400: return ($remembered{$id},1);
2401: }
2402: my $value = $memcache->get($id);
2403: if (!(defined($value))) {
2404: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2405: return (undef,undef);
2406: }
2407: if ($value eq '__undef__') {
2408: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2409: $value=undef;
2410: }
2411: &make_room($id,$value,$debug);
2412: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2413: return ($value,1);
2414: }
2415:
2416: sub do_cache_new {
2417: my ($name,$id,$value,$time,$debug) = @_;
2418: $id=&make_key($name,$id);
2419: my $setvalue=$value;
2420: if (!defined($setvalue)) {
2421: $setvalue='__undef__';
2422: }
2423: if (!defined($time) ) {
2424: $time=600;
2425: }
2426: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2427: my $result = $memcache->set($id,$setvalue,$time);
2428: if (! $result) {
2429: &logthis("caching of id -> $id failed");
2430: $memcache->disconnect_all();
2431: }
2432: # need to make a copy of $value
2433: &make_room($id,$value,$debug);
2434: return $value;
2435: }
2436:
2437: sub make_room {
2438: my ($id,$value,$debug)=@_;
2439:
2440: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2441: : $value;
2442: if ($to_remember<0) { return; }
2443: $accessed{$id}=[&gettimeofday()];
2444: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2445: my $to_kick;
2446: my $max_time=0;
2447: foreach my $other (keys(%accessed)) {
2448: if (&tv_interval($accessed{$other}) > $max_time) {
2449: $to_kick=$other;
2450: $max_time=&tv_interval($accessed{$other});
2451: }
2452: }
2453: delete($remembered{$to_kick});
2454: delete($accessed{$to_kick});
2455: $kicks++;
2456: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2457: return;
2458: }
2459:
2460: sub purge_remembered {
2461: #&logthis("Tossing ".scalar(keys(%remembered)));
2462: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2463: undef(%remembered);
2464: undef(%accessed);
2465: }
2466: # ------------------------------------- Read an entry from a user's environment
2467:
2468: sub userenvironment {
2469: my ($udom,$unam,@what)=@_;
2470: my $items;
2471: foreach my $item (@what) {
2472: $items.=&escape($item).'&';
2473: }
2474: $items=~s/\&$//;
2475: my %returnhash=();
2476: my $uhome = &homeserver($unam,$udom);
2477: unless ($uhome eq 'no_host') {
2478: my @answer=split(/\&/,
2479: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2480: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2481: return %returnhash;
2482: }
2483: my $i;
2484: for ($i=0;$i<=$#what;$i++) {
2485: $returnhash{$what[$i]}=&unescape($answer[$i]);
2486: }
2487: }
2488: return %returnhash;
2489: }
2490:
2491: # ---------------------------------------------------------- Get a studentphoto
2492: sub studentphoto {
2493: my ($udom,$unam,$ext) = @_;
2494: my $home=&Apache::lonnet::homeserver($unam,$udom);
2495: if (defined($env{'request.course.id'})) {
2496: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2497: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2498: return(&retrievestudentphoto($udom,$unam,$ext));
2499: } else {
2500: my ($result,$perm_reqd)=
2501: &Apache::lonnet::auto_photo_permission($unam,$udom);
2502: if ($result eq 'ok') {
2503: if (!($perm_reqd eq 'yes')) {
2504: return(&retrievestudentphoto($udom,$unam,$ext));
2505: }
2506: }
2507: }
2508: }
2509: } else {
2510: my ($result,$perm_reqd) =
2511: &Apache::lonnet::auto_photo_permission($unam,$udom);
2512: if ($result eq 'ok') {
2513: if (!($perm_reqd eq 'yes')) {
2514: return(&retrievestudentphoto($udom,$unam,$ext));
2515: }
2516: }
2517: }
2518: return '/adm/lonKaputt/lonlogo_broken.gif';
2519: }
2520:
2521: sub retrievestudentphoto {
2522: my ($udom,$unam,$ext,$type) = @_;
2523: my $home=&Apache::lonnet::homeserver($unam,$udom);
2524: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2525: if ($ret eq 'ok') {
2526: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2527: if ($type eq 'thumbnail') {
2528: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2529: }
2530: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2531: return $tokenurl;
2532: } else {
2533: if ($type eq 'thumbnail') {
2534: return '/adm/lonKaputt/genericstudent_tn.gif';
2535: } else {
2536: return '/adm/lonKaputt/lonlogo_broken.gif';
2537: }
2538: }
2539: }
2540:
2541: # -------------------------------------------------------------------- New chat
2542:
2543: sub chatsend {
2544: my ($newentry,$anon,$group)=@_;
2545: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2546: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2547: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2548: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2549: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2550: &escape($newentry)).':'.$group,$chome);
2551: }
2552:
2553: # ------------------------------------------ Find current version of a resource
2554:
2555: sub getversion {
2556: my $fname=&clutter(shift);
2557: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2558: return ¤tversion(&filelocation('',$fname));
2559: }
2560:
2561: sub currentversion {
2562: my $fname=shift;
2563: my $author=$fname;
2564: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2565: my ($udom,$uname)=split(/\//,$author);
2566: my $home=&homeserver($uname,$udom);
2567: if ($home eq 'no_host') {
2568: return -1;
2569: }
2570: my $answer=&reply("currentversion:$fname",$home);
2571: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2572: return -1;
2573: }
2574: return $answer;
2575: }
2576:
2577: #
2578: # Return special version number of resource if set by override, empty otherwise
2579: #
2580: sub usedversion {
2581: my $fname=shift;
2582: unless ($fname) { $fname=$env{'request.uri'}; }
2583: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2584: if ($urlversion) { return $urlversion; }
2585: return '';
2586: }
2587:
2588: # ----------------------------- Subscribe to a resource, return URL if possible
2589:
2590: sub subscribe {
2591: my $fname=shift;
2592: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2593: $fname=~s/[\n\r]//g;
2594: my $author=$fname;
2595: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2596: my ($udom,$uname)=split(/\//,$author);
2597: my $home=homeserver($uname,$udom);
2598: if ($home eq 'no_host') {
2599: return 'not_found';
2600: }
2601: my $answer=reply("sub:$fname",$home);
2602: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2603: $answer.=' by '.$home;
2604: }
2605: return $answer;
2606: }
2607:
2608: # -------------------------------------------------------------- Replicate file
2609:
2610: sub repcopy {
2611: my $filename=shift;
2612: $filename=~s/\/+/\//g;
2613: my $londocroot = $perlvar{'lonDocRoot'};
2614: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2615: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2616: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2617: $filename=~m{^/*(uploaded|editupload)/}) {
2618: return &repcopy_userfile($filename);
2619: }
2620: $filename=~s/[\n\r]//g;
2621: my $transname="$filename.in.transfer";
2622: # FIXME: this should flock
2623: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2624: my $remoteurl=subscribe($filename);
2625: if ($remoteurl =~ /^con_lost by/) {
2626: &logthis("Subscribe returned $remoteurl: $filename");
2627: return 'unavailable';
2628: } elsif ($remoteurl eq 'not_found') {
2629: #&logthis("Subscribe returned not_found: $filename");
2630: return 'not_found';
2631: } elsif ($remoteurl =~ /^rejected by/) {
2632: &logthis("Subscribe returned $remoteurl: $filename");
2633: return 'forbidden';
2634: } elsif ($remoteurl eq 'directory') {
2635: return 'ok';
2636: } else {
2637: my $author=$filename;
2638: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2639: my ($udom,$uname)=split(/\//,$author);
2640: my $home=homeserver($uname,$udom);
2641: unless ($home eq $perlvar{'lonHostID'}) {
2642: my @parts=split(/\//,$filename);
2643: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2644: if ($path ne "$londocroot/res") {
2645: &logthis("Malconfiguration for replication: $filename");
2646: return 'bad_request';
2647: }
2648: my $count;
2649: for ($count=5;$count<$#parts;$count++) {
2650: $path.="/$parts[$count]";
2651: if ((-e $path)!=1) {
2652: mkdir($path,0777);
2653: }
2654: }
2655: my $ua=new LWP::UserAgent;
2656: my $request=new HTTP::Request('GET',"$remoteurl");
2657: my $response=$ua->request($request,$transname);
2658: if ($response->is_error()) {
2659: unlink($transname);
2660: my $message=$response->status_line;
2661: &logthis("<font color=\"blue\">WARNING:"
2662: ." LWP get: $message: $filename</font>");
2663: return 'unavailable';
2664: } else {
2665: if ($remoteurl!~/\.meta$/) {
2666: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2667: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2668: if ($mresponse->is_error()) {
2669: unlink($filename.'.meta');
2670: &logthis(
2671: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2672: }
2673: }
2674: rename($transname,$filename);
2675: return 'ok';
2676: }
2677: }
2678: }
2679: }
2680:
2681: # ------------------------------------------------ Get server side include body
2682: sub ssi_body {
2683: my ($filelink,%form)=@_;
2684: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2685: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2686: }
2687: my $output='';
2688: my $response;
2689: if ($filelink=~/^https?\:/) {
2690: ($output,$response)=&externalssi($filelink);
2691: } else {
2692: $filelink .= $filelink=~/\?/ ? '&' : '?';
2693: $filelink .= 'inhibitmenu=yes';
2694: ($output,$response)=&ssi($filelink,%form);
2695: }
2696: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2697: $output=~s/^.*?\<body[^\>]*\>//si;
2698: $output=~s/\<\/body\s*\>.*?$//si;
2699: if (wantarray) {
2700: return ($output, $response);
2701: } else {
2702: return $output;
2703: }
2704: }
2705:
2706: # --------------------------------------------------------- Server Side Include
2707:
2708: sub absolute_url {
2709: my ($host_name) = @_;
2710: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2711: if ($host_name eq '') {
2712: $host_name = $ENV{'SERVER_NAME'};
2713: }
2714: return $protocol.$host_name;
2715: }
2716:
2717: #
2718: # Server side include.
2719: # Parameters:
2720: # fn Possibly encrypted resource name/id.
2721: # form Hash that describes how the rendering should be done
2722: # and other things.
2723: # Returns:
2724: # Scalar context: The content of the response.
2725: # Array context: 2 element list of the content and the full response object.
2726: #
2727: sub ssi {
2728:
2729: my ($fn,%form)=@_;
2730: my $ua=new LWP::UserAgent;
2731: my $request;
2732:
2733: $form{'no_update_last_known'}=1;
2734: &Apache::lonenc::check_encrypt(\$fn);
2735: if (%form) {
2736: $request=new HTTP::Request('POST',&absolute_url().$fn);
2737: $request->content(join('&',map {
2738: my $name = escape($_);
2739: "$name=" . ( ref($form{$_}) eq 'ARRAY'
2740: ? join("&$name=", map {escape($_) } @{$form{$_}})
2741: : &escape($form{$_}) );
2742: } keys(%form)));
2743: } else {
2744: $request=new HTTP::Request('GET',&absolute_url().$fn);
2745: }
2746:
2747: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2748: my $response= $ua->request($request);
2749: my $content = $response->content;
2750:
2751:
2752: if (wantarray) {
2753: return ($content, $response);
2754: } else {
2755: return $content;
2756: }
2757: }
2758:
2759: sub externalssi {
2760: my ($url)=@_;
2761: my $ua=new LWP::UserAgent;
2762: my $request=new HTTP::Request('GET',$url);
2763: my $response=$ua->request($request);
2764: if (wantarray) {
2765: return ($response->content, $response);
2766: } else {
2767: return $response->content;
2768: }
2769: }
2770:
2771: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2772:
2773: sub allowuploaded {
2774: my ($srcurl,$url)=@_;
2775: $url=&clutter(&declutter($url));
2776: my $dir=$url;
2777: $dir=~s/\/[^\/]+$//;
2778: my %httpref=();
2779: my $httpurl=&hreflocation('',$url);
2780: $httpref{'httpref.'.$httpurl}=$srcurl;
2781: &Apache::lonnet::appenv(\%httpref);
2782: }
2783:
2784: #
2785: # Determine if the current user should be able to edit a particular resource,
2786: # when viewing in course context.
2787: # (a) When viewing resource used to determine if "Edit" item is included in
2788: # Functions.
2789: # (b) When displaying folder contents in course editor, used to determine if
2790: # "Edit" link will be displayed alongside resource.
2791: #
2792: # input: six args -- filename (decluttered), course number, course domain,
2793: # url, symb (if registered) and group (if this is a group
2794: # item -- e.g., bulletin board, group page etc.).
2795: # output: array of five scalars --
2796: # $cfile -- url for file editing if editable on current server
2797: # $home -- homeserver of resource (i.e., for author if published,
2798: # or course if uploaded.).
2799: # $switchserver -- 1 if server switch will be needed.
2800: # $forceedit -- 1 if icon/link should be to go to edit mode
2801: # $forceview -- 1 if icon/link should be to go to view mode
2802: #
2803:
2804: sub can_edit_resource {
2805: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
2806: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
2807: #
2808: # For aboutme pages user can only edit his/her own.
2809: #
2810: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
2811: my ($sdom,$sname) = ($1,$2);
2812: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
2813: $home = $env{'user.home'};
2814: $cfile = $resurl;
2815: if ($env{'form.forceedit'}) {
2816: $forceview = 1;
2817: } else {
2818: $forceedit = 1;
2819: }
2820: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2821: } else {
2822: return;
2823: }
2824: }
2825:
2826: if ($env{'request.course.id'}) {
2827: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
2828: if ($group ne '') {
2829: # if this is a group homepage or group bulletin board, check group privs
2830: my $allowed = 0;
2831: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
2832: if ((&allowed('mdg',$env{'request.course.id'}.
2833: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2834: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2835: $allowed = 1;
2836: }
2837: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
2838: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
2839: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
2840: $allowed = 1;
2841: }
2842: }
2843: if ($allowed) {
2844: $home=&homeserver($cnum,$cdom);
2845: if ($env{'form.forceedit'}) {
2846: $forceview = 1;
2847: } else {
2848: $forceedit = 1;
2849: }
2850: $cfile = $resurl;
2851: } else {
2852: return;
2853: }
2854: } else {
2855: if ($resurl =~ m{^/?adm/viewclasslist$}) {
2856: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
2857: return;
2858: }
2859: } elsif (!$crsedit) {
2860: #
2861: # No edit allowed where CC has switched to student role.
2862: #
2863: return;
2864: }
2865: }
2866: }
2867:
2868: if ($file ne '') {
2869: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
2870: if (&is_course_upload($file,$cnum,$cdom)) {
2871: $uploaded = 1;
2872: $incourse = 1;
2873: if ($file =~/\.(htm|html|css|js|txt)$/) {
2874: $cfile = &hreflocation('',$file);
2875: if ($env{'form.forceedit'}) {
2876: $forceview = 1;
2877: } else {
2878: $forceedit = 1;
2879: }
2880: }
2881: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
2882: $incourse = 1;
2883: if ($env{'form.forceedit'}) {
2884: $forceview = 1;
2885: } else {
2886: $forceedit = 1;
2887: }
2888: $cfile = $resurl;
2889: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
2890: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
2891: $incourse = 1;
2892: if ($env{'form.forceedit'}) {
2893: $forceview = 1;
2894: } else {
2895: $forceedit = 1;
2896: }
2897: $cfile = $resurl;
2898: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
2899: $incourse = 1;
2900: $cfile = $resurl.'/smpedit';
2901: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
2902: $incourse = 1;
2903: if ($env{'form.forceedit'}) {
2904: $forceview = 1;
2905: } else {
2906: $forceedit = 1;
2907: }
2908: $cfile = $resurl;
2909: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2910: $incourse = 1;
2911: if ($env{'form.forceedit'}) {
2912: $forceview = 1;
2913: } else {
2914: $forceedit = 1;
2915: }
2916: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2917: }
2918: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
2919: my $template = '/res/lib/templates/simpleproblem.problem';
2920: if (&is_on_map($template)) {
2921: $incourse = 1;
2922: $forceview = 1;
2923: $cfile = $template;
2924: }
2925: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
2926: $incourse = 1;
2927: if ($env{'form.forceedit'}) {
2928: $forceview = 1;
2929: } else {
2930: $forceedit = 1;
2931: }
2932: $cfile = $resurl;
2933: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
2934: $incourse = 1;
2935: $forceview = 1;
2936: if ($symb) {
2937: my ($map,$id,$res)=&decode_symb($symb);
2938: $env{'request.symb'} = $symb;
2939: $cfile = &clutter($res);
2940: } else {
2941: $cfile = $env{'form.suppurl'};
2942: $cfile =~ s{^http://}{};
2943: $cfile = '/adm/wrapper/ext/'.$cfile;
2944: }
2945: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
2946: if ($env{'form.forceedit'}) {
2947: $forceview = 1;
2948: } else {
2949: $forceedit = 1;
2950: }
2951: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
2952: }
2953: }
2954: if ($uploaded || $incourse) {
2955: $home=&homeserver($cnum,$cdom);
2956: } elsif ($file !~ m{/$}) {
2957: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
2958: $file=~s{^($match_domain/$match_username)}{/priv/$1};
2959: # Check that the user has permission to edit this resource
2960: my $setpriv = 1;
2961: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
2962: if (defined($cfudom)) {
2963: $home=&homeserver($cfuname,$cfudom);
2964: $cfile=$file;
2965: }
2966: }
2967: if (($cfile ne '') && (!$incourse || $uploaded) &&
2968: (($home ne '') && ($home ne 'no_host'))) {
2969: my @ids=¤t_machine_ids();
2970: unless (grep(/^\Q$home\E$/,@ids)) {
2971: $switchserver=1;
2972: }
2973: }
2974: }
2975: return ($cfile,$home,$switchserver,$forceedit,$forceview);
2976: }
2977:
2978: sub is_course_upload {
2979: my ($file,$cnum,$cdom) = @_;
2980: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
2981: $uploadpath =~ s{^\/}{};
2982: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
2983: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
2984: return 1;
2985: }
2986: return;
2987: }
2988:
2989: sub in_course {
2990: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
2991: if ($hideprivileged) {
2992: my $skipuser;
2993: my %coursehash = &coursedescription($cdom.'_'.$cnum);
2994: my @possdoms = ($cdom);
2995: if ($coursehash{'checkforpriv'}) {
2996: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
2997: }
2998: if (&privileged($uname,$udom,\@possdoms)) {
2999: $skipuser = 1;
3000: if ($coursehash{'nothideprivileged'}) {
3001: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3002: my $user;
3003: if ($item =~ /:/) {
3004: $user = $item;
3005: } else {
3006: $user = join(':',split(/[\@]/,$item));
3007: }
3008: if ($user eq $uname.':'.$udom) {
3009: undef($skipuser);
3010: last;
3011: }
3012: }
3013: }
3014: if ($skipuser) {
3015: return 0;
3016: }
3017: }
3018: }
3019: $type ||= 'any';
3020: if (!defined($cdom) || !defined($cnum)) {
3021: my $cid = $env{'request.course.id'};
3022: $cdom = $env{'course.'.$cid.'.domain'};
3023: $cnum = $env{'course.'.$cid.'.num'};
3024: }
3025: my $typesref;
3026: if (($type eq 'any') || ($type eq 'all')) {
3027: $typesref = ['active','previous','future'];
3028: } elsif ($type eq 'previous' || $type eq 'future') {
3029: $typesref = [$type];
3030: }
3031: my %roles = &get_my_roles($uname,$udom,'userroles',
3032: $typesref,undef,[$cdom]);
3033: my ($tmp) = keys(%roles);
3034: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3035: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3036: if (@course_roles > 0) {
3037: return 1;
3038: }
3039: return 0;
3040: }
3041:
3042: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3043: # input: action, courseID, current domain, intended
3044: # path to file, source of file, instruction to parse file for objects,
3045: # ref to hash for embedded objects,
3046: # ref to hash for codebase of java objects.
3047: # reference to scalar to accommodate mime type determined
3048: # from File::MMagic if $parser = parse.
3049: #
3050: # output: url to file (if action was uploaddoc),
3051: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3052: #
3053: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3054: # course.
3055: #
3056: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3057: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3058: # course's home server.
3059: #
3060: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3061: # be copied from $source (current location) to
3062: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3063: # and will then be copied to
3064: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3065: # course's home server.
3066: #
3067: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3068: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3069: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3070: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3071: # in course's home server.
3072: #
3073:
3074: sub process_coursefile {
3075: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3076: $mimetype)=@_;
3077: my $fetchresult;
3078: my $home=&homeserver($docuname,$docudom);
3079: if ($action eq 'propagate') {
3080: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3081: $home);
3082: } else {
3083: my $fpath = '';
3084: my $fname = $file;
3085: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3086: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3087: my $filepath = &build_filepath($fpath);
3088: if ($action eq 'copy') {
3089: if ($source eq '') {
3090: $fetchresult = 'no source file';
3091: return $fetchresult;
3092: } else {
3093: my $destination = $filepath.'/'.$fname;
3094: rename($source,$destination);
3095: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3096: $home);
3097: }
3098: } elsif ($action eq 'uploaddoc') {
3099: open(my $fh,'>'.$filepath.'/'.$fname);
3100: print $fh $env{'form.'.$source};
3101: close($fh);
3102: if ($parser eq 'parse') {
3103: my $mm = new File::MMagic;
3104: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3105: if ($type eq 'text/html') {
3106: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3107: unless ($parse_result eq 'ok') {
3108: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3109: }
3110: }
3111: if (ref($mimetype)) {
3112: $$mimetype = $type;
3113: }
3114: }
3115: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3116: $home);
3117: if ($fetchresult eq 'ok') {
3118: return '/uploaded/'.$fpath.'/'.$fname;
3119: } else {
3120: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3121: ' to host '.$home.': '.$fetchresult);
3122: return '/adm/notfound.html';
3123: }
3124: }
3125: }
3126: unless ( $fetchresult eq 'ok') {
3127: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3128: ' to host '.$home.': '.$fetchresult);
3129: }
3130: return $fetchresult;
3131: }
3132:
3133: sub build_filepath {
3134: my ($fpath) = @_;
3135: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3136: unless ($fpath eq '') {
3137: my @parts=split('/',$fpath);
3138: foreach my $part (@parts) {
3139: $filepath.= '/'.$part;
3140: if ((-e $filepath)!=1) {
3141: mkdir($filepath,0777);
3142: }
3143: }
3144: }
3145: return $filepath;
3146: }
3147:
3148: sub store_edited_file {
3149: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3150: my $file = $primary_url;
3151: $file =~ s#^/uploaded/$docudom/$docuname/##;
3152: my $fpath = '';
3153: my $fname = $file;
3154: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3155: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3156: my $filepath = &build_filepath($fpath);
3157: open(my $fh,'>'.$filepath.'/'.$fname);
3158: print $fh $content;
3159: close($fh);
3160: my $home=&homeserver($docuname,$docudom);
3161: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3162: $home);
3163: if ($$fetchresult eq 'ok') {
3164: return '/uploaded/'.$fpath.'/'.$fname;
3165: } else {
3166: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3167: ' to host '.$home.': '.$$fetchresult);
3168: return '/adm/notfound.html';
3169: }
3170: }
3171:
3172: sub clean_filename {
3173: my ($fname,$args)=@_;
3174: # Replace Windows backslashes by forward slashes
3175: $fname=~s/\\/\//g;
3176: if (!$args->{'keep_path'}) {
3177: # Get rid of everything but the actual filename
3178: $fname=~s/^.*\/([^\/]+)$/$1/;
3179: }
3180: # Replace spaces by underscores
3181: $fname=~s/\s+/\_/g;
3182: # Replace all other weird characters by nothing
3183: $fname=~s{[^/\w\.\-]}{}g;
3184: # Replace all .\d. sequences with _\d. so they no longer look like version
3185: # numbers
3186: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3187: return $fname;
3188: }
3189: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3190: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3191: # image with the same aspect ratio as the original, but with dimensions which do
3192: # not exceed $resizewidth and $resizeheight.
3193:
3194: sub resizeImage {
3195: my ($img_path,$resizewidth,$resizeheight) = @_;
3196: my $ima = Image::Magick->new;
3197: my $resized;
3198: if (-e $img_path) {
3199: $ima->Read($img_path);
3200: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3201: my $width = $ima->Get('width');
3202: my $height = $ima->Get('height');
3203: if ($width > $resizewidth) {
3204: my $factor = $width/$resizewidth;
3205: my $newheight = $height/$factor;
3206: $ima->Scale(width=>$resizewidth,height=>$newheight);
3207: $resized = 1;
3208: }
3209: }
3210: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3211: my $width = $ima->Get('width');
3212: my $height = $ima->Get('height');
3213: if ($height > $resizeheight) {
3214: my $factor = $height/$resizeheight;
3215: my $newwidth = $width/$factor;
3216: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3217: $resized = 1;
3218: }
3219: }
3220: if ($resized) {
3221: $ima->Write($img_path);
3222: }
3223: }
3224: return;
3225: }
3226:
3227: # --------------- Take an uploaded file and put it into the userfiles directory
3228: # input: $formname - the contents of the file are in $env{"form.$formname"}
3229: # the desired filename is in $env{"form.$formname.filename"}
3230: # $context - possible values: coursedoc, existingfile, overwrite,
3231: # canceloverwrite, or ''.
3232: # if 'coursedoc': upload to the current course
3233: # if 'existingfile': write file to tmp/overwrites directory
3234: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3235: # $context is passed as argument to &finishuserfileupload
3236: # $subdir - directory in userfile to store the file into
3237: # $parser - instruction to parse file for objects ($parser = parse)
3238: # $allfiles - reference to hash for embedded objects
3239: # $codebase - reference to hash for codebase of java objects
3240: # $desuname - username for permanent storage of uploaded file
3241: # $dsetudom - domain for permanaent storage of uploaded file
3242: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3243: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3244: # $resizewidth - width (pixels) to which to resize uploaded image
3245: # $resizeheight - height (pixels) to which to resize uploaded image
3246: # $mimetype - reference to scalar to accommodate mime type determined
3247: # from File::MMagic.
3248: #
3249: # output: url of file in userspace, or error: <message>
3250: # or /adm/notfound.html if failure to upload occurse
3251:
3252: sub userfileupload {
3253: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3254: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3255: if (!defined($subdir)) { $subdir='unknown'; }
3256: my $fname=$env{'form.'.$formname.'.filename'};
3257: $fname=&clean_filename($fname);
3258: # See if there is anything left
3259: unless ($fname) { return 'error: no uploaded file'; }
3260: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3261: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3262: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3263: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3264: my $now = time;
3265: my $filepath;
3266: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3267: $filepath = 'tmp/helprequests/'.$now;
3268: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3269: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3270: '_'.$env{'user.domain'}.'/pending';
3271: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3272: my ($docuname,$docudom);
3273: if ($destudom) {
3274: $docudom = $destudom;
3275: } else {
3276: $docudom = $env{'user.domain'};
3277: }
3278: if ($destuname) {
3279: $docuname = $destuname;
3280: } else {
3281: $docuname = $env{'user.name'};
3282: }
3283: if (exists($env{'form.group'})) {
3284: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3285: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3286: }
3287: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3288: if ($context eq 'canceloverwrite') {
3289: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3290: if (-e $tempfile) {
3291: my @info = stat($tempfile);
3292: if ($info[9] eq $env{'form.timestamp'}) {
3293: unlink($tempfile);
3294: }
3295: }
3296: return;
3297: }
3298: }
3299: # Create the directory if not present
3300: my @parts=split(/\//,$filepath);
3301: my $fullpath = $perlvar{'lonDaemons'};
3302: for (my $i=0;$i<@parts;$i++) {
3303: $fullpath .= '/'.$parts[$i];
3304: if ((-e $fullpath)!=1) {
3305: mkdir($fullpath,0777);
3306: }
3307: }
3308: open(my $fh,'>'.$fullpath.'/'.$fname);
3309: print $fh $env{'form.'.$formname};
3310: close($fh);
3311: if ($context eq 'existingfile') {
3312: my @info = stat($fullpath.'/'.$fname);
3313: return ($fullpath.'/'.$fname,$info[9]);
3314: } else {
3315: return $fullpath.'/'.$fname;
3316: }
3317: }
3318: if ($subdir eq 'scantron') {
3319: $fname = 'scantron_orig_'.$fname;
3320: } else {
3321: $fname="$subdir/$fname";
3322: }
3323: if ($context eq 'coursedoc') {
3324: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3325: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3326: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3327: return &finishuserfileupload($docuname,$docudom,
3328: $formname,$fname,$parser,$allfiles,
3329: $codebase,$thumbwidth,$thumbheight,
3330: $resizewidth,$resizeheight,$context,$mimetype);
3331: } else {
3332: if ($env{'form.folder'}) {
3333: $fname=$env{'form.folder'}.'/'.$fname;
3334: }
3335: return &process_coursefile('uploaddoc',$docuname,$docudom,
3336: $fname,$formname,$parser,
3337: $allfiles,$codebase,$mimetype);
3338: }
3339: } elsif (defined($destuname)) {
3340: my $docuname=$destuname;
3341: my $docudom=$destudom;
3342: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3343: $parser,$allfiles,$codebase,
3344: $thumbwidth,$thumbheight,
3345: $resizewidth,$resizeheight,$context,$mimetype);
3346: } else {
3347: my $docuname=$env{'user.name'};
3348: my $docudom=$env{'user.domain'};
3349: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3350: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3351: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3352: }
3353: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3354: $parser,$allfiles,$codebase,
3355: $thumbwidth,$thumbheight,
3356: $resizewidth,$resizeheight,$context,$mimetype);
3357: }
3358: }
3359:
3360: sub finishuserfileupload {
3361: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3362: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3363: my $path=$docudom.'/'.$docuname.'/';
3364: my $filepath=$perlvar{'lonDocRoot'};
3365:
3366: my ($fnamepath,$file,$fetchthumb);
3367: $file=$fname;
3368: if ($fname=~m|/|) {
3369: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3370: $path.=$fnamepath.'/';
3371: }
3372: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3373: my $count;
3374: for ($count=4;$count<=$#parts;$count++) {
3375: $filepath.="/$parts[$count]";
3376: if ((-e $filepath)!=1) {
3377: mkdir($filepath,0777);
3378: }
3379: }
3380:
3381: # Save the file
3382: {
3383: if (!open(FH,'>'.$filepath.'/'.$file)) {
3384: &logthis('Failed to create '.$filepath.'/'.$file);
3385: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3386: return '/adm/notfound.html';
3387: }
3388: if ($context eq 'overwrite') {
3389: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3390: my $target = $filepath.'/'.$file;
3391: if (-e $source) {
3392: my @info = stat($source);
3393: if ($info[9] eq $env{'form.timestamp'}) {
3394: unless (&File::Copy::move($source,$target)) {
3395: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3396: return "Moving from $source failed";
3397: }
3398: } else {
3399: return "Temporary file: $source had unexpected date/time for last modification";
3400: }
3401: } else {
3402: return "Temporary file: $source missing";
3403: }
3404: } elsif (!print FH ($env{'form.'.$formname})) {
3405: &logthis('Failed to write to '.$filepath.'/'.$file);
3406: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3407: return '/adm/notfound.html';
3408: }
3409: close(FH);
3410: if ($resizewidth && $resizeheight) {
3411: my $mm = new File::MMagic;
3412: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3413: if ($mime_type =~ m{^image/}) {
3414: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3415: }
3416: }
3417: }
3418: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3419: if (ref($mimetype)) {
3420: if ($$mimetype eq '') {
3421: my $mm = new File::MMagic;
3422: my $type = $mm->checktype_filename($filepath.'/'.$file);
3423: $$mimetype = $type;
3424: }
3425: }
3426: }
3427: if ($parser eq 'parse') {
3428: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3429: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3430: $allfiles,$codebase);
3431: unless ($parse_result eq 'ok') {
3432: &logthis('Failed to parse '.$filepath.$file.
3433: ' for embedded media: '.$parse_result);
3434: }
3435: }
3436: }
3437: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3438: my $input = $filepath.'/'.$file;
3439: my $output = $filepath.'/'.'tn-'.$file;
3440: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3441: system("convert -sample $thumbsize $input $output");
3442: if (-e $filepath.'/'.'tn-'.$file) {
3443: $fetchthumb = 1;
3444: }
3445: }
3446:
3447: # Notify homeserver to grep it
3448: #
3449: my $docuhome=&homeserver($docuname,$docudom);
3450: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3451: if ($fetchresult eq 'ok') {
3452: if ($fetchthumb) {
3453: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3454: if ($thumbresult ne 'ok') {
3455: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3456: $docuhome.': '.$thumbresult);
3457: }
3458: }
3459: #
3460: # Return the URL to it
3461: return '/uploaded/'.$path.$file;
3462: } else {
3463: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3464: ': '.$fetchresult);
3465: return '/adm/notfound.html';
3466: }
3467: }
3468:
3469: sub extract_embedded_items {
3470: my ($fullpath,$allfiles,$codebase,$content) = @_;
3471: my @state = ();
3472: my (%lastids,%related,%shockwave,%flashvars);
3473: my %javafiles = (
3474: codebase => '',
3475: code => '',
3476: archive => ''
3477: );
3478: my %mediafiles = (
3479: src => '',
3480: movie => '',
3481: );
3482: my $p;
3483: if ($content) {
3484: $p = HTML::LCParser->new($content);
3485: } else {
3486: $p = HTML::LCParser->new($fullpath);
3487: }
3488: while (my $t=$p->get_token()) {
3489: if ($t->[0] eq 'S') {
3490: my ($tagname, $attr) = ($t->[1],$t->[2]);
3491: push(@state, $tagname);
3492: if (lc($tagname) eq 'allow') {
3493: &add_filetype($allfiles,$attr->{'src'},'src');
3494: }
3495: if (lc($tagname) eq 'img') {
3496: &add_filetype($allfiles,$attr->{'src'},'src');
3497: }
3498: if (lc($tagname) eq 'a') {
3499: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
3500: &add_filetype($allfiles,$attr->{'href'},'href');
3501: }
3502: }
3503: if (lc($tagname) eq 'script') {
3504: my $src;
3505: if ($attr->{'archive'} =~ /\.jar$/i) {
3506: &add_filetype($allfiles,$attr->{'archive'},'archive');
3507: } else {
3508: if ($attr->{'src'} ne '') {
3509: $src = $attr->{'src'};
3510: &add_filetype($allfiles,$src,'src');
3511: }
3512: }
3513: my $text = $p->get_trimmed_text();
3514: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3515: my @swfargs = split(/,/,$1);
3516: foreach my $item (@swfargs) {
3517: $item =~ s/["']//g;
3518: $item =~ s/^\s+//;
3519: $item =~ s/\s+$//;
3520: }
3521: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3522: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3523: push(@{$related{$swfargs[0]}},$swfargs[2]);
3524: } else {
3525: $related{$swfargs[0]} = [$swfargs[2]];
3526: }
3527: }
3528: }
3529: }
3530: if (lc($tagname) eq 'link') {
3531: if (lc($attr->{'rel'}) eq 'stylesheet') {
3532: &add_filetype($allfiles,$attr->{'href'},'href');
3533: }
3534: }
3535: if (lc($tagname) eq 'object' ||
3536: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3537: foreach my $item (keys(%javafiles)) {
3538: $javafiles{$item} = '';
3539: }
3540: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3541: $lastids{lc($tagname)} = $attr->{'id'};
3542: }
3543: }
3544: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3545: my $name = lc($attr->{'name'});
3546: foreach my $item (keys(%javafiles)) {
3547: if ($name eq $item) {
3548: $javafiles{$item} = $attr->{'value'};
3549: last;
3550: }
3551: }
3552: my $pathfrom;
3553: foreach my $item (keys(%mediafiles)) {
3554: if ($name eq $item) {
3555: $pathfrom = $attr->{'value'};
3556: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3557: &add_filetype($allfiles,$pathfrom,$name);
3558: last;
3559: }
3560: }
3561: if ($name eq 'flashvars') {
3562: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3563: }
3564: if ($pathfrom ne '') {
3565: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3566: $pathfrom);
3567: }
3568: }
3569: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3570: foreach my $item (keys(%javafiles)) {
3571: if ($attr->{$item}) {
3572: $javafiles{$item} = $attr->{$item};
3573: last;
3574: }
3575: }
3576: foreach my $item (keys(%mediafiles)) {
3577: if ($attr->{$item}) {
3578: &add_filetype($allfiles,$attr->{$item},$item);
3579: last;
3580: }
3581: }
3582: if (lc($tagname) eq 'embed') {
3583: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3584: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3585: $attr->{'src'});
3586: }
3587: }
3588: }
3589: if (lc($tagname) eq 'iframe') {
3590: my $src = $attr->{'src'} ;
3591: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
3592: &add_filetype($allfiles,$src,'src');
3593: } elsif ($src =~ m{^/}) {
3594: if ($env{'request.course.id'}) {
3595: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
3596: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
3597: my $url = &hreflocation('',$fullpath);
3598: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
3599: my $relpath = $1;
3600: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
3601: &add_filetype($allfiles,$1,'src');
3602: }
3603: }
3604: }
3605: }
3606: }
3607: if ($t->[4] =~ m{/>$}) {
3608: pop(@state);
3609: }
3610: } elsif ($t->[0] eq 'E') {
3611: my ($tagname) = ($t->[1]);
3612: if ($javafiles{'codebase'} ne '') {
3613: $javafiles{'codebase'} .= '/';
3614: }
3615: if (lc($tagname) eq 'applet' ||
3616: lc($tagname) eq 'object' ||
3617: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3618: ) {
3619: foreach my $item (keys(%javafiles)) {
3620: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3621: my $file=$javafiles{'codebase'}.$javafiles{$item};
3622: &add_filetype($allfiles,$file,$item);
3623: }
3624: }
3625: }
3626: pop @state;
3627: }
3628: }
3629: foreach my $id (sort(keys(%flashvars))) {
3630: if ($shockwave{$id} ne '') {
3631: my @pairs = split(/\&/,$flashvars{$id});
3632: foreach my $pair (@pairs) {
3633: my ($key,$value) = split(/\=/,$pair);
3634: if ($key eq 'thumb') {
3635: &add_filetype($allfiles,$value,$key);
3636: } elsif ($key eq 'content') {
3637: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3638: my ($ext) = ($value =~ /\.([^.]+)$/);
3639: if ($ext ne '') {
3640: &add_filetype($allfiles,$path.$value,$ext);
3641: }
3642: }
3643: }
3644: }
3645: }
3646: return 'ok';
3647: }
3648:
3649: sub add_filetype {
3650: my ($allfiles,$file,$type)=@_;
3651: if (exists($allfiles->{$file})) {
3652: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3653: push(@{$allfiles->{$file}}, &escape($type));
3654: }
3655: } else {
3656: @{$allfiles->{$file}} = (&escape($type));
3657: }
3658: }
3659:
3660: sub embedded_dependency {
3661: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3662: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3663: if (($identifier ne '') &&
3664: (ref($related->{$identifier}) eq 'ARRAY') &&
3665: ($pathfrom ne '')) {
3666: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3667: foreach my $dep (@{$related->{$identifier}}) {
3668: &add_filetype($allfiles,$path.$dep,'object');
3669: }
3670: }
3671: }
3672: return;
3673: }
3674:
3675: sub removeuploadedurl {
3676: my ($url)=@_;
3677: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3678: return &removeuserfile($uname,$udom,$fname);
3679: }
3680:
3681: sub removeuserfile {
3682: my ($docuname,$docudom,$fname)=@_;
3683: my $home=&homeserver($docuname,$docudom);
3684: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3685: if ($result eq 'ok') {
3686: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3687: my $metafile = $fname.'.meta';
3688: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3689: my $url = "/uploaded/$docudom/$docuname/$fname";
3690: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3691: my $sqlresult =
3692: &update_portfolio_table($docuname,$docudom,$file,
3693: 'portfolio_metadata',$group,
3694: 'delete');
3695: }
3696: }
3697: return $result;
3698: }
3699:
3700: sub mkdiruserfile {
3701: my ($docuname,$docudom,$dir)=@_;
3702: my $home=&homeserver($docuname,$docudom);
3703: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3704: }
3705:
3706: sub renameuserfile {
3707: my ($docuname,$docudom,$old,$new)=@_;
3708: my $home=&homeserver($docuname,$docudom);
3709: my $result = &reply("renameuserfile:$docudom:$docuname:".
3710: &escape("$old").':'.&escape("$new"),$home);
3711: if ($result eq 'ok') {
3712: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3713: my $oldmeta = $old.'.meta';
3714: my $newmeta = $new.'.meta';
3715: my $metaresult =
3716: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3717: my $url = "/uploaded/$docudom/$docuname/$old";
3718: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3719: my $sqlresult =
3720: &update_portfolio_table($docuname,$docudom,$file,
3721: 'portfolio_metadata',$group,
3722: 'delete');
3723: }
3724: }
3725: return $result;
3726: }
3727:
3728: # ------------------------------------------------------------------------- Log
3729:
3730: sub log {
3731: my ($dom,$nam,$hom,$what)=@_;
3732: return critical("log:$dom:$nam:$what",$hom);
3733: }
3734:
3735: # ------------------------------------------------------------------ Course Log
3736: #
3737: # This routine flushes several buffers of non-mission-critical nature
3738: #
3739:
3740: sub flushcourselogs {
3741: &logthis('Flushing log buffers');
3742: #
3743: # course logs
3744: # This is a log of all transactions in a course, which can be used
3745: # for data mining purposes
3746: #
3747: # It also collects the courseid database, which lists last transaction
3748: # times and course titles for all courseids
3749: #
3750: my %courseidbuffer=();
3751: foreach my $crsid (keys(%courselogs)) {
3752: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3753: &escape($courselogs{$crsid}),
3754: $coursehombuf{$crsid}) eq 'ok') {
3755: delete $courselogs{$crsid};
3756: } else {
3757: &logthis('Failed to flush log buffer for '.$crsid);
3758: if (length($courselogs{$crsid})>40000) {
3759: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3760: " exceeded maximum size, deleting.</font>");
3761: delete $courselogs{$crsid};
3762: }
3763: }
3764: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3765: 'description' => $coursedescrbuf{$crsid},
3766: 'inst_code' => $courseinstcodebuf{$crsid},
3767: 'type' => $coursetypebuf{$crsid},
3768: 'owner' => $courseownerbuf{$crsid},
3769: };
3770: }
3771: #
3772: # Write course id database (reverse lookup) to homeserver of courses
3773: # Is used in pickcourse
3774: #
3775: foreach my $crs_home (keys(%courseidbuffer)) {
3776: my $response = &courseidput(&host_domain($crs_home),
3777: $courseidbuffer{$crs_home},
3778: $crs_home,'timeonly');
3779: }
3780: #
3781: # File accesses
3782: # Writes to the dynamic metadata of resources to get hit counts, etc.
3783: #
3784: foreach my $entry (keys(%accesshash)) {
3785: if ($entry =~ /___count$/) {
3786: my ($dom,$name);
3787: ($dom,$name,undef)=
3788: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3789: if (! defined($dom) || $dom eq '' ||
3790: ! defined($name) || $name eq '') {
3791: my $cid = $env{'request.course.id'};
3792: $dom = $env{'request.'.$cid.'.domain'};
3793: $name = $env{'request.'.$cid.'.num'};
3794: }
3795: my $value = $accesshash{$entry};
3796: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3797: my %temphash=($url => $value);
3798: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3799: if ($result eq 'ok') {
3800: delete $accesshash{$entry};
3801: }
3802: } else {
3803: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3804: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3805: my %temphash=($entry => $accesshash{$entry});
3806: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3807: delete $accesshash{$entry};
3808: }
3809: }
3810: }
3811: #
3812: # Roles
3813: # Reverse lookup of user roles for course faculty/staff and co-authorship
3814: #
3815: foreach my $entry (keys(%userrolehash)) {
3816: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3817: split(/\:/,$entry);
3818: if (&Apache::lonnet::put('nohist_userroles',
3819: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3820: $rudom,$runame) eq 'ok') {
3821: delete $userrolehash{$entry};
3822: }
3823: }
3824: #
3825: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3826: #
3827: my %domrolebuffer = ();
3828: foreach my $entry (keys(%domainrolehash)) {
3829: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3830: if ($domrolebuffer{$rudom}) {
3831: $domrolebuffer{$rudom}.='&'.&escape($entry).
3832: '='.&escape($domainrolehash{$entry});
3833: } else {
3834: $domrolebuffer{$rudom}.=&escape($entry).
3835: '='.&escape($domainrolehash{$entry});
3836: }
3837: delete $domainrolehash{$entry};
3838: }
3839: foreach my $dom (keys(%domrolebuffer)) {
3840: my %servers = &get_servers($dom,'library');
3841: foreach my $tryserver (keys(%servers)) {
3842: unless (&reply('domroleput:'.$dom.':'.
3843: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3844: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3845: }
3846: }
3847: }
3848: $dumpcount++;
3849: }
3850:
3851: sub courselog {
3852: my $what=shift;
3853: $what=time.':'.$what;
3854: unless ($env{'request.course.id'}) { return ''; }
3855: $coursedombuf{$env{'request.course.id'}}=
3856: $env{'course.'.$env{'request.course.id'}.'.domain'};
3857: $coursenumbuf{$env{'request.course.id'}}=
3858: $env{'course.'.$env{'request.course.id'}.'.num'};
3859: $coursehombuf{$env{'request.course.id'}}=
3860: $env{'course.'.$env{'request.course.id'}.'.home'};
3861: $coursedescrbuf{$env{'request.course.id'}}=
3862: $env{'course.'.$env{'request.course.id'}.'.description'};
3863: $courseinstcodebuf{$env{'request.course.id'}}=
3864: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3865: $courseownerbuf{$env{'request.course.id'}}=
3866: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3867: $coursetypebuf{$env{'request.course.id'}}=
3868: $env{'course.'.$env{'request.course.id'}.'.type'};
3869: if (defined $courselogs{$env{'request.course.id'}}) {
3870: $courselogs{$env{'request.course.id'}}.='&'.$what;
3871: } else {
3872: $courselogs{$env{'request.course.id'}}.=$what;
3873: }
3874: if (length($courselogs{$env{'request.course.id'}})>4048) {
3875: &flushcourselogs();
3876: }
3877: }
3878:
3879: sub courseacclog {
3880: my $fnsymb=shift;
3881: unless ($env{'request.course.id'}) { return ''; }
3882: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3883: if ($fnsymb=~/$LONCAPA::assess_re/) {
3884: $what.=':POST';
3885: # FIXME: Probably ought to escape things....
3886: foreach my $key (keys(%env)) {
3887: if ($key=~/^form\.(.*)/) {
3888: my $formitem = $1;
3889: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3890: $what.=':'.$formitem.'='.$env{$key};
3891: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3892: $what.=':'.$formitem.'='.$env{$key};
3893: }
3894: }
3895: }
3896: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3897: # FIXME: We should not be depending on a form parameter that someone
3898: # editing lonsearchcat.pm might change in the future.
3899: if ($env{'form.phase'} eq 'course_search') {
3900: $what.= ':POST';
3901: # FIXME: Probably ought to escape things....
3902: foreach my $element ('courseexp','crsfulltext','crsrelated',
3903: 'crsdiscuss') {
3904: $what.=':'.$element.'='.$env{'form.'.$element};
3905: }
3906: }
3907: }
3908: &courselog($what);
3909: }
3910:
3911: sub countacc {
3912: my $url=&declutter(shift);
3913: return if (! defined($url) || $url eq '');
3914: unless ($env{'request.course.id'}) { return ''; }
3915: #
3916: # Mark that this url was used in this course
3917: #
3918: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3919: #
3920: # Increase the access count for this resource in this child process
3921: #
3922: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3923: $accesshash{$key}++;
3924: }
3925:
3926: sub linklog {
3927: my ($from,$to)=@_;
3928: $from=&declutter($from);
3929: $to=&declutter($to);
3930: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3931: $accesshash{$to.'___'.$from.'___goto'}=1;
3932: }
3933:
3934: sub statslog {
3935: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3936: if ($users<2) { return; }
3937: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3938: 'course' => $env{'request.course.id'},
3939: 'sections' => '"all"',
3940: 'num_students' => $users,
3941: 'part' => $part,
3942: 'symb' => $symb,
3943: 'mean_tries' => $av_attempts,
3944: 'deg_of_diff' => $degdiff});
3945: foreach my $key (keys(%dynstore)) {
3946: $accesshash{$key}=$dynstore{$key};
3947: }
3948: }
3949:
3950: sub userrolelog {
3951: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3952: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
3953: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3954: $userrolehash
3955: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3956: =$tend.':'.$tstart;
3957: }
3958: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
3959: $userrolehash
3960: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3961: =$tend.':'.$tstart;
3962: }
3963: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
3964: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3965: $domainrolehash
3966: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3967: = $tend.':'.$tstart;
3968: }
3969: }
3970:
3971: sub courserolelog {
3972: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3973: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3974: my $cdom = $1;
3975: my $cnum = $2;
3976: my $sec = $3;
3977: my $namespace = 'rolelog';
3978: my %storehash = (
3979: role => $trole,
3980: start => $tstart,
3981: end => $tend,
3982: selfenroll => $selfenroll,
3983: context => $context,
3984: );
3985: if ($trole eq 'gr') {
3986: $namespace = 'groupslog';
3987: $storehash{'group'} = $sec;
3988: } else {
3989: $storehash{'section'} = $sec;
3990: }
3991: &write_log('course',$namespace,\%storehash,$delflag,$username,
3992: $domain,$cnum,$cdom);
3993: if (($trole ne 'st') || ($sec ne '')) {
3994: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3995: }
3996: }
3997: return;
3998: }
3999:
4000: sub domainrolelog {
4001: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4002: if ($area =~ m{^/($match_domain)/$}) {
4003: my $cdom = $1;
4004: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4005: my $namespace = 'rolelog';
4006: my %storehash = (
4007: role => $trole,
4008: start => $tstart,
4009: end => $tend,
4010: context => $context,
4011: );
4012: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4013: $domain,$domconfiguser,$cdom);
4014: }
4015: return;
4016:
4017: }
4018:
4019: sub coauthorrolelog {
4020: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4021: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4022: my $audom = $1;
4023: my $auname = $2;
4024: my $namespace = 'rolelog';
4025: my %storehash = (
4026: role => $trole,
4027: start => $tstart,
4028: end => $tend,
4029: context => $context,
4030: );
4031: &write_log('author',$namespace,\%storehash,$delflag,$username,
4032: $domain,$auname,$audom);
4033: }
4034: return;
4035: }
4036:
4037: sub get_course_adv_roles {
4038: my ($cid,$codes) = @_;
4039: $cid=$env{'request.course.id'} unless (defined($cid));
4040: my %coursehash=&coursedescription($cid);
4041: my $crstype = &Apache::loncommon::course_type($cid);
4042: my %nothide=();
4043: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4044: if ($user !~ /:/) {
4045: $nothide{join(':',split(/[\@]/,$user))}=1;
4046: } else {
4047: $nothide{$user}=1;
4048: }
4049: }
4050: my @possdoms = ($coursehash{'domain'});
4051: if ($coursehash{'checkforpriv'}) {
4052: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4053: }
4054: my %returnhash=();
4055: my %dumphash=
4056: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4057: my $now=time;
4058: my %privileged;
4059: foreach my $entry (keys(%dumphash)) {
4060: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4061: if (($tstart) && ($tstart<0)) { next; }
4062: if (($tend) && ($tend<$now)) { next; }
4063: if (($tstart) && ($now<$tstart)) { next; }
4064: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4065: if ($username eq '' || $domain eq '') { next; }
4066: if ((&privileged($username,$domain,\@possdoms)) &&
4067: (!$nothide{$username.':'.$domain})) { next; }
4068: if ($role eq 'cr') { next; }
4069: if ($codes) {
4070: if ($section) { $role .= ':'.$section; }
4071: if ($returnhash{$role}) {
4072: $returnhash{$role}.=','.$username.':'.$domain;
4073: } else {
4074: $returnhash{$role}=$username.':'.$domain;
4075: }
4076: } else {
4077: my $key=&plaintext($role,$crstype);
4078: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4079: if ($returnhash{$key}) {
4080: $returnhash{$key}.=','.$username.':'.$domain;
4081: } else {
4082: $returnhash{$key}=$username.':'.$domain;
4083: }
4084: }
4085: }
4086: return %returnhash;
4087: }
4088:
4089: sub get_my_roles {
4090: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4091: unless (defined($uname)) { $uname=$env{'user.name'}; }
4092: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4093: my (%dumphash,%nothide);
4094: if ($context eq 'userroles') {
4095: %dumphash = &dump('roles',$udom,$uname);
4096: } else {
4097: %dumphash = &dump('nohist_userroles',$udom,$uname);
4098: if ($hidepriv) {
4099: my %coursehash=&coursedescription($udom.'_'.$uname);
4100: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4101: if ($user !~ /:/) {
4102: $nothide{join(':',split(/[\@]/,$user))} = 1;
4103: } else {
4104: $nothide{$user} = 1;
4105: }
4106: }
4107: }
4108: }
4109: my %returnhash=();
4110: my $now=time;
4111: my %privileged;
4112: foreach my $entry (keys(%dumphash)) {
4113: my ($role,$tend,$tstart);
4114: if ($context eq 'userroles') {
4115: next if ($entry =~ /^rolesdef/);
4116: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4117: } else {
4118: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4119: }
4120: if (($tstart) && ($tstart<0)) { next; }
4121: my $status = 'active';
4122: if (($tend) && ($tend<=$now)) {
4123: $status = 'previous';
4124: }
4125: if (($tstart) && ($now<$tstart)) {
4126: $status = 'future';
4127: }
4128: if (ref($types) eq 'ARRAY') {
4129: if (!grep(/^\Q$status\E$/,@{$types})) {
4130: next;
4131: }
4132: } else {
4133: if ($status ne 'active') {
4134: next;
4135: }
4136: }
4137: my ($rolecode,$username,$domain,$section,$area);
4138: if ($context eq 'userroles') {
4139: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4140: (undef,$domain,$username,$section) = split(/\//,$area);
4141: } else {
4142: ($role,$username,$domain,$section) = split(/\:/,$entry);
4143: }
4144: if (ref($roledoms) eq 'ARRAY') {
4145: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4146: next;
4147: }
4148: }
4149: if (ref($roles) eq 'ARRAY') {
4150: if (!grep(/^\Q$role\E$/,@{$roles})) {
4151: if ($role =~ /^cr\//) {
4152: if (!grep(/^cr$/,@{$roles})) {
4153: next;
4154: }
4155: } elsif ($role =~ /^gr\//) {
4156: if (!grep(/^gr$/,@{$roles})) {
4157: next;
4158: }
4159: } else {
4160: next;
4161: }
4162: }
4163: }
4164: if ($hidepriv) {
4165: my @privroles = ('dc','su');
4166: if ($context eq 'userroles') {
4167: next if (grep(/^\Q$role\E$/,@privroles));
4168: } else {
4169: my $possdoms = [$domain];
4170: if (ref($roledoms) eq 'ARRAY') {
4171: push(@{$possdoms},@{$roledoms});
4172: }
4173: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4174: if (!$nothide{$username.':'.$domain}) {
4175: next;
4176: }
4177: }
4178: }
4179: }
4180: if ($withsec) {
4181: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4182: $tstart.':'.$tend;
4183: } else {
4184: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4185: }
4186: }
4187: return %returnhash;
4188: }
4189:
4190: # ----------------------------------------------------- Frontpage Announcements
4191: #
4192: #
4193:
4194: sub postannounce {
4195: my ($server,$text)=@_;
4196: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
4197: unless ($text=~/\w/) { $text=''; }
4198: return &reply('setannounce:'.&escape($text),$server);
4199: }
4200:
4201: sub getannounce {
4202:
4203: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
4204: my $announcement='';
4205: while (my $line = <$fh>) { $announcement .= $line; }
4206: close($fh);
4207: if ($announcement=~/\w/) {
4208: return
4209: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
4210: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
4211: } else {
4212: return '';
4213: }
4214: } else {
4215: return '';
4216: }
4217: }
4218:
4219: # ---------------------------------------------------------- Course ID routines
4220: # Deal with domain's nohist_courseid.db files
4221: #
4222:
4223: sub courseidput {
4224: my ($domain,$storehash,$coursehome,$caller) = @_;
4225: return unless (ref($storehash) eq 'HASH');
4226: my $outcome;
4227: if ($caller eq 'timeonly') {
4228: my $cids = '';
4229: foreach my $item (keys(%$storehash)) {
4230: $cids.=&escape($item).'&';
4231: }
4232: $cids=~s/\&$//;
4233: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
4234: $coursehome);
4235: } else {
4236: my $items = '';
4237: foreach my $item (keys(%$storehash)) {
4238: $items.= &escape($item).'='.
4239: &freeze_escape($$storehash{$item}).'&';
4240: }
4241: $items=~s/\&$//;
4242: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
4243: $coursehome);
4244: }
4245: if ($outcome eq 'unknown_cmd') {
4246: my $what;
4247: foreach my $cid (keys(%$storehash)) {
4248: $what .= &escape($cid).'=';
4249: foreach my $item ('description','inst_code','owner','type') {
4250: $what .= &escape($storehash->{$cid}{$item}).':';
4251: }
4252: $what =~ s/\:$/&/;
4253: }
4254: $what =~ s/\&$//;
4255: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
4256: } else {
4257: return $outcome;
4258: }
4259: }
4260:
4261: sub courseiddump {
4262: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
4263: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
4264: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
4265: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
4266: $hasuniquecode)=@_;
4267: my $as_hash = 1;
4268: my %returnhash;
4269: if (!$domfilter) { $domfilter=''; }
4270: my %libserv = &all_library();
4271: foreach my $tryserver (keys(%libserv)) {
4272: if ( ( $hostidflag == 1
4273: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
4274: || (!defined($hostidflag)) ) {
4275:
4276: if (($domfilter eq '') ||
4277: (&host_domain($tryserver) eq $domfilter)) {
4278: my $rep;
4279: if (grep { $_ eq $tryserver } current_machine_ids()) {
4280: $rep = LONCAPA::Lond::dump_course_id_handler(
4281: join(":", (&host_domain($tryserver), $sincefilter,
4282: &escape($descfilter), &escape($instcodefilter),
4283: &escape($ownerfilter), &escape($coursefilter),
4284: &escape($typefilter), &escape($regexp_ok),
4285: $as_hash, &escape($selfenrollonly),
4286: &escape($catfilter), $showhidden, $caller,
4287: &escape($cloner), &escape($cc_clone), $cloneonly,
4288: &escape($createdbefore), &escape($createdafter),
4289: &escape($creationcontext), $domcloner, $hasuniquecode)));
4290: } else {
4291: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
4292: $sincefilter.':'.&escape($descfilter).':'.
4293: &escape($instcodefilter).':'.&escape($ownerfilter).
4294: ':'.&escape($coursefilter).':'.&escape($typefilter).
4295: ':'.&escape($regexp_ok).':'.$as_hash.':'.
4296: &escape($selfenrollonly).':'.&escape($catfilter).':'.
4297: $showhidden.':'.$caller.':'.&escape($cloner).':'.
4298: &escape($cc_clone).':'.$cloneonly.':'.
4299: &escape($createdbefore).':'.&escape($createdafter).':'.
4300: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode,
4301: $tryserver);
4302: }
4303:
4304: my @pairs=split(/\&/,$rep);
4305: foreach my $item (@pairs) {
4306: my ($key,$value)=split(/\=/,$item,2);
4307: $key = &unescape($key);
4308: next if ($key =~ /^error: 2 /);
4309: my $result = &thaw_unescape($value);
4310: if (ref($result) eq 'HASH') {
4311: $returnhash{$key}=$result;
4312: } else {
4313: my @responses = split(/:/,$value);
4314: my @items = ('description','inst_code','owner','type');
4315: for (my $i=0; $i<@responses; $i++) {
4316: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
4317: }
4318: }
4319: }
4320: }
4321: }
4322: }
4323: return %returnhash;
4324: }
4325:
4326: sub courselastaccess {
4327: my ($cdom,$cnum,$hostidref) = @_;
4328: my %returnhash;
4329: if ($cdom && $cnum) {
4330: my $chome = &homeserver($cnum,$cdom);
4331: if ($chome ne 'no_host') {
4332: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
4333: &extract_lastaccess(\%returnhash,$rep);
4334: }
4335: } else {
4336: if (!$cdom) { $cdom=''; }
4337: my %libserv = &all_library();
4338: foreach my $tryserver (keys(%libserv)) {
4339: if (ref($hostidref) eq 'ARRAY') {
4340: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
4341: }
4342: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
4343: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
4344: &extract_lastaccess(\%returnhash,$rep);
4345: }
4346: }
4347: }
4348: return %returnhash;
4349: }
4350:
4351: sub extract_lastaccess {
4352: my ($returnhash,$rep) = @_;
4353: if (ref($returnhash) eq 'HASH') {
4354: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
4355: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
4356: $rep eq '') {
4357: my @pairs=split(/\&/,$rep);
4358: foreach my $item (@pairs) {
4359: my ($key,$value)=split(/\=/,$item,2);
4360: $key = &unescape($key);
4361: next if ($key =~ /^error: 2 /);
4362: $returnhash->{$key} = &thaw_unescape($value);
4363: }
4364: }
4365: }
4366: return;
4367: }
4368:
4369: # ---------------------------------------------------------- DC e-mail
4370:
4371: sub dcmailput {
4372: my ($domain,$msgid,$message,$server)=@_;
4373: my $status = &Apache::lonnet::critical(
4374: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
4375: &escape($message),$server);
4376: return $status;
4377: }
4378:
4379: sub dcmaildump {
4380: my ($dom,$startdate,$enddate,$senders) = @_;
4381: my %returnhash=();
4382:
4383: if (defined(&domain($dom,'primary'))) {
4384: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
4385: &escape($enddate).':';
4386: my @esc_senders=map { &escape($_)} @$senders;
4387: $cmd.=&escape(join('&',@esc_senders));
4388: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
4389: my ($key,$value) = split(/\=/,$line,2);
4390: if (($key) && ($value)) {
4391: $returnhash{&unescape($key)} = &unescape($value);
4392: }
4393: }
4394: }
4395: return %returnhash;
4396: }
4397: # ---------------------------------------------------------- Domain roles
4398:
4399: sub get_domain_roles {
4400: my ($dom,$roles,$startdate,$enddate)=@_;
4401: if ((!defined($startdate)) || ($startdate eq '')) {
4402: $startdate = '.';
4403: }
4404: if ((!defined($enddate)) || ($enddate eq '')) {
4405: $enddate = '.';
4406: }
4407: my $rolelist;
4408: if (ref($roles) eq 'ARRAY') {
4409: $rolelist = join('&',@{$roles});
4410: }
4411: my %personnel = ();
4412:
4413: my %servers = &get_servers($dom,'library');
4414: foreach my $tryserver (keys(%servers)) {
4415: %{$personnel{$tryserver}}=();
4416: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
4417: &escape($startdate).':'.
4418: &escape($enddate).':'.
4419: &escape($rolelist), $tryserver))) {
4420: my ($key,$value) = split(/\=/,$line,2);
4421: if (($key) && ($value)) {
4422: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
4423: }
4424: }
4425: }
4426: return %personnel;
4427: }
4428:
4429: # ----------------------------------------------------------- Interval timing
4430:
4431: {
4432: # Caches needed for speedup of navmaps
4433: # We don't want to cache this for very long at all (5 seconds at most)
4434: #
4435: # The user for whom we cache
4436: my $cachedkey='';
4437: # The cached times for this user
4438: my %cachedtimes=();
4439: # When this was last done
4440: my $cachedtime=();
4441:
4442: sub load_all_first_access {
4443: my ($uname,$udom)=@_;
4444: if (($cachedkey eq $uname.':'.$udom) &&
4445: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
4446: return;
4447: }
4448: $cachedtime=time;
4449: $cachedkey=$uname.':'.$udom;
4450: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
4451: }
4452:
4453: sub get_first_access {
4454: my ($type,$argsymb,$argmap)=@_;
4455: my ($symb,$courseid,$udom,$uname)=&whichuser();
4456: if ($argsymb) { $symb=$argsymb; }
4457: my ($map,$id,$res)=&decode_symb($symb);
4458: if ($argmap) { $map = $argmap; }
4459: if ($type eq 'course') {
4460: $res='course';
4461: } elsif ($type eq 'map') {
4462: $res=&symbread($map);
4463: } else {
4464: $res=$symb;
4465: }
4466: &load_all_first_access($uname,$udom);
4467: return $cachedtimes{"$courseid\0$res"};
4468: }
4469:
4470: sub set_first_access {
4471: my ($type,$interval)=@_;
4472: my ($symb,$courseid,$udom,$uname)=&whichuser();
4473: my ($map,$id,$res)=&decode_symb($symb);
4474: if ($type eq 'course') {
4475: $res='course';
4476: } elsif ($type eq 'map') {
4477: $res=&symbread($map);
4478: } else {
4479: $res=$symb;
4480: }
4481: $cachedkey='';
4482: my $firstaccess=&get_first_access($type,$symb,$map);
4483: if (!$firstaccess) {
4484: my $start = time;
4485: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4486: $udom,$uname);
4487: if ($putres eq 'ok') {
4488: &put('timerinterval',{"$courseid\0$res"=>$interval},
4489: $udom,$uname);
4490: &appenv(
4491: {
4492: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4493: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4494: }
4495: );
4496: }
4497: return $putres;
4498: }
4499: return 'already_set';
4500: }
4501: }
4502: # --------------------------------------------- Set Expire Date for Spreadsheet
4503:
4504: sub expirespread {
4505: my ($uname,$udom,$stype,$usymb)=@_;
4506: my $cid=$env{'request.course.id'};
4507: if ($cid) {
4508: my $now=time;
4509: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4510: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4511: $env{'course.'.$cid.'.num'}.
4512: ':nohist_expirationdates:'.
4513: &escape($key).'='.$now,
4514: $env{'course.'.$cid.'.home'})
4515: }
4516: return 'ok';
4517: }
4518:
4519: # ----------------------------------------------------- Devalidate Spreadsheets
4520:
4521: sub devalidate {
4522: my ($symb,$uname,$udom)=@_;
4523: my $cid=$env{'request.course.id'};
4524: if ($cid) {
4525: # delete the stored spreadsheets for
4526: # - the student level sheet of this user in course's homespace
4527: # - the assessment level sheet for this resource
4528: # for this user in user's homespace
4529: # - current conditional state info
4530: my $key=$uname.':'.$udom.':';
4531: my $status=
4532: &del('nohist_calculatedsheets',
4533: [$key.'studentcalc:'],
4534: $env{'course.'.$cid.'.domain'},
4535: $env{'course.'.$cid.'.num'})
4536: .' '.
4537: &del('nohist_calculatedsheets_'.$cid,
4538: [$key.'assesscalc:'.$symb],$udom,$uname);
4539: unless ($status eq 'ok ok') {
4540: &logthis('Could not devalidate spreadsheet '.
4541: $uname.' at '.$udom.' for '.
4542: $symb.': '.$status);
4543: }
4544: &delenv('user.state.'.$cid);
4545: }
4546: }
4547:
4548: sub get_scalar {
4549: my ($string,$end) = @_;
4550: my $value;
4551: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4552: $value = $1;
4553: } elsif ($$string =~ s/^([^&]*?)&//) {
4554: $value = $1;
4555: }
4556: return &unescape($value);
4557: }
4558:
4559: sub array2str {
4560: my (@array) = @_;
4561: my $result=&arrayref2str(\@array);
4562: $result=~s/^__ARRAY_REF__//;
4563: $result=~s/__END_ARRAY_REF__$//;
4564: return $result;
4565: }
4566:
4567: sub arrayref2str {
4568: my ($arrayref) = @_;
4569: my $result='__ARRAY_REF__';
4570: foreach my $elem (@$arrayref) {
4571: if(ref($elem) eq 'ARRAY') {
4572: $result.=&arrayref2str($elem).'&';
4573: } elsif(ref($elem) eq 'HASH') {
4574: $result.=&hashref2str($elem).'&';
4575: } elsif(ref($elem)) {
4576: #print("Got a ref of ".(ref($elem))." skipping.");
4577: } else {
4578: $result.=&escape($elem).'&';
4579: }
4580: }
4581: $result=~s/\&$//;
4582: $result .= '__END_ARRAY_REF__';
4583: return $result;
4584: }
4585:
4586: sub hash2str {
4587: my (%hash) = @_;
4588: my $result=&hashref2str(\%hash);
4589: $result=~s/^__HASH_REF__//;
4590: $result=~s/__END_HASH_REF__$//;
4591: return $result;
4592: }
4593:
4594: sub hashref2str {
4595: my ($hashref)=@_;
4596: my $result='__HASH_REF__';
4597: foreach my $key (sort(keys(%$hashref))) {
4598: if (ref($key) eq 'ARRAY') {
4599: $result.=&arrayref2str($key).'=';
4600: } elsif (ref($key) eq 'HASH') {
4601: $result.=&hashref2str($key).'=';
4602: } elsif (ref($key)) {
4603: $result.='=';
4604: #print("Got a ref of ".(ref($key))." skipping.");
4605: } else {
4606: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4607: }
4608:
4609: if(ref($hashref->{$key}) eq 'ARRAY') {
4610: $result.=&arrayref2str($hashref->{$key}).'&';
4611: } elsif(ref($hashref->{$key}) eq 'HASH') {
4612: $result.=&hashref2str($hashref->{$key}).'&';
4613: } elsif(ref($hashref->{$key})) {
4614: $result.='&';
4615: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4616: } else {
4617: $result.=&escape($hashref->{$key}).'&';
4618: }
4619: }
4620: $result=~s/\&$//;
4621: $result .= '__END_HASH_REF__';
4622: return $result;
4623: }
4624:
4625: sub str2hash {
4626: my ($string)=@_;
4627: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4628: return %$hash;
4629: }
4630:
4631: sub str2hashref {
4632: my ($string) = @_;
4633:
4634: my %hash;
4635:
4636: if($string !~ /^__HASH_REF__/) {
4637: if (! ($string eq '' || !defined($string))) {
4638: $hash{'error'}='Not hash reference';
4639: }
4640: return (\%hash, $string);
4641: }
4642:
4643: $string =~ s/^__HASH_REF__//;
4644:
4645: while($string !~ /^__END_HASH_REF__/) {
4646: #key
4647: my $key='';
4648: if($string =~ /^__HASH_REF__/) {
4649: ($key, $string)=&str2hashref($string);
4650: if(defined($key->{'error'})) {
4651: $hash{'error'}='Bad data';
4652: return (\%hash, $string);
4653: }
4654: } elsif($string =~ /^__ARRAY_REF__/) {
4655: ($key, $string)=&str2arrayref($string);
4656: if($key->[0] eq 'Array reference error') {
4657: $hash{'error'}='Bad data';
4658: return (\%hash, $string);
4659: }
4660: } else {
4661: $string =~ s/^(.*?)=//;
4662: $key=&unescape($1);
4663: }
4664: $string =~ s/^=//;
4665:
4666: #value
4667: my $value='';
4668: if($string =~ /^__HASH_REF__/) {
4669: ($value, $string)=&str2hashref($string);
4670: if(defined($value->{'error'})) {
4671: $hash{'error'}='Bad data';
4672: return (\%hash, $string);
4673: }
4674: } elsif($string =~ /^__ARRAY_REF__/) {
4675: ($value, $string)=&str2arrayref($string);
4676: if($value->[0] eq 'Array reference error') {
4677: $hash{'error'}='Bad data';
4678: return (\%hash, $string);
4679: }
4680: } else {
4681: $value=&get_scalar(\$string,'__END_HASH_REF__');
4682: }
4683: $string =~ s/^&//;
4684:
4685: $hash{$key}=$value;
4686: }
4687:
4688: $string =~ s/^__END_HASH_REF__//;
4689:
4690: return (\%hash, $string);
4691: }
4692:
4693: sub str2array {
4694: my ($string)=@_;
4695: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4696: return @$array;
4697: }
4698:
4699: sub str2arrayref {
4700: my ($string) = @_;
4701: my @array;
4702:
4703: if($string !~ /^__ARRAY_REF__/) {
4704: if (! ($string eq '' || !defined($string))) {
4705: $array[0]='Array reference error';
4706: }
4707: return (\@array, $string);
4708: }
4709:
4710: $string =~ s/^__ARRAY_REF__//;
4711:
4712: while($string !~ /^__END_ARRAY_REF__/) {
4713: my $value='';
4714: if($string =~ /^__HASH_REF__/) {
4715: ($value, $string)=&str2hashref($string);
4716: if(defined($value->{'error'})) {
4717: $array[0] ='Array reference error';
4718: return (\@array, $string);
4719: }
4720: } elsif($string =~ /^__ARRAY_REF__/) {
4721: ($value, $string)=&str2arrayref($string);
4722: if($value->[0] eq 'Array reference error') {
4723: $array[0] ='Array reference error';
4724: return (\@array, $string);
4725: }
4726: } else {
4727: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4728: }
4729: $string =~ s/^&//;
4730:
4731: push(@array, $value);
4732: }
4733:
4734: $string =~ s/^__END_ARRAY_REF__//;
4735:
4736: return (\@array, $string);
4737: }
4738:
4739: # -------------------------------------------------------------------Temp Store
4740:
4741: sub tmpreset {
4742: my ($symb,$namespace,$domain,$stuname) = @_;
4743: if (!$symb) {
4744: $symb=&symbread();
4745: if (!$symb) { $symb= $env{'request.url'}; }
4746: }
4747: $symb=escape($symb);
4748:
4749: if (!$namespace) { $namespace=$env{'request.state'}; }
4750: $namespace=~s/\//\_/g;
4751: $namespace=~s/\W//g;
4752:
4753: if (!$domain) { $domain=$env{'user.domain'}; }
4754: if (!$stuname) { $stuname=$env{'user.name'}; }
4755: if ($domain eq 'public' && $stuname eq 'public') {
4756: $stuname=$ENV{'REMOTE_ADDR'};
4757: }
4758: my $path=LONCAPA::tempdir();
4759: my %hash;
4760: if (tie(%hash,'GDBM_File',
4761: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4762: &GDBM_WRCREAT(),0640)) {
4763: foreach my $key (keys(%hash)) {
4764: if ($key=~ /:$symb/) {
4765: delete($hash{$key});
4766: }
4767: }
4768: }
4769: }
4770:
4771: sub tmpstore {
4772: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4773:
4774: if (!$symb) {
4775: $symb=&symbread();
4776: if (!$symb) { $symb= $env{'request.url'}; }
4777: }
4778: $symb=escape($symb);
4779:
4780: if (!$namespace) {
4781: # I don't think we would ever want to store this for a course.
4782: # it seems this will only be used if we don't have a course.
4783: #$namespace=$env{'request.course.id'};
4784: #if (!$namespace) {
4785: $namespace=$env{'request.state'};
4786: #}
4787: }
4788: $namespace=~s/\//\_/g;
4789: $namespace=~s/\W//g;
4790: if (!$domain) { $domain=$env{'user.domain'}; }
4791: if (!$stuname) { $stuname=$env{'user.name'}; }
4792: if ($domain eq 'public' && $stuname eq 'public') {
4793: $stuname=$ENV{'REMOTE_ADDR'};
4794: }
4795: my $now=time;
4796: my %hash;
4797: my $path=LONCAPA::tempdir();
4798: if (tie(%hash,'GDBM_File',
4799: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4800: &GDBM_WRCREAT(),0640)) {
4801: $hash{"version:$symb"}++;
4802: my $version=$hash{"version:$symb"};
4803: my $allkeys='';
4804: foreach my $key (keys(%$storehash)) {
4805: $allkeys.=$key.':';
4806: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4807: }
4808: $hash{"$version:$symb:timestamp"}=$now;
4809: $allkeys.='timestamp';
4810: $hash{"$version:keys:$symb"}=$allkeys;
4811: if (untie(%hash)) {
4812: return 'ok';
4813: } else {
4814: return "error:$!";
4815: }
4816: } else {
4817: return "error:$!";
4818: }
4819: }
4820:
4821: # -----------------------------------------------------------------Temp Restore
4822:
4823: sub tmprestore {
4824: my ($symb,$namespace,$domain,$stuname) = @_;
4825:
4826: if (!$symb) {
4827: $symb=&symbread();
4828: if (!$symb) { $symb= $env{'request.url'}; }
4829: }
4830: $symb=escape($symb);
4831:
4832: if (!$namespace) { $namespace=$env{'request.state'}; }
4833:
4834: if (!$domain) { $domain=$env{'user.domain'}; }
4835: if (!$stuname) { $stuname=$env{'user.name'}; }
4836: if ($domain eq 'public' && $stuname eq 'public') {
4837: $stuname=$ENV{'REMOTE_ADDR'};
4838: }
4839: my %returnhash;
4840: $namespace=~s/\//\_/g;
4841: $namespace=~s/\W//g;
4842: my %hash;
4843: my $path=LONCAPA::tempdir();
4844: if (tie(%hash,'GDBM_File',
4845: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4846: &GDBM_READER(),0640)) {
4847: my $version=$hash{"version:$symb"};
4848: $returnhash{'version'}=$version;
4849: my $scope;
4850: for ($scope=1;$scope<=$version;$scope++) {
4851: my $vkeys=$hash{"$scope:keys:$symb"};
4852: my @keys=split(/:/,$vkeys);
4853: my $key;
4854: $returnhash{"$scope:keys"}=$vkeys;
4855: foreach $key (@keys) {
4856: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4857: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4858: }
4859: }
4860: if (!(untie(%hash))) {
4861: return "error:$!";
4862: }
4863: } else {
4864: return "error:$!";
4865: }
4866: return %returnhash;
4867: }
4868:
4869: # ----------------------------------------------------------------------- Store
4870:
4871: sub store {
4872: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
4873: my $home='';
4874:
4875: if ($stuname) { $home=&homeserver($stuname,$domain); }
4876:
4877: $symb=&symbclean($symb);
4878: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4879:
4880: if (!$domain) { $domain=$env{'user.domain'}; }
4881: if (!$stuname) { $stuname=$env{'user.name'}; }
4882:
4883: &devalidate($symb,$stuname,$domain);
4884:
4885: $symb=escape($symb);
4886: if (!$namespace) {
4887: unless ($namespace=$env{'request.course.id'}) {
4888: return '';
4889: }
4890: }
4891: if (!$home) { $home=$env{'user.home'}; }
4892:
4893: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4894: $$storehash{'host'}=$perlvar{'lonHostID'};
4895:
4896: my $namevalue='';
4897: foreach my $key (keys(%$storehash)) {
4898: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4899: }
4900: $namevalue=~s/\&$//;
4901: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4902: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
4903: }
4904:
4905: # -------------------------------------------------------------- Critical Store
4906:
4907: sub cstore {
4908: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
4909: my $home='';
4910:
4911: if ($stuname) { $home=&homeserver($stuname,$domain); }
4912:
4913: $symb=&symbclean($symb);
4914: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4915:
4916: if (!$domain) { $domain=$env{'user.domain'}; }
4917: if (!$stuname) { $stuname=$env{'user.name'}; }
4918:
4919: &devalidate($symb,$stuname,$domain);
4920:
4921: $symb=escape($symb);
4922: if (!$namespace) {
4923: unless ($namespace=$env{'request.course.id'}) {
4924: return '';
4925: }
4926: }
4927: if (!$home) { $home=$env{'user.home'}; }
4928:
4929: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4930: $$storehash{'host'}=$perlvar{'lonHostID'};
4931:
4932: my $namevalue='';
4933: foreach my $key (keys(%$storehash)) {
4934: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4935: }
4936: $namevalue=~s/\&$//;
4937: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4938: return critical
4939: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
4940: }
4941:
4942: # --------------------------------------------------------------------- Restore
4943:
4944: sub restore {
4945: my ($symb,$namespace,$domain,$stuname) = @_;
4946: my $home='';
4947:
4948: if ($stuname) { $home=&homeserver($stuname,$domain); }
4949:
4950: if (!$symb) {
4951: return if ($namespace eq 'courserequests');
4952: unless ($symb=escape(&symbread())) { return ''; }
4953: } else {
4954: unless ($namespace eq 'courserequests') {
4955: $symb=&escape(&symbclean($symb));
4956: }
4957: }
4958: if (!$namespace) {
4959: unless ($namespace=$env{'request.course.id'}) {
4960: return '';
4961: }
4962: }
4963: if (!$domain) { $domain=$env{'user.domain'}; }
4964: if (!$stuname) { $stuname=$env{'user.name'}; }
4965: if (!$home) { $home=$env{'user.home'}; }
4966: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4967:
4968: my %returnhash=();
4969: foreach my $line (split(/\&/,$answer)) {
4970: my ($name,$value)=split(/\=/,$line);
4971: $returnhash{&unescape($name)}=&thaw_unescape($value);
4972: }
4973: my $version;
4974: for ($version=1;$version<=$returnhash{'version'};$version++) {
4975: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4976: $returnhash{$item}=$returnhash{$version.':'.$item};
4977: }
4978: }
4979: return %returnhash;
4980: }
4981:
4982: # ---------------------------------------------------------- Course Description
4983: #
4984: #
4985:
4986: sub coursedescription {
4987: my ($courseid,$args)=@_;
4988: $courseid=~s/^\///;
4989: $courseid=~s/\_/\//g;
4990: my ($cdomain,$cnum)=split(/\//,$courseid);
4991: my $chome=&homeserver($cnum,$cdomain);
4992: my $normalid=$cdomain.'_'.$cnum;
4993: # need to always cache even if we get errors otherwise we keep
4994: # trying and trying and trying to get the course description.
4995: my %envhash=();
4996: my %returnhash=();
4997:
4998: my $expiretime=600;
4999: if ($env{'request.course.id'} eq $normalid) {
5000: $expiretime=120;
5001: }
5002:
5003: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
5004: if (!$args->{'freshen_cache'}
5005: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
5006: foreach my $key (keys(%env)) {
5007: next if ($key !~ /^\Q$prefix\E(.*)/);
5008: my ($setting) = $1;
5009: $returnhash{$setting} = $env{$key};
5010: }
5011: return %returnhash;
5012: }
5013:
5014: # get the data again
5015:
5016: if (!$args->{'one_time'}) {
5017: $envhash{'course.'.$normalid.'.last_cache'}=time;
5018: }
5019:
5020: if ($chome ne 'no_host') {
5021: %returnhash=&dump('environment',$cdomain,$cnum);
5022: if (!exists($returnhash{'con_lost'})) {
5023: my $username = $env{'user.name'}; # Defult username
5024: if(defined $args->{'user'}) {
5025: $username = $args->{'user'};
5026: }
5027: $returnhash{'home'}= $chome;
5028: $returnhash{'domain'} = $cdomain;
5029: $returnhash{'num'} = $cnum;
5030: if (!defined($returnhash{'type'})) {
5031: $returnhash{'type'} = 'Course';
5032: }
5033: while (my ($name,$value) = each %returnhash) {
5034: $envhash{'course.'.$normalid.'.'.$name}=$value;
5035: }
5036: $returnhash{'url'}=&clutter($returnhash{'url'});
5037: $returnhash{'fn'}=LONCAPA::tempdir() .
5038: $username.'_'.$cdomain.'_'.$cnum;
5039: $envhash{'course.'.$normalid.'.home'}=$chome;
5040: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
5041: $envhash{'course.'.$normalid.'.num'}=$cnum;
5042: }
5043: }
5044: if (!$args->{'one_time'}) {
5045: &appenv(\%envhash);
5046: }
5047: return %returnhash;
5048: }
5049:
5050: sub update_released_required {
5051: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
5052: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
5053: $cid = $env{'request.course.id'};
5054: $cdom = $env{'course.'.$cid.'.domain'};
5055: $cnum = $env{'course.'.$cid.'.num'};
5056: $chome = $env{'course.'.$cid.'.home'};
5057: }
5058: if ($needsrelease) {
5059: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
5060: my $needsupdate;
5061: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
5062: $needsupdate = 1;
5063: } else {
5064: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
5065: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
5066: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
5067: $needsupdate = 1;
5068: }
5069: }
5070: if ($needsupdate) {
5071: my %needshash = (
5072: 'internal.releaserequired' => $needsrelease,
5073: );
5074: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
5075: if ($putresult eq 'ok') {
5076: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
5077: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
5078: if (ref($crsinfo{$cid}) eq 'HASH') {
5079: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
5080: &courseidput($cdom,\%crsinfo,$chome,'notime');
5081: }
5082: }
5083: }
5084: }
5085: return;
5086: }
5087:
5088: # -------------------------------------------------See if a user is privileged
5089:
5090: sub privileged {
5091: my ($username,$domain,$possdomains,$possroles)=@_;
5092: my $now = time;
5093: my $roles;
5094: if (ref($possroles) eq 'ARRAY') {
5095: $roles = $possroles;
5096: } else {
5097: $roles = ['dc','su'];
5098: }
5099: if (ref($possdomains) eq 'ARRAY') {
5100: my %privileged = &privileged_by_domain($possdomains,$roles);
5101: foreach my $dom (@{$possdomains}) {
5102: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
5103: (ref($privileged{$dom}) eq 'HASH')) {
5104: foreach my $role (@{$roles}) {
5105: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5106: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
5107: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
5108: return 1 unless (($end && $end < $now) ||
5109: ($start && $start > $now));
5110: }
5111: }
5112: }
5113: }
5114: }
5115: } else {
5116: my %rolesdump = &dump("roles", $domain, $username) or return 0;
5117: my $now = time;
5118:
5119: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
5120: my ($trole, $tend, $tstart) = split(/_/, $role);
5121: if (grep(/^\Q$trole\E$/,@{$roles})) {
5122: return 1 unless ($tend && $tend < $now)
5123: or ($tstart && $tstart > $now);
5124: }
5125: }
5126: }
5127: return 0;
5128: }
5129:
5130: sub privileged_by_domain {
5131: my ($domains,$roles) = @_;
5132: my %privileged = ();
5133: my $cachetime = 60*60*24;
5134: my $now = time;
5135: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
5136: return %privileged;
5137: }
5138: foreach my $dom (@{$domains}) {
5139: next if (ref($privileged{$dom}) eq 'HASH');
5140: my $needroles;
5141: foreach my $role (@{$roles}) {
5142: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
5143: if (defined($cached)) {
5144: if (ref($result) eq 'HASH') {
5145: $privileged{$dom}{$role} = $result;
5146: }
5147: } else {
5148: $needroles = 1;
5149: }
5150: }
5151: if ($needroles) {
5152: my %dompersonnel = &get_domain_roles($dom,$roles);
5153: $privileged{$dom} = {};
5154: foreach my $server (keys(%dompersonnel)) {
5155: if (ref($dompersonnel{$server}) eq 'HASH') {
5156: foreach my $item (keys(%{$dompersonnel{$server}})) {
5157: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
5158: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
5159: next if ($end && $end < $now);
5160: $privileged{$dom}{$trole}{$uname.':'.$udom} =
5161: $dompersonnel{$server}{$item};
5162: }
5163: }
5164: }
5165: if (ref($privileged{$dom}) eq 'HASH') {
5166: foreach my $role (@{$roles}) {
5167: if (ref($privileged{$dom}{$role}) eq 'HASH') {
5168: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
5169: } else {
5170: my %hash = ();
5171: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
5172: }
5173: }
5174: }
5175: }
5176: }
5177: return %privileged;
5178: }
5179:
5180: # -------------------------------------------------------- Get user privileges
5181:
5182: sub rolesinit {
5183: my ($domain, $username) = @_;
5184: my %userroles = ('user.login.time' => time);
5185: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
5186:
5187: # firstaccess and timerinterval are related to timed maps/resources.
5188: # also, blocking can be triggered by an activating timer
5189: # it's saved in the user's %env.
5190: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
5191: my %timerinterval = &dump('timerinterval', $domain, $username);
5192: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
5193: %timerintchk, %timerintenv);
5194:
5195: foreach my $key (keys(%firstaccess)) {
5196: my ($cid, $rest) = split(/\0/, $key);
5197: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
5198: }
5199:
5200: foreach my $key (keys(%timerinterval)) {
5201: my ($cid,$rest) = split(/\0/,$key);
5202: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
5203: }
5204:
5205: my %allroles=();
5206: my %allgroups=();
5207:
5208: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
5209: my $role = $rolesdump{$area};
5210: $area =~ s/\_\w\w$//;
5211:
5212: my ($trole, $tend, $tstart, $group_privs);
5213:
5214: if ($role =~ /^cr/) {
5215: # Custom role, defined by a user
5216: # e.g., user.role.cr/msu/smith/mynewrole
5217: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
5218: $trole = $1;
5219: ($tend, $tstart) = split('_', $2);
5220: } else {
5221: $trole = $role;
5222: }
5223: } elsif ($role =~ m|^gr/|) {
5224: # Role of member in a group, defined within a course/community
5225: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
5226: ($trole, $tend, $tstart) = split(/_/, $role);
5227: next if $tstart eq '-1';
5228: ($trole, $group_privs) = split(/\//, $trole);
5229: $group_privs = &unescape($group_privs);
5230: } else {
5231: # Just a normal role, defined in roles.tab
5232: ($trole, $tend, $tstart) = split(/_/,$role);
5233: }
5234:
5235: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
5236: $username);
5237: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
5238:
5239: # role expired or not available yet?
5240: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
5241: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
5242:
5243: next if $area eq '' or $trole eq '';
5244:
5245: my $spec = "$trole.$area";
5246: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
5247:
5248: if ($trole =~ /^cr\//) {
5249: # Custom role, defined by a user
5250: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5251: } elsif ($trole eq 'gr') {
5252: # Role of a member in a group, defined within a course/community
5253: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
5254: next;
5255: } else {
5256: # Normal role, defined in roles.tab
5257: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5258: }
5259:
5260: my $cid = $tdomain.'_'.$trest;
5261: unless ($firstaccchk{$cid}) {
5262: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
5263: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
5264: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
5265: $coursetimerstarts{$cid}{$item};
5266: }
5267: }
5268: $firstaccchk{$cid} = 1;
5269: }
5270: unless ($timerintchk{$cid}) {
5271: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
5272: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
5273: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
5274: $coursetimerintervals{$cid}{$item};
5275: }
5276: }
5277: $timerintchk{$cid} = 1;
5278: }
5279: }
5280:
5281: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
5282: \%allroles, \%allgroups);
5283: $env{'user.adv'} = $userroles{'user.adv'};
5284:
5285: return (\%userroles,\%firstaccenv,\%timerintenv);
5286: }
5287:
5288: sub set_arearole {
5289: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
5290: unless ($nolog) {
5291: # log the associated role with the area
5292: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
5293: }
5294: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
5295: }
5296:
5297: sub custom_roleprivs {
5298: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
5299: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
5300: my $homsvr = &homeserver($rauthor,$rdomain);
5301: if (&hostname($homsvr) ne '') {
5302: my ($rdummy,$roledef)=
5303: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
5304: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
5305: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
5306: if (defined($syspriv)) {
5307: if ($trest =~ /^$match_community$/) {
5308: $syspriv =~ s/bre\&S//;
5309: }
5310: $$allroles{'cm./'}.=':'.$syspriv;
5311: $$allroles{$spec.'./'}.=':'.$syspriv;
5312: }
5313: if ($tdomain ne '') {
5314: if (defined($dompriv)) {
5315: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
5316: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
5317: }
5318: if (($trest ne '') && (defined($coursepriv))) {
5319: $$allroles{'cm.'.$area}.=':'.$coursepriv;
5320: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
5321: }
5322: }
5323: }
5324: }
5325: }
5326:
5327: sub group_roleprivs {
5328: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
5329: my $access = 1;
5330: my $now = time;
5331: if (($tend!=0) && ($tend<$now)) { $access = 0; }
5332: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
5333: if ($access) {
5334: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
5335: $$allgroups{$course}{$group} .=':'.$group_privs;
5336: }
5337: }
5338:
5339: sub standard_roleprivs {
5340: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
5341: if (defined($pr{$trole.':s'})) {
5342: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
5343: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
5344: }
5345: if ($tdomain ne '') {
5346: if (defined($pr{$trole.':d'})) {
5347: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5348: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
5349: }
5350: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
5351: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
5352: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
5353: }
5354: }
5355: }
5356:
5357: sub set_userprivs {
5358: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
5359: my $author=0;
5360: my $adv=0;
5361: my %grouproles = ();
5362: if (keys(%{$allgroups}) > 0) {
5363: my @groupkeys;
5364: foreach my $role (keys(%{$allroles})) {
5365: push(@groupkeys,$role);
5366: }
5367: if (ref($groups_roles) eq 'HASH') {
5368: foreach my $key (keys(%{$groups_roles})) {
5369: unless (grep(/^\Q$key\E$/,@groupkeys)) {
5370: push(@groupkeys,$key);
5371: }
5372: }
5373: }
5374: if (@groupkeys > 0) {
5375: foreach my $role (@groupkeys) {
5376: my ($trole,$area,$sec,$extendedarea);
5377: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
5378: $trole = $1;
5379: $area = $2;
5380: $sec = $3;
5381: $extendedarea = $area.$sec;
5382: if (exists($$allgroups{$area})) {
5383: foreach my $group (keys(%{$$allgroups{$area}})) {
5384: my $spec = $trole.'.'.$extendedarea;
5385: $grouproles{$spec.'.'.$area.'/'.$group} =
5386: $$allgroups{$area}{$group};
5387: }
5388: }
5389: }
5390: }
5391: }
5392: }
5393: foreach my $group (keys(%grouproles)) {
5394: $$allroles{$group} = $grouproles{$group};
5395: }
5396: foreach my $role (keys(%{$allroles})) {
5397: my %thesepriv;
5398: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
5399: foreach my $item (split(/:/,$$allroles{$role})) {
5400: if ($item ne '') {
5401: my ($privilege,$restrictions)=split(/&/,$item);
5402: if ($restrictions eq '') {
5403: $thesepriv{$privilege}='F';
5404: } elsif ($thesepriv{$privilege} ne 'F') {
5405: $thesepriv{$privilege}.=$restrictions;
5406: }
5407: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
5408: }
5409: }
5410: my $thesestr='';
5411: foreach my $priv (sort(keys(%thesepriv))) {
5412: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
5413: }
5414: $userroles->{'user.priv.'.$role} = $thesestr;
5415: }
5416: return ($author,$adv);
5417: }
5418:
5419: sub role_status {
5420: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
5421: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
5422: my ($one,$two) = split(m{\./},$rolekey,2);
5423: (undef,undef,$$role) = split(/\./,$one,3);
5424: unless (!defined($$role) || $$role eq '') {
5425: $$where = '/'.$two;
5426: $$trolecode=$$role.'.'.$$where;
5427: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
5428: $$tstatus='is';
5429: if ($$tstart && $$tstart>$update) {
5430: $$tstatus='future';
5431: if ($$tstart<$now) {
5432: if ($$tstart && $$tstart>$refresh) {
5433: if (($$where ne '') && ($$role ne '')) {
5434: my (%allroles,%allgroups,$group_privs,
5435: %groups_roles,@rolecodes);
5436: my %userroles = (
5437: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
5438: );
5439: @rolecodes = ('cm');
5440: my $spec=$$role.'.'.$$where;
5441: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
5442: if ($$role =~ /^cr\//) {
5443: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
5444: push(@rolecodes,'cr');
5445: } elsif ($$role eq 'gr') {
5446: push(@rolecodes,$$role);
5447: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
5448: $env{'user.name'});
5449: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
5450: (undef,my $group_privs) = split(/\//,$trole);
5451: $group_privs = &unescape($group_privs);
5452: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
5453: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
5454: &get_groups_roles($tdomain,$trest,
5455: \%course_roles,\@rolecodes,
5456: \%groups_roles);
5457: } else {
5458: push(@rolecodes,$$role);
5459: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
5460: }
5461: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
5462: &appenv(\%userroles,\@rolecodes);
5463: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5464: }
5465: }
5466: $$tstatus = 'is';
5467: }
5468: }
5469: if ($$tend) {
5470: if ($$tend<$update) {
5471: $$tstatus='expired';
5472: } elsif ($$tend<$now) {
5473: $$tstatus='will_not';
5474: }
5475: }
5476: }
5477: }
5478: }
5479:
5480: sub get_groups_roles {
5481: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
5482: return unless((ref($cdom_courseroles) eq 'HASH') &&
5483: (ref($rolecodes) eq 'ARRAY') &&
5484: (ref($groups_roles) eq 'HASH'));
5485: if (keys(%{$cdom_courseroles}) > 0) {
5486: my ($cnum) = ($rest =~ /^($match_courseid)/);
5487: if ($cdom ne '' && $cnum ne '') {
5488: foreach my $key (keys(%{$cdom_courseroles})) {
5489: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
5490: my $crsrole = $1;
5491: my $crssec = $2;
5492: if ($crsrole =~ /^cr/) {
5493: unless (grep(/^cr$/,@{$rolecodes})) {
5494: push(@{$rolecodes},'cr');
5495: }
5496: } else {
5497: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
5498: push(@{$rolecodes},$crsrole);
5499: }
5500: }
5501: my $rolekey = "$crsrole./$cdom/$cnum";
5502: if ($crssec ne '') {
5503: $rolekey .= "/$crssec";
5504: }
5505: $rolekey .= './';
5506: $groups_roles->{$rolekey} = $rolecodes;
5507: }
5508: }
5509: }
5510: }
5511: return;
5512: }
5513:
5514: sub delete_env_groupprivs {
5515: my ($where,$courseroles,$possroles) = @_;
5516: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
5517: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
5518: unless (ref($courseroles->{$udom}) eq 'HASH') {
5519: %{$courseroles->{$udom}} =
5520: &get_my_roles('','','userroles',['active'],
5521: $possroles,[$udom],1);
5522: }
5523: if (ref($courseroles->{$udom}) eq 'HASH') {
5524: foreach my $item (keys(%{$courseroles->{$udom}})) {
5525: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5526: my $area = '/'.$cdom.'/'.$cnum;
5527: my $privkey = "user.priv.$crsrole.$area";
5528: if ($crssec ne '') {
5529: $privkey .= '/'.$crssec;
5530: }
5531: $privkey .= ".$area/$group";
5532: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5533: }
5534: }
5535: return;
5536: }
5537:
5538: sub check_adhoc_privs {
5539: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
5540: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5541: my $setprivs;
5542: if ($env{$cckey}) {
5543: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
5544: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
5545: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
5546: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5547: $setprivs = 1;
5548: }
5549: } else {
5550: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
5551: $setprivs = 1;
5552: }
5553: return $setprivs;
5554: }
5555:
5556: sub set_adhoc_privileges {
5557: # role can be cc or ca
5558: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5559: my $area = '/'.$dcdom.'/'.$pickedcourse;
5560: my $spec = $role.'.'.$area;
5561: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5562: $env{'user.name'},1);
5563: my %ccrole = ();
5564: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5565: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5566: &appenv(\%userroles,[$role,'cm']);
5567: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5568: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5569: &appenv( {'request.role' => $spec,
5570: 'request.role.domain' => $dcdom,
5571: 'request.course.sec' => ''
5572: }
5573: );
5574: my $tadv=0;
5575: if (&allowed('adv') eq 'F') { $tadv=1; }
5576: &appenv({'request.role.adv' => $tadv});
5577: }
5578: }
5579:
5580: # --------------------------------------------------------------- get interface
5581:
5582: sub get {
5583: my ($namespace,$storearr,$udomain,$uname)=@_;
5584: my $items='';
5585: foreach my $item (@$storearr) {
5586: $items.=&escape($item).'&';
5587: }
5588: $items=~s/\&$//;
5589: if (!$udomain) { $udomain=$env{'user.domain'}; }
5590: if (!$uname) { $uname=$env{'user.name'}; }
5591: my $uhome=&homeserver($uname,$udomain);
5592:
5593: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5594: my @pairs=split(/\&/,$rep);
5595: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5596: return @pairs;
5597: }
5598: my %returnhash=();
5599: my $i=0;
5600: foreach my $item (@$storearr) {
5601: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5602: $i++;
5603: }
5604: return %returnhash;
5605: }
5606:
5607: # --------------------------------------------------------------- del interface
5608:
5609: sub del {
5610: my ($namespace,$storearr,$udomain,$uname)=@_;
5611: my $items='';
5612: foreach my $item (@$storearr) {
5613: $items.=&escape($item).'&';
5614: }
5615:
5616: $items=~s/\&$//;
5617: if (!$udomain) { $udomain=$env{'user.domain'}; }
5618: if (!$uname) { $uname=$env{'user.name'}; }
5619: my $uhome=&homeserver($uname,$udomain);
5620: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5621: }
5622:
5623: # -------------------------------------------------------------- dump interface
5624:
5625: sub unserialize {
5626: my ($rep, $escapedkeys) = @_;
5627:
5628: return {} if $rep =~ /^error/;
5629:
5630: my %returnhash=();
5631: foreach my $item (split(/\&/,$rep)) {
5632: my ($key, $value) = split(/=/, $item, 2);
5633: $key = unescape($key) unless $escapedkeys;
5634: next if $key =~ /^error: 2 /;
5635: $returnhash{$key} = &thaw_unescape($value);
5636: }
5637: #return %returnhash;
5638: return \%returnhash;
5639: }
5640:
5641: # see Lond::dump_with_regexp
5642: # if $escapedkeys hash keys won't get unescaped.
5643: sub dump {
5644: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
5645: if (!$udomain) { $udomain=$env{'user.domain'}; }
5646: if (!$uname) { $uname=$env{'user.name'}; }
5647: my $uhome=&homeserver($uname,$udomain);
5648:
5649: if ($regexp) {
5650: $regexp=&escape($regexp);
5651: } else {
5652: $regexp='.';
5653: }
5654: if (grep { $_ eq $uhome } current_machine_ids()) {
5655: # user is hosted on this machine
5656: my $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5657: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
5658: return %{unserialize($reply, $escapedkeys)};
5659: }
5660: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5661: my @pairs=split(/\&/,$rep);
5662: my %returnhash=();
5663: if (!($rep =~ /^error/ )) {
5664: foreach my $item (@pairs) {
5665: my ($key,$value)=split(/=/,$item,2);
5666: $key = unescape($key) unless $escapedkeys;
5667: #$key = &unescape($key);
5668: next if ($key =~ /^error: 2 /);
5669: $returnhash{$key}=&thaw_unescape($value);
5670: }
5671: }
5672: return %returnhash;
5673: }
5674:
5675:
5676: # --------------------------------------------------------- dumpstore interface
5677:
5678: sub dumpstore {
5679: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5680: # same as dump but keys must be escaped. They may contain colon separated
5681: # lists of values that may themself contain colons (e.g. symbs).
5682: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
5683: }
5684:
5685: # -------------------------------------------------------------- keys interface
5686:
5687: sub getkeys {
5688: my ($namespace,$udomain,$uname)=@_;
5689: if (!$udomain) { $udomain=$env{'user.domain'}; }
5690: if (!$uname) { $uname=$env{'user.name'}; }
5691: my $uhome=&homeserver($uname,$udomain);
5692: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5693: my @keyarray=();
5694: foreach my $key (split(/\&/,$rep)) {
5695: next if ($key =~ /^error: 2 /);
5696: push(@keyarray,&unescape($key));
5697: }
5698: return @keyarray;
5699: }
5700:
5701: # --------------------------------------------------------------- currentdump
5702: sub currentdump {
5703: my ($courseid,$sdom,$sname)=@_;
5704: $courseid = $env{'request.course.id'} if (! defined($courseid));
5705: $sdom = $env{'user.domain'} if (! defined($sdom));
5706: $sname = $env{'user.name'} if (! defined($sname));
5707: my $uhome = &homeserver($sname,$sdom);
5708: my $rep;
5709:
5710: if (grep { $_ eq $uhome } current_machine_ids()) {
5711: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5712: $courseid)));
5713: } else {
5714: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5715: }
5716:
5717: return if ($rep =~ /^(error:|no_such_host)/);
5718: #
5719: my %returnhash=();
5720: #
5721: if ($rep eq "unknown_cmd") {
5722: # an old lond will not know currentdump
5723: # Do a dump and make it look like a currentdump
5724: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5725: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5726: my %hash = @tmp;
5727: @tmp=();
5728: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5729: } else {
5730: my @pairs=split(/\&/,$rep);
5731: foreach my $pair (@pairs) {
5732: my ($key,$value)=split(/=/,$pair,2);
5733: my ($symb,$param) = split(/:/,$key);
5734: $returnhash{&unescape($symb)}->{&unescape($param)} =
5735: &thaw_unescape($value);
5736: }
5737: }
5738: return %returnhash;
5739: }
5740:
5741: sub convert_dump_to_currentdump{
5742: my %hash = %{shift()};
5743: my %returnhash;
5744: # Code ripped from lond, essentially. The only difference
5745: # here is the unescaping done by lonnet::dump(). Conceivably
5746: # we might run in to problems with parameter names =~ /^v\./
5747: while (my ($key,$value) = each(%hash)) {
5748: my ($v,$symb,$param) = split(/:/,$key);
5749: $symb = &unescape($symb);
5750: $param = &unescape($param);
5751: next if ($v eq 'version' || $symb eq 'keys');
5752: next if (exists($returnhash{$symb}) &&
5753: exists($returnhash{$symb}->{$param}) &&
5754: $returnhash{$symb}->{'v.'.$param} > $v);
5755: $returnhash{$symb}->{$param}=$value;
5756: $returnhash{$symb}->{'v.'.$param}=$v;
5757: }
5758: #
5759: # Remove all of the keys in the hashes which keep track of
5760: # the version of the parameter.
5761: while (my ($symb,$param_hash) = each(%returnhash)) {
5762: # use a foreach because we are going to delete from the hash.
5763: foreach my $key (keys(%$param_hash)) {
5764: delete($param_hash->{$key}) if ($key =~ /^v\./);
5765: }
5766: }
5767: return \%returnhash;
5768: }
5769:
5770: # ------------------------------------------------------ critical inc interface
5771:
5772: sub cinc {
5773: return &inc(@_,'critical');
5774: }
5775:
5776: # --------------------------------------------------------------- inc interface
5777:
5778: sub inc {
5779: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5780: if (!$udomain) { $udomain=$env{'user.domain'}; }
5781: if (!$uname) { $uname=$env{'user.name'}; }
5782: my $uhome=&homeserver($uname,$udomain);
5783: my $items='';
5784: if (! ref($store)) {
5785: # got a single value, so use that instead
5786: $items = &escape($store).'=&';
5787: } elsif (ref($store) eq 'SCALAR') {
5788: $items = &escape($$store).'=&';
5789: } elsif (ref($store) eq 'ARRAY') {
5790: $items = join('=&',map {&escape($_);} @{$store});
5791: } elsif (ref($store) eq 'HASH') {
5792: while (my($key,$value) = each(%{$store})) {
5793: $items.= &escape($key).'='.&escape($value).'&';
5794: }
5795: }
5796: $items=~s/\&$//;
5797: if ($critical) {
5798: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5799: } else {
5800: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5801: }
5802: }
5803:
5804: # --------------------------------------------------------------- put interface
5805:
5806: sub put {
5807: my ($namespace,$storehash,$udomain,$uname)=@_;
5808: if (!$udomain) { $udomain=$env{'user.domain'}; }
5809: if (!$uname) { $uname=$env{'user.name'}; }
5810: my $uhome=&homeserver($uname,$udomain);
5811: my $items='';
5812: foreach my $item (keys(%$storehash)) {
5813: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5814: }
5815: $items=~s/\&$//;
5816: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5817: }
5818:
5819: # ------------------------------------------------------------ newput interface
5820:
5821: sub newput {
5822: my ($namespace,$storehash,$udomain,$uname)=@_;
5823: if (!$udomain) { $udomain=$env{'user.domain'}; }
5824: if (!$uname) { $uname=$env{'user.name'}; }
5825: my $uhome=&homeserver($uname,$udomain);
5826: my $items='';
5827: foreach my $key (keys(%$storehash)) {
5828: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5829: }
5830: $items=~s/\&$//;
5831: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5832: }
5833:
5834: # --------------------------------------------------------- putstore interface
5835:
5836: sub putstore {
5837: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
5838: if (!$udomain) { $udomain=$env{'user.domain'}; }
5839: if (!$uname) { $uname=$env{'user.name'}; }
5840: my $uhome=&homeserver($uname,$udomain);
5841: my $items='';
5842: foreach my $key (keys(%$storehash)) {
5843: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5844: }
5845: $items=~s/\&$//;
5846: my $esc_symb=&escape($symb);
5847: my $esc_v=&escape($version);
5848: my $reply =
5849: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5850: $uhome);
5851: if (($tolog) && ($reply eq 'ok')) {
5852: my $namevalue='';
5853: foreach my $key (keys(%{$storehash})) {
5854: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5855: }
5856: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
5857: '&host='.&escape($perlvar{'lonHostID'}).
5858: '&version='.$esc_v.
5859: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
5860: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
5861: }
5862: if ($reply eq 'unknown_cmd') {
5863: # gfall back to way things use to be done
5864: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5865: $uname);
5866: }
5867: return $reply;
5868: }
5869:
5870: sub old_putstore {
5871: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5872: if (!$udomain) { $udomain=$env{'user.domain'}; }
5873: if (!$uname) { $uname=$env{'user.name'}; }
5874: my $uhome=&homeserver($uname,$udomain);
5875: my %newstorehash;
5876: foreach my $item (keys(%$storehash)) {
5877: my $key = $version.':'.&escape($symb).':'.$item;
5878: $newstorehash{$key} = $storehash->{$item};
5879: }
5880: my $items='';
5881: my %allitems = ();
5882: foreach my $item (keys(%newstorehash)) {
5883: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5884: my $key = $1.':keys:'.$2;
5885: $allitems{$key} .= $3.':';
5886: }
5887: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5888: }
5889: foreach my $item (keys(%allitems)) {
5890: $allitems{$item} =~ s/\:$//;
5891: $items.= $item.'='.$allitems{$item}.'&';
5892: }
5893: $items=~s/\&$//;
5894: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5895: }
5896:
5897: # ------------------------------------------------------ critical put interface
5898:
5899: sub cput {
5900: my ($namespace,$storehash,$udomain,$uname)=@_;
5901: if (!$udomain) { $udomain=$env{'user.domain'}; }
5902: if (!$uname) { $uname=$env{'user.name'}; }
5903: my $uhome=&homeserver($uname,$udomain);
5904: my $items='';
5905: foreach my $item (keys(%$storehash)) {
5906: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5907: }
5908: $items=~s/\&$//;
5909: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5910: }
5911:
5912: # -------------------------------------------------------------- eget interface
5913:
5914: sub eget {
5915: my ($namespace,$storearr,$udomain,$uname)=@_;
5916: my $items='';
5917: foreach my $item (@$storearr) {
5918: $items.=&escape($item).'&';
5919: }
5920: $items=~s/\&$//;
5921: if (!$udomain) { $udomain=$env{'user.domain'}; }
5922: if (!$uname) { $uname=$env{'user.name'}; }
5923: my $uhome=&homeserver($uname,$udomain);
5924: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5925: my @pairs=split(/\&/,$rep);
5926: my %returnhash=();
5927: my $i=0;
5928: foreach my $item (@$storearr) {
5929: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5930: $i++;
5931: }
5932: return %returnhash;
5933: }
5934:
5935: # ------------------------------------------------------------ tmpput interface
5936: sub tmpput {
5937: my ($storehash,$server,$context)=@_;
5938: my $items='';
5939: foreach my $item (keys(%$storehash)) {
5940: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5941: }
5942: $items=~s/\&$//;
5943: if (defined($context)) {
5944: $items .= ':'.&escape($context);
5945: }
5946: return &reply("tmpput:$items",$server);
5947: }
5948:
5949: # ------------------------------------------------------------ tmpget interface
5950: sub tmpget {
5951: my ($token,$server)=@_;
5952: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5953: my $rep=&reply("tmpget:$token",$server);
5954: my %returnhash;
5955: foreach my $item (split(/\&/,$rep)) {
5956: my ($key,$value)=split(/=/,$item);
5957: next if ($key =~ /^error: 2 /);
5958: $returnhash{&unescape($key)}=&thaw_unescape($value);
5959: }
5960: return %returnhash;
5961: }
5962:
5963: # ------------------------------------------------------------ tmpdel interface
5964: sub tmpdel {
5965: my ($token,$server)=@_;
5966: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5967: return &reply("tmpdel:$token",$server);
5968: }
5969:
5970: # ------------------------------------------------------------ get_timebased_id
5971:
5972: sub get_timebased_id {
5973: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
5974: $maxtries) = @_;
5975: my ($newid,$error,$dellock);
5976: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
5977: return ('','ok','invalid call to get suffix');
5978: }
5979:
5980: # set defaults for any optional args for which values were not supplied
5981: if ($who eq '') {
5982: $who = $env{'user.name'}.':'.$env{'user.domain'};
5983: }
5984: if (!$locktries) {
5985: $locktries = 3;
5986: }
5987: if (!$maxtries) {
5988: $maxtries = 10;
5989: }
5990:
5991: if (($cdom eq '') || ($cnum eq '')) {
5992: if ($env{'request.course.id'}) {
5993: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5994: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5995: }
5996: if (($cdom eq '') || ($cnum eq '')) {
5997: return ('','ok','call to get suffix not in course context');
5998: }
5999: }
6000:
6001: # construct locking item
6002: my $lockhash = {
6003: $prefix."\0".'locked_'.$keyid => $who,
6004: };
6005: my $tries = 0;
6006:
6007: # attempt to get lock on nohist_$namespace file
6008: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6009: while (($gotlock ne 'ok') && $tries <$locktries) {
6010: $tries ++;
6011: sleep 1;
6012: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
6013: }
6014:
6015: # attempt to get unique identifier, based on current timestamp
6016: if ($gotlock eq 'ok') {
6017: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
6018: my $id = time;
6019: $newid = $id;
6020: if ($idtype eq 'addcode') {
6021: $newid .= &sixnum_code();
6022: }
6023: my $idtries = 0;
6024: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
6025: if ($idtype eq 'concat') {
6026: $newid = $id.$idtries;
6027: } elsif ($idtype eq 'addcode') {
6028: $newid = $newid.&sixnum_code();
6029: } else {
6030: $newid ++;
6031: }
6032: $idtries ++;
6033: }
6034: if (!exists($inuse{$prefix."\0".$newid})) {
6035: my %new_item = (
6036: $prefix."\0".$newid => $who,
6037: );
6038: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
6039: $cdom,$cnum);
6040: if ($putresult ne 'ok') {
6041: undef($newid);
6042: $error = 'error saving new item: '.$putresult;
6043: }
6044: } else {
6045: undef($newid);
6046: $error = ('error: no unique suffix available for the new item ');
6047: }
6048: # remove lock
6049: my @del_lock = ($prefix."\0".'locked_'.$keyid);
6050: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
6051: } else {
6052: $error = "error: could not obtain lockfile\n";
6053: $dellock = 'ok';
6054: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
6055: $dellock = 'nolock';
6056: }
6057: }
6058: return ($newid,$dellock,$error);
6059: }
6060:
6061: sub sixnum_code {
6062: my $code;
6063: for (0..6) {
6064: $code .= int( rand(9) );
6065: }
6066: return $code;
6067: }
6068:
6069: # -------------------------------------------------- portfolio access checking
6070:
6071: sub portfolio_access {
6072: my ($requrl,$clientip) = @_;
6073: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
6074: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
6075: if ($result) {
6076: my %setters;
6077: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6078: my ($startblock,$endblock) =
6079: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
6080: if ($startblock && $endblock) {
6081: return 'B';
6082: }
6083: } else {
6084: my ($startblock,$endblock) =
6085: &Apache::loncommon::blockcheck(\%setters,'port');
6086: if ($startblock && $endblock) {
6087: return 'B';
6088: }
6089: }
6090: }
6091: if ($result eq 'ok') {
6092: return 'F';
6093: } elsif ($result =~ /^[^:]+:guest_/) {
6094: return 'A';
6095: }
6096: return '';
6097: }
6098:
6099: sub get_portfolio_access {
6100: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
6101:
6102: if (!ref($access_hash)) {
6103: my $current_perms = &get_portfile_permissions($udom,$unum);
6104: my %access_controls = &get_access_controls($current_perms,$group,
6105: $file_name);
6106: $access_hash = $access_controls{$file_name};
6107: }
6108:
6109: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
6110: my $now = time;
6111: if (ref($access_hash) eq 'HASH') {
6112: foreach my $key (keys(%{$access_hash})) {
6113: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6114: if ($start > $now) {
6115: next;
6116: }
6117: if ($end && $end<$now) {
6118: next;
6119: }
6120: if ($scope eq 'public') {
6121: $public = $key;
6122: last;
6123: } elsif ($scope eq 'guest') {
6124: $guest = $key;
6125: } elsif ($scope eq 'domains') {
6126: push(@domains,$key);
6127: } elsif ($scope eq 'users') {
6128: push(@users,$key);
6129: } elsif ($scope eq 'course') {
6130: push(@courses,$key);
6131: } elsif ($scope eq 'group') {
6132: push(@groups,$key);
6133: } elsif ($scope eq 'ip') {
6134: push(@ips,$key);
6135: }
6136: }
6137: if ($public) {
6138: return 'ok';
6139: } elsif (@ips > 0) {
6140: my $allowed;
6141: foreach my $ipkey (@ips) {
6142: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
6143: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
6144: $allowed = 1;
6145: last;
6146: }
6147: }
6148: }
6149: if ($allowed) {
6150: return 'ok';
6151: }
6152: }
6153: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
6154: if ($guest) {
6155: return $guest;
6156: }
6157: } else {
6158: if (@domains > 0) {
6159: foreach my $domkey (@domains) {
6160: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
6161: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
6162: return 'ok';
6163: }
6164: }
6165: }
6166: }
6167: if (@users > 0) {
6168: foreach my $userkey (@users) {
6169: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
6170: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
6171: if (ref($item) eq 'HASH') {
6172: if (($item->{'uname'} eq $env{'user.name'}) &&
6173: ($item->{'udom'} eq $env{'user.domain'})) {
6174: return 'ok';
6175: }
6176: }
6177: }
6178: }
6179: }
6180: }
6181: my %roleshash;
6182: my @courses_and_groups = @courses;
6183: push(@courses_and_groups,@groups);
6184: if (@courses_and_groups > 0) {
6185: my (%allgroups,%allroles);
6186: my ($start,$end,$role,$sec,$group);
6187: foreach my $envkey (%env) {
6188: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
6189: my $cid = $2.'_'.$3;
6190: if ($1 eq 'gr') {
6191: $group = $4;
6192: $allgroups{$cid}{$group} = $env{$envkey};
6193: } else {
6194: if ($4 eq '') {
6195: $sec = 'none';
6196: } else {
6197: $sec = $4;
6198: }
6199: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6200: }
6201: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
6202: my $cid = $2.'_'.$3;
6203: if ($4 eq '') {
6204: $sec = 'none';
6205: } else {
6206: $sec = $4;
6207: }
6208: $allroles{$cid}{$1}{$sec} = $env{$envkey};
6209: }
6210: }
6211: if (keys(%allroles) == 0) {
6212: return;
6213: }
6214: foreach my $key (@courses_and_groups) {
6215: my %content = %{$$access_hash{$key}};
6216: my $cnum = $content{'number'};
6217: my $cdom = $content{'domain'};
6218: my $cid = $cdom.'_'.$cnum;
6219: if (!exists($allroles{$cid})) {
6220: next;
6221: }
6222: foreach my $role_id (keys(%{$content{'roles'}})) {
6223: my @sections = @{$content{'roles'}{$role_id}{'section'}};
6224: my @groups = @{$content{'roles'}{$role_id}{'group'}};
6225: my @status = @{$content{'roles'}{$role_id}{'access'}};
6226: my @roles = @{$content{'roles'}{$role_id}{'role'}};
6227: foreach my $role (keys(%{$allroles{$cid}})) {
6228: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
6229: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
6230: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
6231: if (grep/^all$/,@sections) {
6232: return 'ok';
6233: } else {
6234: if (grep/^$sec$/,@sections) {
6235: return 'ok';
6236: }
6237: }
6238: }
6239: }
6240: if (keys(%{$allgroups{$cid}}) == 0) {
6241: if (grep/^none$/,@groups) {
6242: return 'ok';
6243: }
6244: } else {
6245: if (grep/^all$/,@groups) {
6246: return 'ok';
6247: }
6248: foreach my $group (keys(%{$allgroups{$cid}})) {
6249: if (grep/^$group$/,@groups) {
6250: return 'ok';
6251: }
6252: }
6253: }
6254: }
6255: }
6256: }
6257: }
6258: }
6259: if ($guest) {
6260: return $guest;
6261: }
6262: }
6263: }
6264: return;
6265: }
6266:
6267: sub course_group_datechecker {
6268: my ($dates,$now,$status) = @_;
6269: my ($start,$end) = split(/\./,$dates);
6270: if (!$start && !$end) {
6271: return 'ok';
6272: }
6273: if (grep/^active$/,@{$status}) {
6274: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
6275: return 'ok';
6276: }
6277: }
6278: if (grep/^previous$/,@{$status}) {
6279: if ($end > $now ) {
6280: return 'ok';
6281: }
6282: }
6283: if (grep/^future$/,@{$status}) {
6284: if ($start > $now) {
6285: return 'ok';
6286: }
6287: }
6288: return;
6289: }
6290:
6291: sub parse_portfolio_url {
6292: my ($url) = @_;
6293:
6294: my ($type,$udom,$unum,$group,$file_name);
6295:
6296: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
6297: $type = 1;
6298: $udom = $1;
6299: $unum = $2;
6300: $file_name = $3;
6301: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
6302: $type = 2;
6303: $udom = $1;
6304: $unum = $2;
6305: $group = $3;
6306: $file_name = $3.'/'.$4;
6307: }
6308: if (wantarray) {
6309: return ($type,$udom,$unum,$file_name,$group);
6310: }
6311: return $type;
6312: }
6313:
6314: sub is_portfolio_url {
6315: my ($url) = @_;
6316: return scalar(&parse_portfolio_url($url));
6317: }
6318:
6319: sub is_portfolio_file {
6320: my ($file) = @_;
6321: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
6322: return 1;
6323: }
6324: return;
6325: }
6326:
6327: sub usertools_access {
6328: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
6329: my ($access,%tools);
6330: if ($context eq '') {
6331: $context = 'tools';
6332: }
6333: if ($context eq 'requestcourses') {
6334: %tools = (
6335: official => 1,
6336: unofficial => 1,
6337: community => 1,
6338: textbook => 1,
6339: );
6340: } elsif ($context eq 'requestauthor') {
6341: %tools = (
6342: requestauthor => 1,
6343: );
6344: } else {
6345: %tools = (
6346: aboutme => 1,
6347: blog => 1,
6348: webdav => 1,
6349: portfolio => 1,
6350: );
6351: }
6352: return if (!defined($tools{$tool}));
6353:
6354: if (($udom eq '') || ($uname eq '')) {
6355: $udom = $env{'user.domain'};
6356: $uname = $env{'user.name'};
6357: }
6358:
6359: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6360: if ($action ne 'reload') {
6361: if ($context eq 'requestcourses') {
6362: return $env{'environment.canrequest.'.$tool};
6363: } elsif ($context eq 'requestauthor') {
6364: return $env{'environment.canrequest.author'};
6365: } else {
6366: return $env{'environment.availabletools.'.$tool};
6367: }
6368: }
6369: }
6370:
6371: my ($toolstatus,$inststatus,$envkey);
6372: if ($context eq 'requestauthor') {
6373: $envkey = $context;
6374: } else {
6375: $envkey = $context.'.'.$tool;
6376: }
6377:
6378: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
6379: ($action ne 'reload')) {
6380: $toolstatus = $env{'environment.'.$envkey};
6381: $inststatus = $env{'environment.inststatus'};
6382: } else {
6383: if (ref($userenvref) eq 'HASH') {
6384: $toolstatus = $userenvref->{$envkey};
6385: $inststatus = $userenvref->{'inststatus'};
6386: } else {
6387: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
6388: $toolstatus = $userenv{$envkey};
6389: $inststatus = $userenv{'inststatus'};
6390: }
6391: }
6392:
6393: if ($toolstatus ne '') {
6394: if ($toolstatus) {
6395: $access = 1;
6396: } else {
6397: $access = 0;
6398: }
6399: return $access;
6400: }
6401:
6402: my ($is_adv,%domdef);
6403: if (ref($is_advref) eq 'HASH') {
6404: $is_adv = $is_advref->{'is_adv'};
6405: } else {
6406: $is_adv = &is_advanced_user($udom,$uname);
6407: }
6408: if (ref($domdefref) eq 'HASH') {
6409: %domdef = %{$domdefref};
6410: } else {
6411: %domdef = &get_domain_defaults($udom);
6412: }
6413: if (ref($domdef{$tool}) eq 'HASH') {
6414: if ($is_adv) {
6415: if ($domdef{$tool}{'_LC_adv'} ne '') {
6416: if ($domdef{$tool}{'_LC_adv'}) {
6417: $access = 1;
6418: } else {
6419: $access = 0;
6420: }
6421: return $access;
6422: }
6423: }
6424: if ($inststatus ne '') {
6425: my ($hasaccess,$hasnoaccess);
6426: foreach my $affiliation (split(/:/,$inststatus)) {
6427: if ($domdef{$tool}{$affiliation} ne '') {
6428: if ($domdef{$tool}{$affiliation}) {
6429: $hasaccess = 1;
6430: } else {
6431: $hasnoaccess = 1;
6432: }
6433: }
6434: }
6435: if ($hasaccess || $hasnoaccess) {
6436: if ($hasaccess) {
6437: $access = 1;
6438: } elsif ($hasnoaccess) {
6439: $access = 0;
6440: }
6441: return $access;
6442: }
6443: } else {
6444: if ($domdef{$tool}{'default'} ne '') {
6445: if ($domdef{$tool}{'default'}) {
6446: $access = 1;
6447: } elsif ($domdef{$tool}{'default'} == 0) {
6448: $access = 0;
6449: }
6450: return $access;
6451: }
6452: }
6453: } else {
6454: if (($context eq 'tools') && ($tool ne 'webdav')) {
6455: $access = 1;
6456: } else {
6457: $access = 0;
6458: }
6459: return $access;
6460: }
6461: }
6462:
6463: sub is_course_owner {
6464: my ($cdom,$cnum,$udom,$uname) = @_;
6465: if (($udom eq '') || ($uname eq '')) {
6466: $udom = $env{'user.domain'};
6467: $uname = $env{'user.name'};
6468: }
6469: unless (($udom eq '') || ($uname eq '')) {
6470: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
6471: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
6472: return 1;
6473: } else {
6474: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
6475: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
6476: return 1;
6477: }
6478: }
6479: }
6480: }
6481: return;
6482: }
6483:
6484: sub is_advanced_user {
6485: my ($udom,$uname) = @_;
6486: if ($udom ne '' && $uname ne '') {
6487: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6488: if (wantarray) {
6489: return ($env{'user.adv'},$env{'user.author'});
6490: } else {
6491: return $env{'user.adv'};
6492: }
6493: }
6494: }
6495: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
6496: my %allroles;
6497: my ($is_adv,$is_author);
6498: foreach my $role (keys(%roleshash)) {
6499: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
6500: my $area = '/'.$tdomain.'/'.$trest;
6501: if ($sec ne '') {
6502: $area .= '/'.$sec;
6503: }
6504: if (($area ne '') && ($trole ne '')) {
6505: my $spec=$trole.'.'.$area;
6506: if ($trole =~ /^cr\//) {
6507: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6508: } elsif ($trole ne 'gr') {
6509: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6510: }
6511: if ($trole eq 'au') {
6512: $is_author = 1;
6513: }
6514: }
6515: }
6516: foreach my $role (keys(%allroles)) {
6517: last if ($is_adv);
6518: foreach my $item (split(/:/,$allroles{$role})) {
6519: if ($item ne '') {
6520: my ($privilege,$restrictions)=split(/&/,$item);
6521: if ($privilege eq 'adv') {
6522: $is_adv = 1;
6523: last;
6524: }
6525: }
6526: }
6527: }
6528: if (wantarray) {
6529: return ($is_adv,$is_author);
6530: }
6531: return $is_adv;
6532: }
6533:
6534: sub check_can_request {
6535: my ($dom,$can_request,$request_domains) = @_;
6536: my $canreq = 0;
6537: my ($types,$typename) = &Apache::loncommon::course_types();
6538: my @options = ('approval','validate','autolimit');
6539: my $optregex = join('|',@options);
6540: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
6541: foreach my $type (@{$types}) {
6542: if (&usertools_access($env{'user.name'},
6543: $env{'user.domain'},
6544: $type,undef,'requestcourses')) {
6545: $canreq ++;
6546: if (ref($request_domains) eq 'HASH') {
6547: push(@{$request_domains->{$type}},$env{'user.domain'});
6548: }
6549: if ($dom eq $env{'user.domain'}) {
6550: $can_request->{$type} = 1;
6551: }
6552: }
6553: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
6554: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
6555: if (@curr > 0) {
6556: foreach my $item (@curr) {
6557: if (ref($request_domains) eq 'HASH') {
6558: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
6559: if ($otherdom ne '') {
6560: if (ref($request_domains->{$type}) eq 'ARRAY') {
6561: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
6562: push(@{$request_domains->{$type}},$otherdom);
6563: }
6564: } else {
6565: push(@{$request_domains->{$type}},$otherdom);
6566: }
6567: }
6568: }
6569: }
6570: unless($dom eq $env{'user.domain'}) {
6571: $canreq ++;
6572: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
6573: $can_request->{$type} = 1;
6574: }
6575: }
6576: }
6577: }
6578: }
6579: }
6580: return $canreq;
6581: }
6582:
6583: # ---------------------------------------------- Custom access rule evaluation
6584:
6585: sub customaccess {
6586: my ($priv,$uri)=@_;
6587: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
6588: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
6589: $udom = &LONCAPA::clean_domain($udom);
6590: $ucrs = &LONCAPA::clean_username($ucrs);
6591: my $access=0;
6592: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
6593: my ($effect,$realm,$role,$type)=split(/\:/,$right);
6594: if ($type eq 'user') {
6595: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6596: my ($tdom,$tuname)=split(m{/},$scope);
6597: if ($tdom) {
6598: if ($tdom ne $env{'user.domain'}) { next; }
6599: }
6600: if ($tuname) {
6601: if ($tuname ne $env{'user.name'}) { next; }
6602: }
6603: $access=($effect eq 'allow');
6604: last;
6605: }
6606: } else {
6607: if ($role) {
6608: if ($role ne $urole) { next; }
6609: }
6610: foreach my $scope (split(/\s*\,\s*/,$realm)) {
6611: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
6612: if ($tdom) {
6613: if ($tdom ne $udom) { next; }
6614: }
6615: if ($tcrs) {
6616: if ($tcrs ne $ucrs) { next; }
6617: }
6618: if ($tsec) {
6619: if ($tsec ne $usec) { next; }
6620: }
6621: $access=($effect eq 'allow');
6622: last;
6623: }
6624: if ($realm eq '' && $role eq '') {
6625: $access=($effect eq 'allow');
6626: }
6627: }
6628: }
6629: return $access;
6630: }
6631:
6632: # ------------------------------------------------- Check for a user privilege
6633:
6634: sub allowed {
6635: my ($priv,$uri,$symb,$role,$clientip)=@_;
6636: my $ver_orguri=$uri;
6637: $uri=&deversion($uri);
6638: my $orguri=$uri;
6639: $uri=&declutter($uri);
6640:
6641: if ($priv eq 'evb') {
6642: # Evade communication block restrictions for specified role in a course
6643: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
6644: return $1;
6645: } else {
6646: return;
6647: }
6648: }
6649:
6650: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
6651: # Free bre access to adm and meta resources
6652: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
6653: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6654: && ($priv eq 'bre')) {
6655: return 'F';
6656: }
6657:
6658: # Free bre access to user's own portfolio contents
6659: my ($space,$domain,$name,@dir)=split('/',$uri);
6660: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
6661: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
6662: my %setters;
6663: my ($startblock,$endblock) =
6664: &Apache::loncommon::blockcheck(\%setters,'port');
6665: if ($startblock && $endblock) {
6666: return 'B';
6667: } else {
6668: return 'F';
6669: }
6670: }
6671:
6672: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
6673: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6674: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6675: if (exists($env{'request.course.id'})) {
6676: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6677: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6678: if (($domain eq $cdom) && ($name eq $cnum)) {
6679: my $courseprivid=$env{'request.course.id'};
6680: $courseprivid=~s/\_/\//;
6681: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6682: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6683: return $1;
6684: } else {
6685: if ($env{'request.course.sec'}) {
6686: $courseprivid.='/'.$env{'request.course.sec'};
6687: }
6688: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6689: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6690: return $2;
6691: }
6692: }
6693: }
6694: }
6695: }
6696:
6697: # Free bre to public access
6698:
6699: if ($priv eq 'bre') {
6700: my $copyright=&metadata($uri,'copyright');
6701: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
6702: return 'F';
6703: }
6704: if ($copyright eq 'priv') {
6705: $uri=~/([^\/]+)\/([^\/]+)\//;
6706: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
6707: return '';
6708: }
6709: }
6710: if ($copyright eq 'domain') {
6711: $uri=~/([^\/]+)\/([^\/]+)\//;
6712: unless (($env{'user.domain'} eq $1) ||
6713: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6714: return '';
6715: }
6716: }
6717: if ($env{'request.role'}=~ /li\.\//) {
6718: # Library role, so allow browsing of resources in this domain.
6719: return 'F';
6720: }
6721: if ($copyright eq 'custom') {
6722: unless (&customaccess($priv,$uri)) { return ''; }
6723: }
6724: }
6725: # Domain coordinator is trying to create a course
6726: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6727: # uri is the requested domain in this case.
6728: # comparison to 'request.role.domain' shows if the user has selected
6729: # a role of dc for the domain in question.
6730: return 'F' if ($uri eq $env{'request.role.domain'});
6731: }
6732:
6733: my $thisallowed='';
6734: my $statecond=0;
6735: my $courseprivid='';
6736:
6737: my $ownaccess;
6738: # Community Coordinator or Assistant Co-author browsing resource space.
6739: if (($priv eq 'bro') && ($env{'user.author'})) {
6740: if ($uri eq '') {
6741: $ownaccess = 1;
6742: } else {
6743: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6744: my $udom = $env{'user.domain'};
6745: my $uname = $env{'user.name'};
6746: if ($uri =~ m{^\Q$udom\E/?$}) {
6747: $ownaccess = 1;
6748: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6749: unless ($uri =~ m{\.\./}) {
6750: $ownaccess = 1;
6751: }
6752: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6753: my $now = time;
6754: if ($uri =~ m{^([^/]+)/?$}) {
6755: my $adom = $1;
6756: foreach my $key (keys(%env)) {
6757: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6758: my ($start,$end) = split('.',$env{$key});
6759: if (($now >= $start) && (!$end || $end < $now)) {
6760: $ownaccess = 1;
6761: last;
6762: }
6763: }
6764: }
6765: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6766: my $adom = $1;
6767: my $aname = $2;
6768: foreach my $role ('ca','aa') {
6769: if ($env{"user.role.$role./$adom/$aname"}) {
6770: my ($start,$end) =
6771: split('.',$env{"user.role.$role./$adom/$aname"});
6772: if (($now >= $start) && (!$end || $end < $now)) {
6773: $ownaccess = 1;
6774: last;
6775: }
6776: }
6777: }
6778: }
6779: }
6780: }
6781: }
6782: }
6783:
6784: # Course
6785:
6786: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6787: unless (($priv eq 'bro') && (!$ownaccess)) {
6788: $thisallowed.=$1;
6789: }
6790: }
6791:
6792: # Domain
6793:
6794: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6795: =~/\Q$priv\E\&([^\:]*)/) {
6796: unless (($priv eq 'bro') && (!$ownaccess)) {
6797: $thisallowed.=$1;
6798: }
6799: }
6800:
6801: # User who is not author or co-author might still be able to edit
6802: # resource of an author in the domain (e.g., if Domain Coordinator).
6803: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6804: (&allowed('mdc',$env{'request.course.id'}))) {
6805: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6806: $thisallowed.=$1;
6807: }
6808: }
6809:
6810: # Course: uri itself is a course
6811: my $courseuri=$uri;
6812: $courseuri=~s/\_(\d)/\/$1/;
6813: $courseuri=~s/^([^\/])/\/$1/;
6814:
6815: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6816: =~/\Q$priv\E\&([^\:]*)/) {
6817: unless (($priv eq 'bro') && (!$ownaccess)) {
6818: $thisallowed.=$1;
6819: }
6820: }
6821:
6822: # URI is an uploaded document for this course, default permissions don't matter
6823: # not allowing 'edit' access (editupload) to uploaded course docs
6824: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6825: $thisallowed='';
6826: my ($match)=&is_on_map($uri);
6827: if ($match) {
6828: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6829: =~/\Q$priv\E\&([^\:]*)/) {
6830: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6831: if (@blockers > 0) {
6832: $thisallowed = 'B';
6833: } else {
6834: $thisallowed.=$1;
6835: }
6836: }
6837: } else {
6838: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6839: if ($refuri) {
6840: if ($refuri =~ m|^/adm/|) {
6841: $thisallowed='F';
6842: } else {
6843: $refuri=&declutter($refuri);
6844: my ($match) = &is_on_map($refuri);
6845: if ($match) {
6846: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6847: if (@blockers > 0) {
6848: $thisallowed = 'B';
6849: } else {
6850: $thisallowed='F';
6851: }
6852: }
6853: }
6854: }
6855: }
6856: }
6857:
6858: if ($priv eq 'bre'
6859: && $thisallowed ne 'F'
6860: && $thisallowed ne '2'
6861: && &is_portfolio_url($uri)) {
6862: $thisallowed = &portfolio_access($uri,$clientip);
6863: }
6864:
6865: # Full access at system, domain or course-wide level? Exit.
6866: if ($thisallowed=~/F/) {
6867: return 'F';
6868: }
6869:
6870: # If this is generating or modifying users, exit with special codes
6871:
6872: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6873: if (($priv eq 'cca') || ($priv eq 'caa')) {
6874: my ($audom,$auname)=split('/',$uri);
6875: # no author name given, so this just checks on the general right to make a co-author in this domain
6876: unless ($auname) { return $thisallowed; }
6877: # an author name is given, so we are about to actually make a co-author for a certain account
6878: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6879: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6880: ($audom ne $env{'request.role.domain'}))) { return ''; }
6881: }
6882: return $thisallowed;
6883: }
6884: #
6885: # Gathered so far: system, domain and course wide privileges
6886: #
6887: # Course: See if uri or referer is an individual resource that is part of
6888: # the course
6889:
6890: if ($env{'request.course.id'}) {
6891:
6892: $courseprivid=$env{'request.course.id'};
6893: if ($env{'request.course.sec'}) {
6894: $courseprivid.='/'.$env{'request.course.sec'};
6895: }
6896: $courseprivid=~s/\_/\//;
6897: my $checkreferer=1;
6898: my ($match,$cond)=&is_on_map($uri);
6899: if ($match) {
6900: $statecond=$cond;
6901: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6902: =~/\Q$priv\E\&([^\:]*)/) {
6903: my $value = $1;
6904: if ($priv eq 'bre') {
6905: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6906: if (@blockers > 0) {
6907: $thisallowed = 'B';
6908: } else {
6909: $thisallowed.=$value;
6910: }
6911: } else {
6912: $thisallowed.=$value;
6913: }
6914: $checkreferer=0;
6915: }
6916: }
6917:
6918: if ($checkreferer) {
6919: my $refuri=$env{'httpref.'.$orguri};
6920: unless ($refuri) {
6921: foreach my $key (keys(%env)) {
6922: if ($key=~/^httpref\..*\*/) {
6923: my $pattern=$key;
6924: $pattern=~s/^httpref\.\/res\///;
6925: $pattern=~s/\*/\[\^\/\]\+/g;
6926: $pattern=~s/\//\\\//g;
6927: if ($orguri=~/$pattern/) {
6928: $refuri=$env{$key};
6929: }
6930: }
6931: }
6932: }
6933:
6934: if ($refuri) {
6935: $refuri=&declutter($refuri);
6936: my ($match,$cond)=&is_on_map($refuri);
6937: if ($match) {
6938: my $refstatecond=$cond;
6939: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6940: =~/\Q$priv\E\&([^\:]*)/) {
6941: my $value = $1;
6942: if ($priv eq 'bre') {
6943: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6944: if (@blockers > 0) {
6945: $thisallowed = 'B';
6946: } else {
6947: $thisallowed.=$value;
6948: }
6949: } else {
6950: $thisallowed.=$value;
6951: }
6952: $uri=$refuri;
6953: $statecond=$refstatecond;
6954: }
6955: }
6956: }
6957: }
6958: }
6959:
6960: #
6961: # Gathered now: all privileges that could apply, and condition number
6962: #
6963: #
6964: # Full or no access?
6965: #
6966:
6967: if ($thisallowed=~/F/) {
6968: return 'F';
6969: }
6970:
6971: unless ($thisallowed) {
6972: return '';
6973: }
6974:
6975: # Restrictions exist, deal with them
6976: #
6977: # C:according to course preferences
6978: # R:according to resource settings
6979: # L:unless locked
6980: # X:according to user session state
6981: #
6982:
6983: # Possibly locked functionality, check all courses
6984: # Locks might take effect only after 10 minutes cache expiration for other
6985: # courses, and 2 minutes for current course
6986:
6987: my $envkey;
6988: if ($thisallowed=~/L/) {
6989: foreach $envkey (keys(%env)) {
6990: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6991: my $courseid=$2;
6992: my $roleid=$1.'.'.$2;
6993: $courseid=~s/^\///;
6994: my $expiretime=600;
6995: if ($env{'request.role'} eq $roleid) {
6996: $expiretime=120;
6997: }
6998: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6999: my $prefix='course.'.$cdom.'_'.$cnum.'.';
7000: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
7001: &coursedescription($courseid,{'freshen_cache' => 1});
7002: }
7003: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
7004: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
7005: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
7006: &log($env{'user.domain'},$env{'user.name'},
7007: $env{'user.home'},
7008: 'Locked by res: '.$priv.' for '.$uri.' due to '.
7009: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7010: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7011: return '';
7012: }
7013: }
7014: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
7015: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
7016: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
7017: &log($env{'user.domain'},$env{'user.name'},
7018: $env{'user.home'},
7019: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
7020: $cdom.'/'.$cnum.'/'.$csec.' expire '.
7021: $env{$prefix.'priv.'.$priv.'.lock.expire'});
7022: return '';
7023: }
7024: }
7025: }
7026: }
7027: }
7028:
7029: #
7030: # Rest of the restrictions depend on selected course
7031: #
7032:
7033: unless ($env{'request.course.id'}) {
7034: if ($thisallowed eq 'A') {
7035: return 'A';
7036: } elsif ($thisallowed eq 'B') {
7037: return 'B';
7038: } else {
7039: return '1';
7040: }
7041: }
7042:
7043: #
7044: # Now user is definitely in a course
7045: #
7046:
7047:
7048: # Course preferences
7049:
7050: if ($thisallowed=~/C/) {
7051: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7052: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
7053: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
7054: =~/\Q$rolecode\E/) {
7055: if (($priv ne 'pch') && ($priv ne 'plc')) {
7056: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7057: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
7058: $env{'request.course.id'});
7059: }
7060: return '';
7061: }
7062:
7063: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
7064: =~/\Q$unamedom\E/) {
7065: if (($priv ne 'pch') && ($priv ne 'plc')) {
7066: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
7067: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
7068: $env{'request.course.id'});
7069: }
7070: return '';
7071: }
7072: }
7073:
7074: # Resource preferences
7075:
7076: if ($thisallowed=~/R/) {
7077: my $rolecode=(split(/\./,$env{'request.role'}))[0];
7078: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
7079: if (($priv ne 'pch') && ($priv ne 'plc')) {
7080: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
7081: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
7082: }
7083: return '';
7084: }
7085: }
7086:
7087: # Restricted by state or randomout?
7088:
7089: if ($thisallowed=~/X/) {
7090: if ($env{'acc.randomout'}) {
7091: if (!$symb) { $symb=&symbread($uri,1); }
7092: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
7093: return '';
7094: }
7095: }
7096: if (&condval($statecond)) {
7097: return '2';
7098: } else {
7099: return '';
7100: }
7101: }
7102:
7103: if ($thisallowed eq 'A') {
7104: return 'A';
7105: } elsif ($thisallowed eq 'B') {
7106: return 'B';
7107: }
7108: return 'F';
7109: }
7110:
7111: # ------------------------------------------- Check construction space access
7112:
7113: sub constructaccess {
7114: my ($url,$setpriv)=@_;
7115:
7116: # We do not allow editing of previous versions of files
7117: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
7118:
7119: # Get username and domain from URL
7120: my ($ownername,$ownerdomain,$ownerhome);
7121:
7122: ($ownerdomain,$ownername) =
7123: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)/});
7124:
7125: # The URL does not really point to any authorspace, forget it
7126: unless (($ownername) && ($ownerdomain)) { return ''; }
7127:
7128: # Now we need to see if the user has access to the authorspace of
7129: # $ownername at $ownerdomain
7130:
7131: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
7132: # Real author for this?
7133: $ownerhome = $env{'user.home'};
7134: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
7135: return ($ownername,$ownerdomain,$ownerhome);
7136: }
7137: } else {
7138: # Co-author for this?
7139: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
7140: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
7141: $ownerhome = &homeserver($ownername,$ownerdomain);
7142: return ($ownername,$ownerdomain,$ownerhome);
7143: }
7144: }
7145:
7146: # We don't have any access right now. If we are not possibly going to do anything about this,
7147: # we might as well leave
7148: unless ($setpriv) { return ''; }
7149:
7150: # Backdoor access?
7151: my $allowed=&allowed('eco',$ownerdomain);
7152: # Nope
7153: unless ($allowed) { return ''; }
7154: # Looks like we may have access, but could be locked by the owner of the construction space
7155: if ($allowed eq 'U') {
7156: my %blocked=&get('environment',['domcoord.author'],
7157: $ownerdomain,$ownername);
7158: # Is blocked by owner
7159: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
7160: }
7161: if (($allowed eq 'F') || ($allowed eq 'U')) {
7162: # Grant temporary access
7163: my $then=$env{'user.login.time'};
7164: my $update=$env{'user.update.time'};
7165: if (!$update) { $update = $then; }
7166: my $refresh=$env{'user.refresh.time'};
7167: if (!$refresh) { $refresh = $update; }
7168: my $now = time;
7169: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
7170: $now,'ca','constructaccess');
7171: $ownerhome = &homeserver($ownername,$ownerdomain);
7172: return($ownername,$ownerdomain,$ownerhome);
7173: }
7174: # No business here
7175: return '';
7176: }
7177:
7178: sub get_comm_blocks {
7179: my ($cdom,$cnum) = @_;
7180: if ($cdom eq '' || $cnum eq '') {
7181: return unless ($env{'request.course.id'});
7182: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7183: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7184: }
7185: my %commblocks;
7186: my $hashid=$cdom.'_'.$cnum;
7187: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
7188: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
7189: %commblocks = %{$blocksref};
7190: } else {
7191: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
7192: my $cachetime = 600;
7193: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
7194: }
7195: return %commblocks;
7196: }
7197:
7198: sub has_comm_blocking {
7199: my ($priv,$symb,$uri,$blocks) = @_;
7200: return unless ($env{'request.course.id'});
7201: return unless ($priv eq 'bre');
7202: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
7203: my %commblocks;
7204: if (ref($blocks) eq 'HASH') {
7205: %commblocks = %{$blocks};
7206: } else {
7207: %commblocks = &get_comm_blocks();
7208: }
7209: return unless (keys(%commblocks) > 0);
7210: if (!$symb) { $symb=&symbread($uri,1); }
7211: my ($map,$resid,undef)=&decode_symb($symb);
7212: my %tocheck = (
7213: maps => $map,
7214: resources => $symb,
7215: );
7216: my @blockers;
7217: my $now = time;
7218: my $navmap = Apache::lonnavmaps::navmap->new();
7219: foreach my $block (keys(%commblocks)) {
7220: if ($block =~ /^(\d+)____(\d+)$/) {
7221: my ($start,$end) = ($1,$2);
7222: if ($start <= $now && $end >= $now) {
7223: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7224: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7225: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
7226: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
7227: unless (grep(/^\Q$block\E$/,@blockers)) {
7228: push(@blockers,$block);
7229: }
7230: }
7231: }
7232: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
7233: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
7234: unless (grep(/^\Q$block\E$/,@blockers)) {
7235: push(@blockers,$block);
7236: }
7237: }
7238: }
7239: }
7240: }
7241: }
7242: } elsif ($block =~ /^firstaccess____(.+)$/) {
7243: my $item = $1;
7244: my @to_test;
7245: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
7246: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
7247: my $check_interval;
7248: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
7249: my @interval;
7250: my $type = 'map';
7251: if ($item eq 'course') {
7252: $type = 'course';
7253: @interval=&EXT("resource.0.interval");
7254: } else {
7255: if ($item =~ /___\d+___/) {
7256: $type = 'resource';
7257: @interval=&EXT("resource.0.interval",$item);
7258: if (ref($navmap)) {
7259: my $res = $navmap->getBySymb($item);
7260: push(@to_test,$res);
7261: }
7262: } else {
7263: my $mapsymb = &symbread($item,1);
7264: if ($mapsymb) {
7265: if (ref($navmap)) {
7266: my $mapres = $navmap->getBySymb($mapsymb);
7267: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
7268: foreach my $res (@to_test) {
7269: my $symb = $res->symb();
7270: next if ($symb eq $mapsymb);
7271: if ($symb ne '') {
7272: @interval=&EXT("resource.0.interval",$symb);
7273: last;
7274: }
7275: }
7276: }
7277: }
7278: }
7279: }
7280: if ($interval[0] =~ /\d+/) {
7281: my $first_access;
7282: if ($type eq 'resource') {
7283: $first_access=&get_first_access($interval[1],$item);
7284: } elsif ($type eq 'map') {
7285: $first_access=&get_first_access($interval[1],undef,$item);
7286: } else {
7287: $first_access=&get_first_access($interval[1]);
7288: }
7289: if ($first_access) {
7290: my $timesup = $first_access+$interval[0];
7291: if ($timesup > $now) {
7292: foreach my $res (@to_test) {
7293: if ($res->is_problem()) {
7294: if ($res->completable()) {
7295: unless (grep(/^\Q$block\E$/,@blockers)) {
7296: push(@blockers,$block);
7297: }
7298: last;
7299: }
7300: }
7301: }
7302: }
7303: }
7304: }
7305: }
7306: }
7307: }
7308: }
7309: }
7310: return @blockers;
7311: }
7312:
7313: sub check_docs_block {
7314: my ($docsblock,$tocheck) =@_;
7315: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
7316: return;
7317: }
7318: if (ref($docsblock->{'maps'}) eq 'HASH') {
7319: if ($tocheck->{'maps'}) {
7320: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
7321: return 1;
7322: }
7323: }
7324: }
7325: if (ref($docsblock->{'resources'}) eq 'HASH') {
7326: if ($tocheck->{'resources'}) {
7327: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
7328: return 1;
7329: }
7330: }
7331: }
7332: return;
7333: }
7334:
7335: #
7336: # Removes the versino from a URI and
7337: # splits it in to its filename and path to the filename.
7338: # Seems like File::Basename could have done this more clearly.
7339: # Parameters:
7340: # $uri - input URI
7341: # Returns:
7342: # Two element list consisting of
7343: # $pathname - the URI up to and excluding the trailing /
7344: # $filename - The part of the URI following the last /
7345: # NOTE:
7346: # Another realization of this is simply:
7347: # use File::Basename;
7348: # ...
7349: # $uri = shift;
7350: # $filename = basename($uri);
7351: # $path = dirname($uri);
7352: # return ($filename, $path);
7353: #
7354: # The implementation below is probably faster however.
7355: #
7356: sub split_uri_for_cond {
7357: my $uri=&deversion(&declutter(shift));
7358: my @uriparts=split(/\//,$uri);
7359: my $filename=pop(@uriparts);
7360: my $pathname=join('/',@uriparts);
7361: return ($pathname,$filename);
7362: }
7363: # --------------------------------------------------- Is a resource on the map?
7364:
7365: sub is_on_map {
7366: my ($pathname,$filename) = &split_uri_for_cond(shift);
7367: #Trying to find the conditional for the file
7368: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
7369: /\&\Q$filename\E\:([\d\|]+)\&/);
7370: if ($match) {
7371: return (1,$1);
7372: } else {
7373: return (0,0);
7374: }
7375: }
7376:
7377: # --------------------------------------------------------- Get symb from alias
7378:
7379: sub get_symb_from_alias {
7380: my $symb=shift;
7381: my ($map,$resid,$url)=&decode_symb($symb);
7382: # Already is a symb
7383: if ($url) { return $symb; }
7384: # Must be an alias
7385: my $aliassymb='';
7386: my %bighash;
7387: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7388: &GDBM_READER(),0640)) {
7389: my $rid=$bighash{'mapalias_'.$symb};
7390: if ($rid) {
7391: my ($mapid,$resid)=split(/\./,$rid);
7392: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
7393: $resid,$bighash{'src_'.$rid});
7394: }
7395: untie %bighash;
7396: }
7397: return $aliassymb;
7398: }
7399:
7400: # ----------------------------------------------------------------- Define Role
7401:
7402: sub definerole {
7403: if (allowed('mcr','/')) {
7404: my ($rolename,$sysrole,$domrole,$courole)=@_;
7405: foreach my $role (split(':',$sysrole)) {
7406: my ($crole,$cqual)=split(/\&/,$role);
7407: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
7408: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
7409: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7410: return "refused:s:$crole&$cqual";
7411: }
7412: }
7413: }
7414: foreach my $role (split(':',$domrole)) {
7415: my ($crole,$cqual)=split(/\&/,$role);
7416: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
7417: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
7418: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
7419: return "refused:d:$crole&$cqual";
7420: }
7421: }
7422: }
7423: foreach my $role (split(':',$courole)) {
7424: my ($crole,$cqual)=split(/\&/,$role);
7425: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
7426: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
7427: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
7428: return "refused:c:$crole&$cqual";
7429: }
7430: }
7431: }
7432: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7433: "$env{'user.domain'}:$env{'user.name'}:".
7434: "rolesdef_$rolename=".
7435: escape($sysrole.'_'.$domrole.'_'.$courole);
7436: return reply($command,$env{'user.home'});
7437: } else {
7438: return 'refused';
7439: }
7440: }
7441:
7442: # ---------------- Make a metadata query against the network of library servers
7443:
7444: sub metadata_query {
7445: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
7446: my %rhash;
7447: my %libserv = &all_library();
7448: my @server_list = (defined($server_array) ? @$server_array
7449: : keys(%libserv) );
7450: for my $server (@server_list) {
7451: my $domains = '';
7452: if (ref($domains_hash) eq 'HASH') {
7453: $domains = $domains_hash->{$server};
7454: }
7455: unless ($custom or $customshow) {
7456: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
7457: $rhash{$server}=$reply;
7458: }
7459: else {
7460: my $reply=&reply("querysend:".&escape($query).':'.
7461: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
7462: $server);
7463: $rhash{$server}=$reply;
7464: }
7465: }
7466: return \%rhash;
7467: }
7468:
7469: # ----------------------------------------- Send log queries and wait for reply
7470:
7471: sub log_query {
7472: my ($uname,$udom,$query,%filters)=@_;
7473: my $uhome=&homeserver($uname,$udom);
7474: if ($uhome eq 'no_host') { return 'error: no_host'; }
7475: my $uhost=&hostname($uhome);
7476: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
7477: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
7478: $uhome);
7479: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
7480: return get_query_reply($queryid);
7481: }
7482:
7483: # -------------------------- Update MySQL table for portfolio file
7484:
7485: sub update_portfolio_table {
7486: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
7487: if ($group ne '') {
7488: $file_name =~s /^\Q$group\E//;
7489: }
7490: my $homeserver = &homeserver($uname,$udom);
7491: my $queryid=
7492: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
7493: ':'.&escape($file_name).':'.$action,$homeserver);
7494: my $reply = &get_query_reply($queryid);
7495: return $reply;
7496: }
7497:
7498: # -------------------------- Update MySQL allusers table
7499:
7500: sub update_allusers_table {
7501: my ($uname,$udom,$names) = @_;
7502: my $homeserver = &homeserver($uname,$udom);
7503: my $queryid=
7504: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
7505: 'lastname='.&escape($names->{'lastname'}).'%%'.
7506: 'firstname='.&escape($names->{'firstname'}).'%%'.
7507: 'middlename='.&escape($names->{'middlename'}).'%%'.
7508: 'generation='.&escape($names->{'generation'}).'%%'.
7509: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
7510: 'id='.&escape($names->{'id'}),$homeserver);
7511: return;
7512: }
7513:
7514: # ------- Request retrieval of institutional classlists for course(s)
7515:
7516: sub fetch_enrollment_query {
7517: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
7518: my $homeserver;
7519: my $maxtries = 1;
7520: if ($context eq 'automated') {
7521: $homeserver = $perlvar{'lonHostID'};
7522: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
7523: } else {
7524: $homeserver = &homeserver($cnum,$dom);
7525: }
7526: my $host=&hostname($homeserver);
7527: my $cmd = '';
7528: foreach my $affiliate (keys(%{$affiliatesref})) {
7529: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7530: }
7531: $cmd =~ s/%%$//;
7532: $cmd = &escape($cmd);
7533: my $query = 'fetchenrollment';
7534: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
7535: unless ($queryid=~/^\Q$host\E\_/) {
7536: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
7537: return 'error: '.$queryid;
7538: }
7539: my $reply = &get_query_reply($queryid);
7540: my $tries = 1;
7541: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7542: $reply = &get_query_reply($queryid);
7543: $tries ++;
7544: }
7545: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7546: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7547: } else {
7548: my @responses = split(/:/,$reply);
7549: if ($homeserver eq $perlvar{'lonHostID'}) {
7550: foreach my $line (@responses) {
7551: my ($key,$value) = split(/=/,$line,2);
7552: $$replyref{$key} = $value;
7553: }
7554: } else {
7555: my $pathname = LONCAPA::tempdir();
7556: foreach my $line (@responses) {
7557: my ($key,$value) = split(/=/,$line);
7558: $$replyref{$key} = $value;
7559: if ($value > 0) {
7560: foreach my $item (@{$$affiliatesref{$key}}) {
7561: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
7562: my $destname = $pathname.'/'.$filename;
7563: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
7564: if ($xml_classlist =~ /^error/) {
7565: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
7566: } else {
7567: if ( open(FILE,">$destname") ) {
7568: print FILE &unescape($xml_classlist);
7569: close(FILE);
7570: } else {
7571: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
7572: }
7573: }
7574: }
7575: }
7576: }
7577: }
7578: return 'ok';
7579: }
7580: return 'error';
7581: }
7582:
7583: sub get_query_reply {
7584: my $queryid=shift;
7585: my $replyfile=LONCAPA::tempdir().$queryid;
7586: my $reply='';
7587: for (1..100) {
7588: sleep 2;
7589: if (-e $replyfile.'.end') {
7590: if (open(my $fh,$replyfile)) {
7591: $reply = join('',<$fh>);
7592: close($fh);
7593: } else { return 'error: reply_file_error'; }
7594: return &unescape($reply);
7595: }
7596: }
7597: return 'timeout:'.$queryid;
7598: }
7599:
7600: sub courselog_query {
7601: #
7602: # possible filters:
7603: # url: url or symb
7604: # username
7605: # domain
7606: # action: view, submit, grade
7607: # start: timestamp
7608: # end: timestamp
7609: #
7610: my (%filters)=@_;
7611: unless ($env{'request.course.id'}) { return 'no_course'; }
7612: if ($filters{'url'}) {
7613: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
7614: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
7615: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
7616: }
7617: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
7618: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
7619: return &log_query($cname,$cdom,'courselog',%filters);
7620: }
7621:
7622: sub userlog_query {
7623: #
7624: # possible filters:
7625: # action: log check role
7626: # start: timestamp
7627: # end: timestamp
7628: #
7629: my ($uname,$udom,%filters)=@_;
7630: return &log_query($uname,$udom,'userlog',%filters);
7631: }
7632:
7633: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
7634:
7635: sub auto_run {
7636: my ($cnum,$cdom) = @_;
7637: my $response = 0;
7638: my $settings;
7639: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
7640: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
7641: $settings = $domconfig{'autoenroll'};
7642: if ($settings->{'run'} eq '1') {
7643: $response = 1;
7644: }
7645: } else {
7646: my $homeserver;
7647: if (&is_course($cdom,$cnum)) {
7648: $homeserver = &homeserver($cnum,$cdom);
7649: } else {
7650: $homeserver = &domain($cdom,'primary');
7651: }
7652: if ($homeserver ne 'no_host') {
7653: $response = &reply('autorun:'.$cdom,$homeserver);
7654: }
7655: }
7656: return $response;
7657: }
7658:
7659: sub auto_get_sections {
7660: my ($cnum,$cdom,$inst_coursecode) = @_;
7661: my $homeserver;
7662: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7663: $homeserver = &homeserver($cnum,$cdom);
7664: }
7665: if (!defined($homeserver)) {
7666: if ($cdom =~ /^$match_domain$/) {
7667: $homeserver = &domain($cdom,'primary');
7668: }
7669: }
7670: my @secs;
7671: if (defined($homeserver)) {
7672: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
7673: unless ($response eq 'refused') {
7674: @secs = split(/:/,$response);
7675: }
7676: }
7677: return @secs;
7678: }
7679:
7680: sub auto_new_course {
7681: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
7682: my $homeserver = &homeserver($cnum,$cdom);
7683: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
7684: return $response;
7685: }
7686:
7687: sub auto_validate_courseID {
7688: my ($cnum,$cdom,$inst_course_id) = @_;
7689: my $homeserver = &homeserver($cnum,$cdom);
7690: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
7691: return $response;
7692: }
7693:
7694: sub auto_validate_instcode {
7695: my ($cnum,$cdom,$instcode,$owner) = @_;
7696: my ($homeserver,$response);
7697: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7698: $homeserver = &homeserver($cnum,$cdom);
7699: }
7700: if (!defined($homeserver)) {
7701: if ($cdom =~ /^$match_domain$/) {
7702: $homeserver = &domain($cdom,'primary');
7703: }
7704: }
7705: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
7706: &escape($instcode).':'.&escape($owner),$homeserver));
7707: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
7708: return ($outcome,$description,$defaultcredits);
7709: }
7710:
7711: sub auto_create_password {
7712: my ($cnum,$cdom,$authparam,$udom) = @_;
7713: my ($homeserver,$response);
7714: my $create_passwd = 0;
7715: my $authchk = '';
7716: if ($udom =~ /^$match_domain$/) {
7717: $homeserver = &domain($udom,'primary');
7718: }
7719: if ($homeserver eq '') {
7720: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
7721: $homeserver = &homeserver($cnum,$cdom);
7722: }
7723: }
7724: if ($homeserver eq '') {
7725: $authchk = 'nodomain';
7726: } else {
7727: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7728: if ($response eq 'refused') {
7729: $authchk = 'refused';
7730: } else {
7731: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
7732: }
7733: }
7734: return ($authparam,$create_passwd,$authchk);
7735: }
7736:
7737: sub auto_photo_permission {
7738: my ($cnum,$cdom,$students) = @_;
7739: my $homeserver = &homeserver($cnum,$cdom);
7740: my ($outcome,$perm_reqd,$conditions) =
7741: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
7742: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7743: return (undef,undef);
7744: }
7745: return ($outcome,$perm_reqd,$conditions);
7746: }
7747:
7748: sub auto_checkphotos {
7749: my ($uname,$udom,$pid) = @_;
7750: my $homeserver = &homeserver($uname,$udom);
7751: my ($result,$resulttype);
7752: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
7753: &escape($uname).':'.&escape($pid),
7754: $homeserver));
7755: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7756: return (undef,undef);
7757: }
7758: if ($outcome) {
7759: ($result,$resulttype) = split(/:/,$outcome);
7760: }
7761: return ($result,$resulttype);
7762: }
7763:
7764: sub auto_photochoice {
7765: my ($cnum,$cdom) = @_;
7766: my $homeserver = &homeserver($cnum,$cdom);
7767: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
7768: &escape($cdom),
7769: $homeserver)));
7770: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7771: return (undef,undef);
7772: }
7773: return ($update,$comment);
7774: }
7775:
7776: sub auto_photoupdate {
7777: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7778: my $homeserver = &homeserver($cnum,$dom);
7779: my $host=&hostname($homeserver);
7780: my $cmd = '';
7781: my $maxtries = 1;
7782: foreach my $affiliate (keys(%{$affiliatesref})) {
7783: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7784: }
7785: $cmd =~ s/%%$//;
7786: $cmd = &escape($cmd);
7787: my $query = 'institutionalphotos';
7788: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7789: unless ($queryid=~/^\Q$host\E\_/) {
7790: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7791: return 'error: '.$queryid;
7792: }
7793: my $reply = &get_query_reply($queryid);
7794: my $tries = 1;
7795: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7796: $reply = &get_query_reply($queryid);
7797: $tries ++;
7798: }
7799: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7800: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7801: } else {
7802: my @responses = split(/:/,$reply);
7803: my $outcome = shift(@responses);
7804: foreach my $item (@responses) {
7805: my ($key,$value) = split(/=/,$item);
7806: $$photo{$key} = $value;
7807: }
7808: return $outcome;
7809: }
7810: return 'error';
7811: }
7812:
7813: sub auto_instcode_format {
7814: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7815: $cat_order) = @_;
7816: my $courses = '';
7817: my @homeservers;
7818: if ($caller eq 'global') {
7819: my %servers = &get_servers($codedom,'library');
7820: foreach my $tryserver (keys(%servers)) {
7821: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7822: push(@homeservers,$tryserver);
7823: }
7824: }
7825: } elsif ($caller eq 'requests') {
7826: if ($codedom =~ /^$match_domain$/) {
7827: my $chome = &domain($codedom,'primary');
7828: unless ($chome eq 'no_host') {
7829: push(@homeservers,$chome);
7830: }
7831: }
7832: } else {
7833: push(@homeservers,&homeserver($caller,$codedom));
7834: }
7835: foreach my $code (keys(%{$instcodes})) {
7836: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7837: }
7838: chop($courses);
7839: my $ok_response = 0;
7840: my $response;
7841: while (@homeservers > 0 && $ok_response == 0) {
7842: my $server = shift(@homeservers);
7843: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7844: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7845: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7846: split(/:/,$response);
7847: %{$codes} = (%{$codes},&str2hash($codes_str));
7848: push(@{$codetitles},&str2array($codetitles_str));
7849: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7850: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7851: $ok_response = 1;
7852: }
7853: }
7854: if ($ok_response) {
7855: return 'ok';
7856: } else {
7857: return $response;
7858: }
7859: }
7860:
7861: sub auto_instcode_defaults {
7862: my ($domain,$returnhash,$code_order) = @_;
7863: my @homeservers;
7864:
7865: my %servers = &get_servers($domain,'library');
7866: foreach my $tryserver (keys(%servers)) {
7867: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7868: push(@homeservers,$tryserver);
7869: }
7870: }
7871:
7872: my $response;
7873: foreach my $server (@homeservers) {
7874: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7875: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7876:
7877: foreach my $pair (split(/\&/,$response)) {
7878: my ($name,$value)=split(/\=/,$pair);
7879: if ($name eq 'code_order') {
7880: @{$code_order} = split(/\&/,&unescape($value));
7881: } else {
7882: $returnhash->{&unescape($name)}=&unescape($value);
7883: }
7884: }
7885: return 'ok';
7886: }
7887:
7888: return $response;
7889: }
7890:
7891: sub auto_possible_instcodes {
7892: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7893: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7894: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7895: return;
7896: }
7897: my (@homeservers,$uhome);
7898: if (defined(&domain($domain,'primary'))) {
7899: $uhome=&domain($domain,'primary');
7900: push(@homeservers,&domain($domain,'primary'));
7901: } else {
7902: my %servers = &get_servers($domain,'library');
7903: foreach my $tryserver (keys(%servers)) {
7904: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7905: push(@homeservers,$tryserver);
7906: }
7907: }
7908: }
7909: my $response;
7910: foreach my $server (@homeservers) {
7911: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7912: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7913: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7914: split(':',$response);
7915: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7916: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7917: foreach my $item (split('&',$cat_title)) {
7918: my ($name,$value)=split('=',$item);
7919: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7920: }
7921: foreach my $item (split('&',$cat_order)) {
7922: my ($name,$value)=split('=',$item);
7923: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7924: }
7925: return 'ok';
7926: }
7927: return $response;
7928: }
7929:
7930: sub auto_courserequest_checks {
7931: my ($dom) = @_;
7932: my ($homeserver,%validations);
7933: if ($dom =~ /^$match_domain$/) {
7934: $homeserver = &domain($dom,'primary');
7935: }
7936: unless ($homeserver eq 'no_host') {
7937: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7938: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7939: my @items = split(/&/,$response);
7940: foreach my $item (@items) {
7941: my ($key,$value) = split('=',$item);
7942: $validations{&unescape($key)} = &thaw_unescape($value);
7943: }
7944: }
7945: }
7946: return %validations;
7947: }
7948:
7949: sub auto_courserequest_validation {
7950: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
7951: my ($homeserver,$response);
7952: if ($dom =~ /^$match_domain$/) {
7953: $homeserver = &domain($dom,'primary');
7954: }
7955: unless ($homeserver eq 'no_host') {
7956: my $customdata;
7957: if (ref($custominfo) eq 'HASH') {
7958: $customdata = &freeze_escape($custominfo);
7959: }
7960: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7961: ':'.&escape($crstype).':'.&escape($inststatuslist).
7962: ':'.&escape($instcode).':'.&escape($instseclist).':'.
7963: $customdata,$homeserver));
7964: }
7965: return $response;
7966: }
7967:
7968: sub auto_validate_class_sec {
7969: my ($cdom,$cnum,$owners,$inst_class) = @_;
7970: my $homeserver = &homeserver($cnum,$cdom);
7971: my $ownerlist;
7972: if (ref($owners) eq 'ARRAY') {
7973: $ownerlist = join(',',@{$owners});
7974: } else {
7975: $ownerlist = $owners;
7976: }
7977: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7978: &escape($ownerlist).':'.$cdom,$homeserver);
7979: return $response;
7980: }
7981:
7982: sub auto_crsreq_update {
7983: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
7984: $code,$accessstart,$accessend,$inbound) = @_;
7985: my ($homeserver,%crsreqresponse);
7986: if ($cdom =~ /^$match_domain$/) {
7987: $homeserver = &domain($cdom,'primary');
7988: }
7989: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
7990: my $info;
7991: if (ref($inbound) eq 'HASH') {
7992: $info = &freeze_escape($inbound);
7993: }
7994: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
7995: ':'.&escape($action).':'.&escape($ownername).':'.
7996: &escape($ownerdomain).':'.&escape($fullname).':'.
7997: &escape($title).':'.&escape($code).':'.
7998: &escape($accessstart).':'.&escape($accessend).':'.$info,
7999: $homeserver);
8000: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
8001: my @items = split(/&/,$response);
8002: foreach my $item (@items) {
8003: my ($key,$value) = split('=',$item);
8004: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
8005: }
8006: }
8007: }
8008: return \%crsreqresponse;
8009: }
8010:
8011: # ------------------------------------------------------- Course Group routines
8012:
8013: sub get_coursegroups {
8014: my ($cdom,$cnum,$group,$namespace) = @_;
8015: return(&dump($namespace,$cdom,$cnum,$group));
8016: }
8017:
8018: sub modify_coursegroup {
8019: my ($cdom,$cnum,$groupsettings) = @_;
8020: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
8021: }
8022:
8023: sub toggle_coursegroup_status {
8024: my ($cdom,$cnum,$group,$action) = @_;
8025: my ($from_namespace,$to_namespace);
8026: if ($action eq 'delete') {
8027: $from_namespace = 'coursegroups';
8028: $to_namespace = 'deleted_groups';
8029: } else {
8030: $from_namespace = 'deleted_groups';
8031: $to_namespace = 'coursegroups';
8032: }
8033: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
8034: if (my $tmp = &error(%curr_group)) {
8035: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
8036: return ('read error',$tmp);
8037: } else {
8038: my %savedsettings = %curr_group;
8039: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
8040: my $deloutcome;
8041: if ($result eq 'ok') {
8042: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
8043: } else {
8044: return ('write error',$result);
8045: }
8046: if ($deloutcome eq 'ok') {
8047: return 'ok';
8048: } else {
8049: return ('delete error',$deloutcome);
8050: }
8051: }
8052: }
8053:
8054: sub modify_group_roles {
8055: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
8056: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
8057: my $role = 'gr/'.&escape($userprivs);
8058: my ($uname,$udom) = split(/:/,$user);
8059: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
8060: if ($result eq 'ok') {
8061: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
8062: }
8063: return $result;
8064: }
8065:
8066: sub modify_coursegroup_membership {
8067: my ($cdom,$cnum,$membership) = @_;
8068: my $result = &put('groupmembership',$membership,$cdom,$cnum);
8069: return $result;
8070: }
8071:
8072: sub get_active_groups {
8073: my ($udom,$uname,$cdom,$cnum) = @_;
8074: my $now = time;
8075: my %groups = ();
8076: foreach my $key (keys(%env)) {
8077: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
8078: my ($start,$end) = split(/\./,$env{$key});
8079: if (($end!=0) && ($end<$now)) { next; }
8080: if (($start!=0) && ($start>$now)) { next; }
8081: if ($1 eq $cdom && $2 eq $cnum) {
8082: $groups{$3} = $env{$key} ;
8083: }
8084: }
8085: }
8086: return %groups;
8087: }
8088:
8089: sub get_group_membership {
8090: my ($cdom,$cnum,$group) = @_;
8091: return(&dump('groupmembership',$cdom,$cnum,$group));
8092: }
8093:
8094: sub get_users_groups {
8095: my ($udom,$uname,$courseid) = @_;
8096: my @usersgroups;
8097: my $cachetime=1800;
8098:
8099: my $hashid="$udom:$uname:$courseid";
8100: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
8101: if (defined($cached)) {
8102: @usersgroups = split(/:/,$grouplist);
8103: } else {
8104: $grouplist = '';
8105: my $courseurl = &courseid_to_courseurl($courseid);
8106: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
8107: my $access_end = $env{'course.'.$courseid.
8108: '.default_enrollment_end_date'};
8109: my $now = time;
8110: foreach my $key (keys(%roleshash)) {
8111: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
8112: my $group = $1;
8113: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
8114: my $start = $2;
8115: my $end = $1;
8116: if ($start == -1) { next; } # deleted from group
8117: if (($start!=0) && ($start>$now)) { next; }
8118: if (($end!=0) && ($end<$now)) {
8119: if ($access_end && $access_end < $now) {
8120: if ($access_end - $end < 86400) {
8121: push(@usersgroups,$group);
8122: }
8123: }
8124: next;
8125: }
8126: push(@usersgroups,$group);
8127: }
8128: }
8129: }
8130: @usersgroups = &sort_course_groups($courseid,@usersgroups);
8131: $grouplist = join(':',@usersgroups);
8132: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
8133: }
8134: return @usersgroups;
8135: }
8136:
8137: sub devalidate_getgroups_cache {
8138: my ($udom,$uname,$cdom,$cnum)=@_;
8139: my $courseid = $cdom.'_'.$cnum;
8140:
8141: my $hashid="$udom:$uname:$courseid";
8142: &devalidate_cache_new('getgroups',$hashid);
8143: }
8144:
8145: # ------------------------------------------------------------------ Plain Text
8146:
8147: sub plaintext {
8148: my ($short,$type,$cid,$forcedefault) = @_;
8149: if ($short =~ m{^cr/}) {
8150: return (split('/',$short))[-1];
8151: }
8152: if (!defined($cid)) {
8153: $cid = $env{'request.course.id'};
8154: }
8155: my %rolenames = (
8156: Course => 'std',
8157: Community => 'alt1',
8158: );
8159: if ($cid ne '') {
8160: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
8161: unless ($forcedefault) {
8162: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
8163: &Apache::lonlocal::mt_escape(\$roletext);
8164: return &Apache::lonlocal::mt($roletext);
8165: }
8166: }
8167: }
8168: if ((defined($type)) && (defined($rolenames{$type})) &&
8169: (defined($rolenames{$type})) &&
8170: (defined($prp{$short}{$rolenames{$type}}))) {
8171: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
8172: } elsif ($cid ne '') {
8173: my $crstype = $env{'course.'.$cid.'.type'};
8174: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
8175: (defined($prp{$short}{$rolenames{$crstype}}))) {
8176: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
8177: }
8178: }
8179: return &Apache::lonlocal::mt($prp{$short}{'std'});
8180: }
8181:
8182: # ----------------------------------------------------------------- Assign Role
8183:
8184: sub assignrole {
8185: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
8186: $context)=@_;
8187: my $mrole;
8188: if ($role =~ /^cr\//) {
8189: my $cwosec=$url;
8190: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8191: unless (&allowed('ccr',$cwosec)) {
8192: my $refused = 1;
8193: if ($context eq 'requestcourses') {
8194: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
8195: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
8196: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
8197: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8198: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8199: if ($crsenv{'internal.courseowner'} eq
8200: $env{'user.name'}.':'.$env{'user.domain'}) {
8201: $refused = '';
8202: }
8203: }
8204: }
8205: }
8206: }
8207: if ($refused) {
8208: &logthis('Refused custom assignrole: '.
8209: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
8210: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
8211: return 'refused';
8212: }
8213: }
8214: $mrole='cr';
8215: } elsif ($role =~ /^gr\//) {
8216: my $cwogrp=$url;
8217: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
8218: unless (&allowed('mdg',$cwogrp)) {
8219: &logthis('Refused group assignrole: '.
8220: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
8221: $env{'user.name'}.' at '.$env{'user.domain'});
8222: return 'refused';
8223: }
8224: $mrole='gr';
8225: } else {
8226: my $cwosec=$url;
8227: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
8228: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
8229: my $refused;
8230: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
8231: if (!(&allowed('c'.$role,$url))) {
8232: $refused = 1;
8233: }
8234: } else {
8235: $refused = 1;
8236: }
8237: if ($refused) {
8238: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
8239: if (!$selfenroll && $context eq 'course') {
8240: my %crsenv;
8241: if ($role eq 'cc' || $role eq 'co') {
8242: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8243: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
8244: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
8245: if ($crsenv{'internal.courseowner'} eq
8246: $env{'user.name'}.':'.$env{'user.domain'}) {
8247: $refused = '';
8248: }
8249: }
8250: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
8251: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
8252: if ($crsenv{'internal.courseowner'} eq
8253: $env{'user.name'}.':'.$env{'user.domain'}) {
8254: $refused = '';
8255: }
8256: }
8257: }
8258: }
8259: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
8260: $refused = '';
8261: } elsif ($context eq 'requestcourses') {
8262: my @possroles = ('st','ta','ep','in','cc','co');
8263: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
8264: my $wrongcc;
8265: if ($cnum =~ /^$match_community$/) {
8266: $wrongcc = 1 if ($role eq 'cc');
8267: } else {
8268: $wrongcc = 1 if ($role eq 'co');
8269: }
8270: unless ($wrongcc) {
8271: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
8272: if ($crsenv{'internal.courseowner'} eq
8273: $env{'user.name'}.':'.$env{'user.domain'}) {
8274: $refused = '';
8275: }
8276: }
8277: }
8278: } elsif ($context eq 'requestauthor') {
8279: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
8280: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
8281: if ($env{'environment.requestauthor'} eq 'automatic') {
8282: $refused = '';
8283: } else {
8284: my %domdefaults = &get_domain_defaults($udom);
8285: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
8286: my $checkbystatus;
8287: if ($env{'user.adv'}) {
8288: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
8289: if ($disposition eq 'automatic') {
8290: $refused = '';
8291: } elsif ($disposition eq '') {
8292: $checkbystatus = 1;
8293: }
8294: } else {
8295: $checkbystatus = 1;
8296: }
8297: if ($checkbystatus) {
8298: if ($env{'environment.inststatus'}) {
8299: my @inststatuses = split(/,/,$env{'environment.inststatus'});
8300: foreach my $type (@inststatuses) {
8301: if (($type ne '') &&
8302: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
8303: $refused = '';
8304: }
8305: }
8306: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
8307: $refused = '';
8308: }
8309: }
8310: }
8311: }
8312: }
8313: }
8314: if ($refused) {
8315: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
8316: ' '.$role.' '.$end.' '.$start.' by '.
8317: $env{'user.name'}.' at '.$env{'user.domain'});
8318: return 'refused';
8319: }
8320: }
8321: } elsif ($role eq 'au') {
8322: if ($url ne '/'.$udom.'/') {
8323: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
8324: ' to assign author role for '.$uname.':'.$udom.
8325: ' in domain: '.$url.' refused (wrong domain).');
8326: return 'refused';
8327: }
8328: }
8329: $mrole=$role;
8330: }
8331: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8332: "$udom:$uname:$url".'_'."$mrole=$role";
8333: if ($end) { $command.='_'.$end; }
8334: if ($start) {
8335: if ($end) {
8336: $command.='_'.$start;
8337: } else {
8338: $command.='_0_'.$start;
8339: }
8340: }
8341: my $origstart = $start;
8342: my $origend = $end;
8343: my $delflag;
8344: # actually delete
8345: if ($deleteflag) {
8346: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
8347: # modify command to delete the role
8348: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
8349: "$udom:$uname:$url".'_'."$mrole";
8350: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
8351: # set start and finish to negative values for userrolelog
8352: $start=-1;
8353: $end=-1;
8354: $delflag = 1;
8355: }
8356: }
8357: # send command
8358: my $answer=&reply($command,&homeserver($uname,$udom));
8359: # log new user role if status is ok
8360: if ($answer eq 'ok') {
8361: &userrolelog($role,$uname,$udom,$url,$start,$end);
8362: if (($role eq 'cc') || ($role eq 'in') ||
8363: ($role eq 'ep') || ($role eq 'ad') ||
8364: ($role eq 'ta') || ($role eq 'st') ||
8365: ($role=~/^cr/) || ($role eq 'gr') ||
8366: ($role eq 'co')) {
8367: # for course roles, perform group memberships changes triggered by role change.
8368: unless ($role =~ /^gr/) {
8369: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
8370: $origstart,$selfenroll,$context);
8371: }
8372: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8373: $selfenroll,$context);
8374: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
8375: ($role eq 'au') || ($role eq 'dc')) {
8376: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8377: $context);
8378: } elsif (($role eq 'ca') || ($role eq 'aa')) {
8379: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
8380: $context);
8381: }
8382: if ($role eq 'cc') {
8383: &autoupdate_coowners($url,$end,$start,$uname,$udom);
8384: }
8385: }
8386: return $answer;
8387: }
8388:
8389: sub autoupdate_coowners {
8390: my ($url,$end,$start,$uname,$udom) = @_;
8391: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
8392: if (($cdom ne '') && ($cnum ne '')) {
8393: my $now = time;
8394: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
8395: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
8396: my %coursehash = &coursedescription($cdom.'_'.$cnum);
8397: my $instcode = $coursehash{'internal.coursecode'};
8398: if ($instcode ne '') {
8399: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
8400: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
8401: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
8402: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
8403: if ($result eq 'valid') {
8404: if ($coursehash{'internal.co-owners'}) {
8405: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8406: push(@newcoowners,$coowner);
8407: }
8408: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
8409: push(@newcoowners,$uname.':'.$udom);
8410: }
8411: @newcoowners = sort(@newcoowners);
8412: } else {
8413: push(@newcoowners,$uname.':'.$udom);
8414: }
8415: } else {
8416: if ($coursehash{'internal.co-owners'}) {
8417: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
8418: unless ($coowner eq $uname.':'.$udom) {
8419: push(@newcoowners,$coowner);
8420: }
8421: }
8422: unless (@newcoowners > 0) {
8423: $delcoowners = 1;
8424: $coowners = '';
8425: }
8426: }
8427: }
8428: if (@newcoowners || $delcoowners) {
8429: &store_coowners($cdom,$cnum,$coursehash{'home'},
8430: $delcoowners,@newcoowners);
8431: }
8432: }
8433: }
8434: }
8435: }
8436: }
8437: }
8438:
8439: sub store_coowners {
8440: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
8441: my $cid = $cdom.'_'.$cnum;
8442: my ($coowners,$delresult,$putresult);
8443: if (@newcoowners) {
8444: $coowners = join(',',@newcoowners);
8445: my %coownershash = (
8446: 'internal.co-owners' => $coowners,
8447: );
8448: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
8449: if ($putresult eq 'ok') {
8450: if ($env{'course.'.$cid.'.num'} eq $cnum) {
8451: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
8452: }
8453: }
8454: }
8455: if ($delcoowners) {
8456: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
8457: if ($delresult eq 'ok') {
8458: if ($env{'course.'.$cid.'.internal.co-owners'}) {
8459: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
8460: }
8461: }
8462: }
8463: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
8464: my %crsinfo =
8465: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
8466: if (ref($crsinfo{$cid}) eq 'HASH') {
8467: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
8468: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
8469: }
8470: }
8471: }
8472:
8473: # -------------------------------------------------- Modify user authentication
8474: # Overrides without validation
8475:
8476: sub modifyuserauth {
8477: my ($udom,$uname,$umode,$upass)=@_;
8478: my $uhome=&homeserver($uname,$udom);
8479: unless (&allowed('mau',$udom)) { return 'refused'; }
8480: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
8481: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8482: ' in domain '.$env{'request.role.domain'});
8483: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
8484: &escape($upass),$uhome);
8485: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
8486: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
8487: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8488: &log($udom,,$uname,$uhome,
8489: 'Authentication changed by '.$env{'user.domain'}.', '.
8490: $env{'user.name'}.', '.$umode.
8491: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
8492: unless ($reply eq 'ok') {
8493: &logthis('Authentication mode error: '.$reply);
8494: return 'error: '.$reply;
8495: }
8496: return 'ok';
8497: }
8498:
8499: # --------------------------------------------------------------- Modify a user
8500:
8501: sub modifyuser {
8502: my ($udom, $uname, $uid,
8503: $umode, $upass, $first,
8504: $middle, $last, $gene,
8505: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
8506: $udom= &LONCAPA::clean_domain($udom);
8507: $uname=&LONCAPA::clean_username($uname);
8508: my $showcandelete = 'none';
8509: if (ref($candelete) eq 'ARRAY') {
8510: if (@{$candelete} > 0) {
8511: $showcandelete = join(', ',@{$candelete});
8512: }
8513: }
8514: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
8515: $umode.', '.$first.', '.$middle.', '.
8516: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
8517: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
8518: ' desiredhome not specified').
8519: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
8520: ' in domain '.$env{'request.role.domain'});
8521: my $uhome=&homeserver($uname,$udom,'true');
8522: my $newuser;
8523: if ($uhome eq 'no_host') {
8524: $newuser = 1;
8525: }
8526: # ----------------------------------------------------------------- Create User
8527: if (($uhome eq 'no_host') &&
8528: (($umode && $upass) || ($umode eq 'localauth'))) {
8529: my $unhome='';
8530: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
8531: $unhome = $desiredhome;
8532: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
8533: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
8534: } else { # load balancing routine for determining $unhome
8535: my $loadm=10000000;
8536: my %servers = &get_servers($udom,'library');
8537: foreach my $tryserver (keys(%servers)) {
8538: my $answer=reply('load',$tryserver);
8539: if (($answer=~/\d+/) && ($answer<$loadm)) {
8540: $loadm=$answer;
8541: $unhome=$tryserver;
8542: }
8543: }
8544: }
8545: if (($unhome eq '') || ($unhome eq 'no_host')) {
8546: return 'error: unable to find a home server for '.$uname.
8547: ' in domain '.$udom;
8548: }
8549: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
8550: &escape($upass),$unhome);
8551: unless ($reply eq 'ok') {
8552: return 'error: '.$reply;
8553: }
8554: $uhome=&homeserver($uname,$udom,'true');
8555: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
8556: return 'error: unable verify users home machine.';
8557: }
8558: } # End of creation of new user
8559: # ---------------------------------------------------------------------- Add ID
8560: if ($uid) {
8561: $uid=~tr/A-Z/a-z/;
8562: my %uidhash=&idrget($udom,$uname);
8563: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
8564: && (!$forceid)) {
8565: unless ($uid eq $uidhash{$uname}) {
8566: return 'error: user id "'.$uid.'" does not match '.
8567: 'current user id "'.$uidhash{$uname}.'".';
8568: }
8569: } else {
8570: &idput($udom,($uname => $uid));
8571: }
8572: }
8573: # -------------------------------------------------------------- Add names, etc
8574: my @tmp=&get('environment',
8575: ['firstname','middlename','lastname','generation','id',
8576: 'permanentemail','inststatus'],
8577: $udom,$uname);
8578: my (%names,%oldnames);
8579: if ($tmp[0] =~ m/^error:.*/) {
8580: %names=();
8581: } else {
8582: %names = @tmp;
8583: %oldnames = %names;
8584: }
8585: #
8586: # If name, email and/or uid are blank (e.g., because an uploaded file
8587: # of users did not contain them), do not overwrite existing values
8588: # unless field is in $candelete array ref.
8589: #
8590:
8591: my @fields = ('firstname','middlename','lastname','generation',
8592: 'permanentemail','id');
8593: my %newvalues;
8594: if (ref($candelete) eq 'ARRAY') {
8595: foreach my $field (@fields) {
8596: if (grep(/^\Q$field\E$/,@{$candelete})) {
8597: if ($field eq 'firstname') {
8598: $names{$field} = $first;
8599: } elsif ($field eq 'middlename') {
8600: $names{$field} = $middle;
8601: } elsif ($field eq 'lastname') {
8602: $names{$field} = $last;
8603: } elsif ($field eq 'generation') {
8604: $names{$field} = $gene;
8605: } elsif ($field eq 'permanentemail') {
8606: $names{$field} = $email;
8607: } elsif ($field eq 'id') {
8608: $names{$field} = $uid;
8609: }
8610: }
8611: }
8612: }
8613: if ($first) { $names{'firstname'} = $first; }
8614: if (defined($middle)) { $names{'middlename'} = $middle; }
8615: if ($last) { $names{'lastname'} = $last; }
8616: if (defined($gene)) { $names{'generation'} = $gene; }
8617: if ($email) {
8618: $email=~s/[^\w\@\.\-\,]//gs;
8619: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
8620: }
8621: if ($uid) { $names{'id'} = $uid; }
8622: if (defined($inststatus)) {
8623: $names{'inststatus'} = '';
8624: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
8625: if (ref($usertypes) eq 'HASH') {
8626: my @okstatuses;
8627: foreach my $item (split(/:/,$inststatus)) {
8628: if (defined($usertypes->{$item})) {
8629: push(@okstatuses,$item);
8630: }
8631: }
8632: if (@okstatuses) {
8633: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
8634: }
8635: }
8636: }
8637: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
8638: $umode.', '.$first.', '.$middle.', '.
8639: $last.', '.$gene.', '.$email.', '.$inststatus;
8640: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
8641: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
8642: } else {
8643: $logmsg .= ' during self creation';
8644: }
8645: my $changed;
8646: if ($newuser) {
8647: $changed = 1;
8648: } else {
8649: foreach my $field (@fields) {
8650: if ($names{$field} ne $oldnames{$field}) {
8651: $changed = 1;
8652: last;
8653: }
8654: }
8655: }
8656: unless ($changed) {
8657: $logmsg = 'No changes in user information needed for: '.$logmsg;
8658: &logthis($logmsg);
8659: return 'ok';
8660: }
8661: my $reply = &put('environment', \%names, $udom,$uname);
8662: if ($reply ne 'ok') {
8663: return 'error: '.$reply;
8664: }
8665: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
8666: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
8667: }
8668: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
8669: &devalidate_cache_new('namescache',$uname.':'.$udom);
8670: $logmsg = 'Success modifying user '.$logmsg;
8671: &logthis($logmsg);
8672: return 'ok';
8673: }
8674:
8675: # -------------------------------------------------------------- Modify student
8676:
8677: sub modifystudent {
8678: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
8679: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
8680: $selfenroll,$context,$inststatus,$credits)=@_;
8681: if (!$cid) {
8682: unless ($cid=$env{'request.course.id'}) {
8683: return 'not_in_class';
8684: }
8685: }
8686: # --------------------------------------------------------------- Make the user
8687: my $reply=&modifyuser
8688: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
8689: $desiredhome,$email,$inststatus);
8690: unless ($reply eq 'ok') { return $reply; }
8691: # This will cause &modify_student_enrollment to get the uid from the
8692: # student's environment
8693: $uid = undef if (!$forceid);
8694: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
8695: $gene,$usec,$end,$start,$type,$locktype,
8696: $cid,$selfenroll,$context,$credits);
8697: return $reply;
8698: }
8699:
8700: sub modify_student_enrollment {
8701: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
8702: $locktype,$cid,$selfenroll,$context,$credits) = @_;
8703: my ($cdom,$cnum,$chome);
8704: if (!$cid) {
8705: unless ($cid=$env{'request.course.id'}) {
8706: return 'not_in_class';
8707: }
8708: $cdom=$env{'course.'.$cid.'.domain'};
8709: $cnum=$env{'course.'.$cid.'.num'};
8710: } else {
8711: ($cdom,$cnum)=split(/_/,$cid);
8712: }
8713: $chome=$env{'course.'.$cid.'.home'};
8714: if (!$chome) {
8715: $chome=&homeserver($cnum,$cdom);
8716: }
8717: if (!$chome) { return 'unknown_course'; }
8718: # Make sure the user exists
8719: my $uhome=&homeserver($uname,$udom);
8720: if (($uhome eq '') || ($uhome eq 'no_host')) {
8721: return 'error: no such user';
8722: }
8723: # Get student data if we were not given enough information
8724: if (!defined($first) || $first eq '' ||
8725: !defined($last) || $last eq '' ||
8726: !defined($uid) || $uid eq '' ||
8727: !defined($middle) || $middle eq '' ||
8728: !defined($gene) || $gene eq '') {
8729: # They did not supply us with enough data to enroll the student, so
8730: # we need to pick up more information.
8731: my %tmp = &get('environment',
8732: ['firstname','middlename','lastname', 'generation','id']
8733: ,$udom,$uname);
8734:
8735: #foreach my $key (keys(%tmp)) {
8736: # &logthis("key $key = ".$tmp{$key});
8737: #}
8738: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
8739: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
8740: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
8741: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
8742: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
8743: }
8744: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
8745: my $user = "$uname:$udom";
8746: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
8747: my $reply=cput('classlist',
8748: {$user =>
8749: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits) },
8750: $cdom,$cnum);
8751: if (($reply eq 'ok') || ($reply eq 'delayed')) {
8752: &devalidate_getsection_cache($udom,$uname,$cid);
8753: } else {
8754: return 'error: '.$reply;
8755: }
8756: # Add student role to user
8757: my $uurl='/'.$cid;
8758: $uurl=~s/\_/\//g;
8759: if ($usec) {
8760: $uurl.='/'.$usec;
8761: }
8762: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
8763: $selfenroll,$context);
8764: if ($result ne 'ok') {
8765: if ($old_entry{$user} ne '') {
8766: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
8767: } else {
8768: $reply = &del('classlist',[$user],$cdom,$cnum);
8769: }
8770: }
8771: return $result;
8772: }
8773:
8774: sub format_name {
8775: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8776: my $name;
8777: if ($first ne 'lastname') {
8778: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8779: } else {
8780: if ($lastname=~/\S/) {
8781: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8782: $name=~s/\s+,/,/;
8783: } else {
8784: $name.= $firstname.' '.$middlename.' '.$generation;
8785: }
8786: }
8787: $name=~s/^\s+//;
8788: $name=~s/\s+$//;
8789: $name=~s/\s+/ /g;
8790: return $name;
8791: }
8792:
8793: # ------------------------------------------------- Write to course preferences
8794:
8795: sub writecoursepref {
8796: my ($courseid,%prefs)=@_;
8797: $courseid=~s/^\///;
8798: $courseid=~s/\_/\//g;
8799: my ($cdomain,$cnum)=split(/\//,$courseid);
8800: my $chome=homeserver($cnum,$cdomain);
8801: if (($chome eq '') || ($chome eq 'no_host')) {
8802: return 'error: no such course';
8803: }
8804: my $cstring='';
8805: foreach my $pref (keys(%prefs)) {
8806: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
8807: }
8808: $cstring=~s/\&$//;
8809: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8810: }
8811:
8812: # ---------------------------------------------------------- Make/modify course
8813:
8814: sub createcourse {
8815: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
8816: $course_owner,$crstype,$cnum,$context,$category)=@_;
8817: $url=&declutter($url);
8818: my $cid='';
8819: if ($context eq 'requestcourses') {
8820: my $can_create = 0;
8821: my ($ownername,$ownerdom) = split(':',$course_owner);
8822: if ($udom eq $ownerdom) {
8823: if (&usertools_access($ownername,$ownerdom,$category,undef,
8824: $context)) {
8825: $can_create = 1;
8826: }
8827: } else {
8828: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8829: $category);
8830: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8831: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8832: if (@curr > 0) {
8833: my @options = qw(approval validate autolimit);
8834: my $optregex = join('|',@options);
8835: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8836: $can_create = 1;
8837: }
8838: }
8839: }
8840: }
8841: if ($can_create) {
8842: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8843: unless (&allowed('ccc',$udom)) {
8844: return 'refused';
8845: }
8846: }
8847: } else {
8848: return 'refused';
8849: }
8850: } elsif (!&allowed('ccc',$udom)) {
8851: return 'refused';
8852: }
8853: # --------------------------------------------------------------- Get Unique ID
8854: my $uname;
8855: if ($cnum =~ /^$match_courseid$/) {
8856: my $chome=&homeserver($cnum,$udom,'true');
8857: if (($chome eq '') || ($chome eq 'no_host')) {
8858: $uname = $cnum;
8859: } else {
8860: $uname = &generate_coursenum($udom,$crstype);
8861: }
8862: } else {
8863: $uname = &generate_coursenum($udom,$crstype);
8864: }
8865: return $uname if ($uname =~ /^error/);
8866: # -------------------------------------------------- Check supplied server name
8867: if (!defined($course_server)) {
8868: if (defined(&domain($udom,'primary'))) {
8869: $course_server = &domain($udom,'primary');
8870: } else {
8871: $course_server = $env{'user.home'};
8872: }
8873: }
8874: my %host_servers =
8875: &Apache::lonnet::get_servers($udom,'library');
8876: unless ($host_servers{$course_server}) {
8877: return 'error: invalid home server for course: '.$course_server;
8878: }
8879: # ------------------------------------------------------------- Make the course
8880: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8881: $course_server);
8882: unless ($reply eq 'ok') { return 'error: '.$reply; }
8883: my $uhome=&homeserver($uname,$udom,'true');
8884: if (($uhome eq '') || ($uhome eq 'no_host')) {
8885: return 'error: no such course';
8886: }
8887: # ----------------------------------------------------------------- Course made
8888: # log existence
8889: my $now = time;
8890: my $newcourse = {
8891: $udom.'_'.$uname => {
8892: description => $description,
8893: inst_code => $inst_code,
8894: owner => $course_owner,
8895: type => $crstype,
8896: creator => $env{'user.name'}.':'.
8897: $env{'user.domain'},
8898: created => $now,
8899: context => $context,
8900: },
8901: };
8902: &courseidput($udom,$newcourse,$uhome,'notime');
8903: # set toplevel url
8904: my $topurl=$url;
8905: unless ($nonstandard) {
8906: # ------------------------------------------ For standard courses, make top url
8907: my $mapurl=&clutter($url);
8908: if ($mapurl eq '/res/') { $mapurl=''; }
8909: $env{'form.initmap'}=(<<ENDINITMAP);
8910: <map>
8911: <resource id="1" type="start"></resource>
8912: <resource id="2" src="$mapurl"></resource>
8913: <resource id="3" type="finish"></resource>
8914: <link index="1" from="1" to="2"></link>
8915: <link index="2" from="2" to="3"></link>
8916: </map>
8917: ENDINITMAP
8918: $topurl=&declutter(
8919: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8920: );
8921: }
8922: # ----------------------------------------------------------- Write preferences
8923: &writecoursepref($udom.'_'.$uname,
8924: ('description' => $description,
8925: 'url' => $topurl,
8926: 'internal.creator' => $env{'user.name'}.':'.
8927: $env{'user.domain'},
8928: 'internal.created' => $now,
8929: 'internal.creationcontext' => $context)
8930: );
8931: return '/'.$udom.'/'.$uname;
8932: }
8933:
8934: # ------------------------------------------------------------------- Create ID
8935: sub generate_coursenum {
8936: my ($udom,$crstype) = @_;
8937: my $domdesc = &domain($udom);
8938: return 'error: invalid domain' if ($domdesc eq '');
8939: my $first;
8940: if ($crstype eq 'Community') {
8941: $first = '0';
8942: } else {
8943: $first = int(1+rand(9));
8944: }
8945: my $uname=$first.
8946: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8947: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8948: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8949: # ----------------------------------------------- Make sure that does not exist
8950: my $uhome=&homeserver($uname,$udom,'true');
8951: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8952: if ($crstype eq 'Community') {
8953: $first = '0';
8954: } else {
8955: $first = int(1+rand(9));
8956: }
8957: $uname=$first.
8958: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8959: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8960: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8961: $uhome=&homeserver($uname,$udom,'true');
8962: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8963: return 'error: unable to generate unique course-ID';
8964: }
8965: }
8966: return $uname;
8967: }
8968:
8969: sub is_course {
8970: my ($cdom, $cnum) = scalar(@_) == 1 ?
8971: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8972:
8973: return unless $cdom and $cnum;
8974:
8975: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8976: '.');
8977:
8978: return unless(exists($courses{$cdom.'_'.$cnum}));
8979: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8980: }
8981:
8982: sub store_userdata {
8983: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8984: my $result;
8985: if ($datakey ne '') {
8986: if (ref($storehash) eq 'HASH') {
8987: if ($udom eq '' || $uname eq '') {
8988: $udom = $env{'user.domain'};
8989: $uname = $env{'user.name'};
8990: }
8991: my $uhome=&homeserver($uname,$udom);
8992: if (($uhome eq '') || ($uhome eq 'no_host')) {
8993: $result = 'error: no_host';
8994: } else {
8995: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8996: $storehash->{'host'} = $perlvar{'lonHostID'};
8997:
8998: my $namevalue='';
8999: foreach my $key (keys(%{$storehash})) {
9000: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
9001: }
9002: $namevalue=~s/\&$//;
9003: unless ($namespace eq 'courserequests') {
9004: $datakey = &escape($datakey);
9005: }
9006: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
9007: $namevalue,$uhome);
9008: }
9009: } else {
9010: $result = 'error: data to store was not a hash reference';
9011: }
9012: } else {
9013: $result= 'error: invalid requestkey';
9014: }
9015: return $result;
9016: }
9017:
9018: # ---------------------------------------------------------- Assign Custom Role
9019:
9020: sub assigncustomrole {
9021: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
9022: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
9023: $end,$start,$deleteflag,$selfenroll,$context);
9024: }
9025:
9026: # ----------------------------------------------------------------- Revoke Role
9027:
9028: sub revokerole {
9029: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
9030: my $now=time;
9031: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
9032: }
9033:
9034: # ---------------------------------------------------------- Revoke Custom Role
9035:
9036: sub revokecustomrole {
9037: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
9038: my $now=time;
9039: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
9040: $deleteflag,$selfenroll,$context);
9041: }
9042:
9043: # ------------------------------------------------------------ Disk usage
9044: sub diskusage {
9045: my ($udom,$uname,$directorypath,$getpropath)=@_;
9046: $directorypath =~ s/\/$//;
9047: my $listing=&reply('du2:'.&escape($directorypath).':'
9048: .&escape($getpropath).':'.&escape($uname).':'
9049: .&escape($udom),homeserver($uname,$udom));
9050: if ($listing eq 'unknown_cmd') {
9051: if ($getpropath) {
9052: $directorypath = &propath($udom,$uname).'/'.$directorypath;
9053: }
9054: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
9055: }
9056: return $listing;
9057: }
9058:
9059: sub is_locked {
9060: my ($file_name, $domain, $user, $which) = @_;
9061: my @check;
9062: my $is_locked;
9063: push (@check,$file_name);
9064: my %locked = &get('file_permissions',\@check,
9065: $env{'user.domain'},$env{'user.name'});
9066: my ($tmp)=keys(%locked);
9067: if ($tmp=~/^error:/) { undef(%locked); }
9068:
9069: if (ref($locked{$file_name}) eq 'ARRAY') {
9070: $is_locked = 'false';
9071: foreach my $entry (@{$locked{$file_name}}) {
9072: if (ref($entry) eq 'ARRAY') {
9073: $is_locked = 'true';
9074: if (ref($which) eq 'ARRAY') {
9075: push(@{$which},$entry);
9076: } else {
9077: last;
9078: }
9079: }
9080: }
9081: } else {
9082: $is_locked = 'false';
9083: }
9084: return $is_locked;
9085: }
9086:
9087: sub declutter_portfile {
9088: my ($file) = @_;
9089: $file =~ s{^(/portfolio/|portfolio/)}{/};
9090: return $file;
9091: }
9092:
9093: # ------------------------------------------------------------- Mark as Read Only
9094:
9095: sub mark_as_readonly {
9096: my ($domain,$user,$files,$what) = @_;
9097: my %current_permissions = &dump('file_permissions',$domain,$user);
9098: my ($tmp)=keys(%current_permissions);
9099: if ($tmp=~/^error:/) { undef(%current_permissions); }
9100: foreach my $file (@{$files}) {
9101: $file = &declutter_portfile($file);
9102: push(@{$current_permissions{$file}},$what);
9103: }
9104: &put('file_permissions',\%current_permissions,$domain,$user);
9105: return;
9106: }
9107:
9108: # ------------------------------------------------------------Save Selected Files
9109:
9110: sub save_selected_files {
9111: my ($user, $path, @files) = @_;
9112: my $filename = $user."savedfiles";
9113: my @other_files = &files_not_in_path($user, $path);
9114: open (OUT, '>'.$tmpdir.$filename);
9115: foreach my $file (@files) {
9116: print (OUT $env{'form.currentpath'}.$file."\n");
9117: }
9118: foreach my $file (@other_files) {
9119: print (OUT $file."\n");
9120: }
9121: close (OUT);
9122: return 'ok';
9123: }
9124:
9125: sub clear_selected_files {
9126: my ($user) = @_;
9127: my $filename = $user."savedfiles";
9128: open (OUT, '>'.LONCAPA::tempdir().$filename);
9129: print (OUT undef);
9130: close (OUT);
9131: return ("ok");
9132: }
9133:
9134: sub files_in_path {
9135: my ($user, $path) = @_;
9136: my $filename = $user."savedfiles";
9137: my %return_files;
9138: open (IN, '<'.LONCAPA::tempdir().$filename);
9139: while (my $line_in = <IN>) {
9140: chomp ($line_in);
9141: my @paths_and_file = split (m!/!, $line_in);
9142: my $file_part = pop (@paths_and_file);
9143: my $path_part = join ('/', @paths_and_file);
9144: $path_part.='/';
9145: my $path_and_file = $path_part.$file_part;
9146: if ($path_part eq $path) {
9147: $return_files{$file_part}= 'selected';
9148: }
9149: }
9150: close (IN);
9151: return (\%return_files);
9152: }
9153:
9154: # called in portfolio select mode, to show files selected NOT in current directory
9155: sub files_not_in_path {
9156: my ($user, $path) = @_;
9157: my $filename = $user."savedfiles";
9158: my @return_files;
9159: my $path_part;
9160: open(IN, '<'.LONCAPA::.$filename);
9161: while (my $line = <IN>) {
9162: #ok, I know it's clunky, but I want it to work
9163: my @paths_and_file = split(m|/|, $line);
9164: my $file_part = pop(@paths_and_file);
9165: chomp($file_part);
9166: my $path_part = join('/', @paths_and_file);
9167: $path_part .= '/';
9168: my $path_and_file = $path_part.$file_part;
9169: if ($path_part ne $path) {
9170: push(@return_files, ($path_and_file));
9171: }
9172: }
9173: close(OUT);
9174: return (@return_files);
9175: }
9176:
9177: #------------------------------Submitted/Handedback Portfolio Files Versioning
9178:
9179: sub portfiles_versioning {
9180: my ($symb,$domain,$stu_name,$portfiles,$versioned_portfiles) = @_;
9181: my $portfolio_root = '/userfiles/portfolio';
9182: return unless ((ref($portfiles) eq 'ARRAY') && (ref($versioned_portfiles) eq 'ARRAY'));
9183: foreach my $file (@{$portfiles}) {
9184: &unmark_as_readonly($domain,$stu_name,[$symb,$env{'request.course.id'}],$file);
9185: my ($directory,$answer_file) =($file =~ /^(.*?)([^\/]*)$/);
9186: my ($answer_name,$answer_ver,$answer_ext) = &file_name_version_ext($answer_file);
9187: my $getpropath = 1;
9188: my ($dir_list,$listerror) = &dirlist($portfolio_root.$directory,$domain,
9189: $stu_name,$getpropath);
9190: my $version = &get_next_version($answer_name,$answer_ext,$dir_list);
9191: my $new_answer =
9192: &version_selected_portfile($domain,$stu_name,$directory,$answer_file,$version);
9193: if ($new_answer ne 'problem getting file') {
9194: push(@{$versioned_portfiles}, $directory.$new_answer);
9195: &mark_as_readonly($domain,$stu_name,[$directory.$new_answer],
9196: [$symb,$env{'request.course.id'},'graded']);
9197: }
9198: }
9199: }
9200:
9201: sub get_next_version {
9202: my ($answer_name, $answer_ext, $dir_list) = @_;
9203: my $version;
9204: if (ref($dir_list) eq 'ARRAY') {
9205: foreach my $row (@{$dir_list}) {
9206: my ($file) = split(/\&/,$row,2);
9207: my ($file_name,$file_version,$file_ext) =
9208: &file_name_version_ext($file);
9209: if (($file_name eq $answer_name) &&
9210: ($file_ext eq $answer_ext)) {
9211: # gets here if filename and extension match,
9212: # regardless of version
9213: if ($file_version ne '') {
9214: # a versioned file is found so save it for later
9215: if ($file_version > $version) {
9216: $version = $file_version;
9217: }
9218: }
9219: }
9220: }
9221: }
9222: $version ++;
9223: return($version);
9224: }
9225:
9226: sub version_selected_portfile {
9227: my ($domain,$stu_name,$directory,$file_name,$version) = @_;
9228: my ($answer_name,$answer_ver,$answer_ext) =
9229: &file_name_version_ext($file_name);
9230: my $new_answer;
9231: $env{'form.copy'} =
9232: &getfile("/uploaded/$domain/$stu_name/portfolio$directory$file_name");
9233: if($env{'form.copy'} eq '-1') {
9234: $new_answer = 'problem getting file';
9235: } else {
9236: $new_answer = $answer_name.'.'.$version.'.'.$answer_ext;
9237: my $copy_result =
9238: &finishuserfileupload($stu_name,$domain,'copy',
9239: '/portfolio'.$directory.$new_answer);
9240: }
9241: undef($env{'form.copy'});
9242: return ($new_answer);
9243: }
9244:
9245: sub file_name_version_ext {
9246: my ($file)=@_;
9247: my @file_parts = split(/\./, $file);
9248: my ($name,$version,$ext);
9249: if (@file_parts > 1) {
9250: $ext=pop(@file_parts);
9251: if (@file_parts > 1 && $file_parts[-1] =~ /^\d+$/) {
9252: $version=pop(@file_parts);
9253: }
9254: $name=join('.',@file_parts);
9255: } else {
9256: $name=join('.',@file_parts);
9257: }
9258: return($name,$version,$ext);
9259: }
9260:
9261: #----------------------------------------------Get portfolio file permissions
9262:
9263: sub get_portfile_permissions {
9264: my ($domain,$user) = @_;
9265: my %current_permissions = &dump('file_permissions',$domain,$user);
9266: my ($tmp)=keys(%current_permissions);
9267: if ($tmp=~/^error:/) { undef(%current_permissions); }
9268: return \%current_permissions;
9269: }
9270:
9271: #---------------------------------------------Get portfolio file access controls
9272:
9273: sub get_access_controls {
9274: my ($current_permissions,$group,$file) = @_;
9275: my %access;
9276: my $real_file = $file;
9277: $file =~ s/\.meta$//;
9278: if (defined($file)) {
9279: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
9280: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
9281: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
9282: }
9283: }
9284: } else {
9285: foreach my $key (keys(%{$current_permissions})) {
9286: if ($key =~ /\0accesscontrol$/) {
9287: if (defined($group)) {
9288: if ($key !~ m-^\Q$group\E/-) {
9289: next;
9290: }
9291: }
9292: my ($fullpath) = split(/\0/,$key);
9293: if (ref($$current_permissions{$key}) eq 'HASH') {
9294: foreach my $control (keys(%{$$current_permissions{$key}})) {
9295: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
9296: }
9297: }
9298: }
9299: }
9300: }
9301: return %access;
9302: }
9303:
9304: sub modify_access_controls {
9305: my ($file_name,$changes,$domain,$user)=@_;
9306: my ($outcome,$deloutcome);
9307: my %store_permissions;
9308: my %new_values;
9309: my %new_control;
9310: my %translation;
9311: my @deletions = ();
9312: my $now = time;
9313: if (exists($$changes{'activate'})) {
9314: if (ref($$changes{'activate'}) eq 'HASH') {
9315: my @newitems = sort(keys(%{$$changes{'activate'}}));
9316: my $numnew = scalar(@newitems);
9317: for (my $i=0; $i<$numnew; $i++) {
9318: my $newkey = $newitems[$i];
9319: my $newid = &Apache::loncommon::get_cgi_id();
9320: if ($newkey =~ /^\d+:/) {
9321: $newkey =~ s/^(\d+)/$newid/;
9322: $translation{$1} = $newid;
9323: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
9324: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
9325: $translation{$1} = $newid;
9326: }
9327: $new_values{$file_name."\0".$newkey} =
9328: $$changes{'activate'}{$newitems[$i]};
9329: $new_control{$newkey} = $now;
9330: }
9331: }
9332: }
9333: my %todelete;
9334: my %changed_items;
9335: foreach my $action ('delete','update') {
9336: if (exists($$changes{$action})) {
9337: if (ref($$changes{$action}) eq 'HASH') {
9338: foreach my $key (keys(%{$$changes{$action}})) {
9339: my ($itemnum) = ($key =~ /^([^:]+):/);
9340: if ($action eq 'delete') {
9341: $todelete{$itemnum} = 1;
9342: } else {
9343: $changed_items{$itemnum} = $key;
9344: }
9345: }
9346: }
9347: }
9348: }
9349: # get lock on access controls for file.
9350: my $lockhash = {
9351: $file_name."\0".'locked_access_records' => $env{'user.name'}.
9352: ':'.$env{'user.domain'},
9353: };
9354: my $tries = 0;
9355: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9356:
9357: while (($gotlock ne 'ok') && $tries <3) {
9358: $tries ++;
9359: sleep 1;
9360: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
9361: }
9362: if ($gotlock eq 'ok') {
9363: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
9364: my ($tmp)=keys(%curr_permissions);
9365: if ($tmp=~/^error:/) { undef(%curr_permissions); }
9366: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
9367: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
9368: if (ref($curr_controls) eq 'HASH') {
9369: foreach my $control_item (keys(%{$curr_controls})) {
9370: my ($itemnum) = ($control_item =~ /^([^:]+):/);
9371: if (defined($todelete{$itemnum})) {
9372: push(@deletions,$file_name."\0".$control_item);
9373: } else {
9374: if (defined($changed_items{$itemnum})) {
9375: $new_control{$changed_items{$itemnum}} = $now;
9376: push(@deletions,$file_name."\0".$control_item);
9377: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
9378: } else {
9379: $new_control{$control_item} = $$curr_controls{$control_item};
9380: }
9381: }
9382: }
9383: }
9384: }
9385: my ($group);
9386: if (&is_course($domain,$user)) {
9387: ($group,my $file) = split(/\//,$file_name,2);
9388: }
9389: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
9390: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
9391: $outcome = &put('file_permissions',\%new_values,$domain,$user);
9392: # remove lock
9393: my @del_lock = ($file_name."\0".'locked_access_records');
9394: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
9395: my $sqlresult =
9396: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
9397: $group);
9398: } else {
9399: $outcome = "error: could not obtain lockfile\n";
9400: }
9401: return ($outcome,$deloutcome,\%new_values,\%translation);
9402: }
9403:
9404: sub make_public_indefinitely {
9405: my (@requrl) = @_;
9406: return &automated_portfile_access('public',\@requrl);
9407: }
9408:
9409: sub automated_portfile_access {
9410: my ($accesstype,$addsref,$delsref,$info) = @_;
9411: unless (($accesstype eq 'public') || ($accesstype eq 'ip')) {
9412: return 'invalid';
9413: }
9414: my %urls;
9415: if (ref($addsref) eq 'ARRAY') {
9416: foreach my $requrl (@{$addsref}) {
9417: if (&is_portfolio_url($requrl)) {
9418: unless (exists($urls{$requrl})) {
9419: $urls{$requrl} = 'add';
9420: }
9421: }
9422: }
9423: }
9424: if (ref($delsref) eq 'ARRAY') {
9425: foreach my $requrl (@{$delsref}) {
9426: if (&is_portfolio_url($requrl)) {
9427: unless (exists($urls{$requrl})) {
9428: $urls{$requrl} = 'delete';
9429: }
9430: }
9431: }
9432: }
9433: unless (keys(%urls)) {
9434: return 'invalid';
9435: }
9436: my $ip;
9437: if ($accesstype eq 'ip') {
9438: if (ref($info) eq 'HASH') {
9439: if ($info->{'ip'} ne '') {
9440: $ip = $info->{'ip'};
9441: }
9442: }
9443: if ($ip eq '') {
9444: return 'invalid';
9445: }
9446: }
9447: my $errors;
9448: my $now = time;
9449: my %current_perms;
9450: foreach my $requrl (sort(keys(%urls))) {
9451: my $action;
9452: if ($urls{$requrl} eq 'add') {
9453: $action = 'activate';
9454: } else {
9455: $action = 'none';
9456: }
9457: my $aclnum = 0;
9458: my (undef,$udom,$unum,$file_name,$group) =
9459: &parse_portfolio_url($requrl);
9460: unless (exists($current_perms{$unum.':'.$udom})) {
9461: $current_perms{$unum.':'.$udom} = &get_portfile_permissions($udom,$unum);
9462: }
9463: my %access_controls = &get_access_controls($current_perms{$unum.':'.$udom},
9464: $group,$file_name);
9465: foreach my $key (keys(%{$access_controls{$file_name}})) {
9466: my ($num,$scope,$end,$start) =
9467: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
9468: if ($scope eq $accesstype) {
9469: if (($start <= $now) && ($end == 0)) {
9470: if ($accesstype eq 'ip') {
9471: if (ref($access_controls{$file_name}{$key}) eq 'HASH') {
9472: if (ref($access_controls{$file_name}{$key}{'ip'}) eq 'ARRAY') {
9473: if (grep(/^\Q$ip\E$/,@{$access_controls{$file_name}{$key}{'ip'}})) {
9474: if ($urls{$requrl} eq 'add') {
9475: $action = 'none';
9476: last;
9477: } else {
9478: $action = 'delete';
9479: $aclnum = $num;
9480: last;
9481: }
9482: }
9483: }
9484: }
9485: } elsif ($accesstype eq 'public') {
9486: if ($urls{$requrl} eq 'add') {
9487: $action = 'none';
9488: last;
9489: } else {
9490: $action = 'delete';
9491: $aclnum = $num;
9492: last;
9493: }
9494: }
9495: } elsif ($accesstype eq 'public') {
9496: $action = 'update';
9497: $aclnum = $num;
9498: last;
9499: }
9500: }
9501: }
9502: if ($action eq 'none') {
9503: next;
9504: } else {
9505: my %changes;
9506: my $newend = 0;
9507: my $newstart = $now;
9508: my $newkey = $aclnum.':'.$accesstype.'_'.$newend.'_'.$newstart;
9509: $changes{$action}{$newkey} = {
9510: type => $accesstype,
9511: time => {
9512: start => $newstart,
9513: end => $newend,
9514: },
9515: };
9516: if ($accesstype eq 'ip') {
9517: $changes{$action}{$newkey}{'ip'} = [$ip];
9518: }
9519: my ($outcome,$deloutcome,$new_values,$translation) =
9520: &modify_access_controls($file_name,\%changes,$udom,$unum);
9521: unless ($outcome eq 'ok') {
9522: $errors .= $outcome.' ';
9523: }
9524: }
9525: }
9526: if ($errors) {
9527: $errors =~ s/\s$//;
9528: return $errors;
9529: } else {
9530: return 'ok';
9531: }
9532: }
9533:
9534: #------------------------------------------------------Get Marked as Read Only
9535:
9536: sub get_marked_as_readonly {
9537: my ($domain,$user,$what,$group) = @_;
9538: my $current_permissions = &get_portfile_permissions($domain,$user);
9539: my @readonly_files;
9540: my $cmp1=$what;
9541: if (ref($what)) { $cmp1=join('',@{$what}) };
9542: while (my ($file_name,$value) = each(%{$current_permissions})) {
9543: if (defined($group)) {
9544: if ($file_name !~ m-^\Q$group\E/-) {
9545: next;
9546: }
9547: }
9548: if (ref($value) eq "ARRAY"){
9549: foreach my $stored_what (@{$value}) {
9550: my $cmp2=$stored_what;
9551: if (ref($stored_what) eq 'ARRAY') {
9552: $cmp2=join('',@{$stored_what});
9553: }
9554: if ($cmp1 eq $cmp2) {
9555: push(@readonly_files, $file_name);
9556: last;
9557: } elsif (!defined($what)) {
9558: push(@readonly_files, $file_name);
9559: last;
9560: }
9561: }
9562: }
9563: }
9564: return @readonly_files;
9565: }
9566: #-----------------------------------------------------------Get Marked as Read Only Hash
9567:
9568: sub get_marked_as_readonly_hash {
9569: my ($current_permissions,$group,$what) = @_;
9570: my %readonly_files;
9571: while (my ($file_name,$value) = each(%{$current_permissions})) {
9572: if (defined($group)) {
9573: if ($file_name !~ m-^\Q$group\E/-) {
9574: next;
9575: }
9576: }
9577: if (ref($value) eq "ARRAY"){
9578: foreach my $stored_what (@{$value}) {
9579: if (ref($stored_what) eq 'ARRAY') {
9580: foreach my $lock_descriptor(@{$stored_what}) {
9581: if ($lock_descriptor eq 'graded') {
9582: $readonly_files{$file_name} = 'graded';
9583: } elsif ($lock_descriptor eq 'handback') {
9584: $readonly_files{$file_name} = 'handback';
9585: } else {
9586: if (!exists($readonly_files{$file_name})) {
9587: $readonly_files{$file_name} = 'locked';
9588: }
9589: }
9590: }
9591: }
9592: }
9593: }
9594: }
9595: return %readonly_files;
9596: }
9597: # ------------------------------------------------------------ Unmark as Read Only
9598:
9599: sub unmark_as_readonly {
9600: # unmarks $file_name (if $file_name is defined), or all files locked by $what
9601: # for portfolio submissions, $what contains [$symb,$crsid]
9602: my ($domain,$user,$what,$file_name,$group) = @_;
9603: $file_name = &declutter_portfile($file_name);
9604: my $symb_crs = $what;
9605: if (ref($what)) { $symb_crs=join('',@$what); }
9606: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
9607: my ($tmp)=keys(%current_permissions);
9608: if ($tmp=~/^error:/) { undef(%current_permissions); }
9609: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
9610: foreach my $file (@readonly_files) {
9611: my $clean_file = &declutter_portfile($file);
9612: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
9613: my $current_locks = $current_permissions{$file};
9614: my @new_locks;
9615: my @del_keys;
9616: if (ref($current_locks) eq "ARRAY"){
9617: foreach my $locker (@{$current_locks}) {
9618: my $compare=$locker;
9619: if (ref($locker) eq 'ARRAY') {
9620: $compare=join('',@{$locker});
9621: if ($compare ne $symb_crs) {
9622: push(@new_locks, $locker);
9623: }
9624: }
9625: }
9626: if (scalar(@new_locks) > 0) {
9627: $current_permissions{$file} = \@new_locks;
9628: } else {
9629: push(@del_keys, $file);
9630: &del('file_permissions',\@del_keys, $domain, $user);
9631: delete($current_permissions{$file});
9632: }
9633: }
9634: }
9635: &put('file_permissions',\%current_permissions,$domain,$user);
9636: return;
9637: }
9638:
9639: # ------------------------------------------------------------ Directory lister
9640:
9641: sub dirlist {
9642: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
9643: $uri=~s/^\///;
9644: $uri=~s/\/$//;
9645: my ($udom, $uname);
9646: if ($getuserdir) {
9647: $udom = $userdomain;
9648: $uname = $username;
9649: } else {
9650: (undef,$udom,$uname)=split(/\//,$uri);
9651: if(defined($userdomain)) {
9652: $udom = $userdomain;
9653: }
9654: if(defined($username)) {
9655: $uname = $username;
9656: }
9657: }
9658: my ($dirRoot,$listing,@listing_results);
9659:
9660: $dirRoot = $perlvar{'lonDocRoot'};
9661: if (defined($getpropath)) {
9662: $dirRoot = &propath($udom,$uname);
9663: $dirRoot =~ s/\/$//;
9664: } elsif (defined($getuserdir)) {
9665: my $subdir=$uname.'__';
9666: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
9667: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
9668: ."/$udom/$subdir/$uname";
9669: } elsif (defined($alternateRoot)) {
9670: $dirRoot = $alternateRoot;
9671: }
9672:
9673: if($udom) {
9674: if($uname) {
9675: my $uhome = &homeserver($uname,$udom);
9676: if ($uhome eq 'no_host') {
9677: return ([],'no_host');
9678: }
9679: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
9680: .$getuserdir.':'.&escape($dirRoot)
9681: .':'.&escape($uname).':'.&escape($udom),$uhome);
9682: if ($listing eq 'unknown_cmd') {
9683: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
9684: } else {
9685: @listing_results = map { &unescape($_); } split(/:/,$listing);
9686: }
9687: if ($listing eq 'unknown_cmd') {
9688: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
9689: @listing_results = split(/:/,$listing);
9690: } else {
9691: @listing_results = map { &unescape($_); } split(/:/,$listing);
9692: }
9693: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9694: ($listing eq 'rejected') || ($listing eq 'refused') ||
9695: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9696: return ([],$listing);
9697: } else {
9698: return (\@listing_results);
9699: }
9700: } elsif(!$alternateRoot) {
9701: my (%allusers,%listerror);
9702: my %servers = &get_servers($udom,'library');
9703: foreach my $tryserver (keys(%servers)) {
9704: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
9705: &escape($udom),$tryserver);
9706: if ($listing eq 'unknown_cmd') {
9707: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
9708: $udom, $tryserver);
9709: } else {
9710: @listing_results = map { &unescape($_); } split(/:/,$listing);
9711: }
9712: if ($listing eq 'unknown_cmd') {
9713: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
9714: $udom, $tryserver);
9715: @listing_results = split(/:/,$listing);
9716: } else {
9717: @listing_results =
9718: map { &unescape($_); } split(/:/,$listing);
9719: }
9720: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
9721: ($listing eq 'rejected') || ($listing eq 'refused') ||
9722: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
9723: $listerror{$tryserver} = $listing;
9724: } else {
9725: foreach my $line (@listing_results) {
9726: my ($entry) = split(/&/,$line,2);
9727: $allusers{$entry} = 1;
9728: }
9729: }
9730: }
9731: my @alluserslist=();
9732: foreach my $user (sort(keys(%allusers))) {
9733: push(@alluserslist,$user.'&user');
9734: }
9735: return (\@alluserslist);
9736: } else {
9737: return ([],'missing username');
9738: }
9739: } elsif(!defined($getpropath)) {
9740: my $path = $perlvar{'lonDocRoot'}.'/res/';
9741: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
9742: return (\@all_domains);
9743: } else {
9744: return ([],'missing domain');
9745: }
9746: }
9747:
9748: # --------------------------------------------- GetFileTimestamp
9749: # This function utilizes dirlist and returns the date stamp for
9750: # when it was last modified. It will also return an error of -1
9751: # if an error occurs
9752:
9753: sub GetFileTimestamp {
9754: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
9755: $studentDomain = &LONCAPA::clean_domain($studentDomain);
9756: $studentName = &LONCAPA::clean_username($studentName);
9757: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
9758: undef,$getuserdir);
9759: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9760: return -1;
9761: }
9762: if (ref($fileref) eq 'ARRAY') {
9763: my @stats = split('&',$fileref->[0]);
9764: # @stats contains first the filename, then the stat output
9765: return $stats[10]; # so this is 10 instead of 9.
9766: } else {
9767: return -1;
9768: }
9769: }
9770:
9771: sub stat_file {
9772: my ($uri) = @_;
9773: $uri = &clutter_with_no_wrapper($uri);
9774:
9775: my ($udom,$uname,$file);
9776: if ($uri =~ m-^/(uploaded|editupload)/-) {
9777: ($udom,$uname,$file) =
9778: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
9779: $file = 'userfiles/'.$file;
9780: }
9781: if ($uri =~ m-^/res/-) {
9782: ($udom,$uname) =
9783: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
9784: $file = $uri;
9785: }
9786:
9787: if (!$udom || !$uname || !$file) {
9788: # unable to handle the uri
9789: return ();
9790: }
9791: my $getpropath;
9792: if ($file =~ /^userfiles\//) {
9793: $getpropath = 1;
9794: }
9795: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
9796: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
9797: return ();
9798: } else {
9799: if (ref($listref) eq 'ARRAY') {
9800: my @stats = split('&',$listref->[0]);
9801: shift(@stats); #filename is first
9802: return @stats;
9803: }
9804: }
9805: return ();
9806: }
9807:
9808: # -------------------------------------------------------- Value of a Condition
9809:
9810: # gets the value of a specific preevaluated condition
9811: # stored in the string $env{user.state.<cid>}
9812: # or looks up a condition reference in the bighash and if if hasn't
9813: # already been evaluated recurses into docondval to get the value of
9814: # the condition, then memoizing it to
9815: # $env{user.state.<cid>.<condition>}
9816: sub directcondval {
9817: my $number=shift;
9818: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
9819: &Apache::lonuserstate::evalstate();
9820: }
9821: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
9822: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
9823: } elsif ($number =~ /^_/) {
9824: my $sub_condition;
9825: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9826: &GDBM_READER(),0640)) {
9827: $sub_condition=$bighash{'conditions'.$number};
9828: untie(%bighash);
9829: }
9830: my $value = &docondval($sub_condition);
9831: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
9832: return $value;
9833: }
9834: if ($env{'user.state.'.$env{'request.course.id'}}) {
9835: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
9836: } else {
9837: return 2;
9838: }
9839: }
9840:
9841: # get the collection of conditions for this resource
9842: sub condval {
9843: my $condidx=shift;
9844: my $allpathcond='';
9845: foreach my $cond (split(/\|/,$condidx)) {
9846: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
9847: $allpathcond.=
9848: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
9849: }
9850: }
9851: $allpathcond=~s/\|$//;
9852: return &docondval($allpathcond);
9853: }
9854:
9855: #evaluates an expression of conditions
9856: sub docondval {
9857: my ($allpathcond) = @_;
9858: my $result=0;
9859: if ($env{'request.course.id'}
9860: && defined($allpathcond)) {
9861: my $operand='|';
9862: my @stack;
9863: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
9864: if ($chunk eq '(') {
9865: push @stack,($operand,$result);
9866: } elsif ($chunk eq ')') {
9867: my $before=pop @stack;
9868: if (pop @stack eq '&') {
9869: $result=$result>$before?$before:$result;
9870: } else {
9871: $result=$result>$before?$result:$before;
9872: }
9873: } elsif (($chunk eq '&') || ($chunk eq '|')) {
9874: $operand=$chunk;
9875: } else {
9876: my $new=directcondval($chunk);
9877: if ($operand eq '&') {
9878: $result=$result>$new?$new:$result;
9879: } else {
9880: $result=$result>$new?$result:$new;
9881: }
9882: }
9883: }
9884: }
9885: return $result;
9886: }
9887:
9888: # ---------------------------------------------------- Devalidate courseresdata
9889:
9890: sub devalidatecourseresdata {
9891: my ($coursenum,$coursedomain)=@_;
9892: my $hashid=$coursenum.':'.$coursedomain;
9893: &devalidate_cache_new('courseres',$hashid);
9894: }
9895:
9896:
9897: # --------------------------------------------------- Course Resourcedata Query
9898: #
9899: # Parameters:
9900: # $coursenum - Number of the course.
9901: # $coursedomain - Domain at which the course was created.
9902: # Returns:
9903: # A hash of the course parameters along (I think) with timestamps
9904: # and version info.
9905:
9906: sub get_courseresdata {
9907: my ($coursenum,$coursedomain)=@_;
9908: my $coursehom=&homeserver($coursenum,$coursedomain);
9909: my $hashid=$coursenum.':'.$coursedomain;
9910: my ($result,$cached)=&is_cached_new('courseres',$hashid);
9911: my %dumpreply;
9912: unless (defined($cached)) {
9913: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
9914: $result=\%dumpreply;
9915: my ($tmp) = keys(%dumpreply);
9916: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9917: &do_cache_new('courseres',$hashid,$result,600);
9918: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
9919: return $tmp;
9920: } elsif ($tmp =~ /^(error)/) {
9921: $result=undef;
9922: &do_cache_new('courseres',$hashid,$result,600);
9923: }
9924: }
9925: return $result;
9926: }
9927:
9928: sub devalidateuserresdata {
9929: my ($uname,$udom)=@_;
9930: my $hashid="$udom:$uname";
9931: &devalidate_cache_new('userres',$hashid);
9932: }
9933:
9934: sub get_userresdata {
9935: my ($uname,$udom)=@_;
9936: #most student don\'t have any data set, check if there is some data
9937: if (&EXT_cache_status($udom,$uname)) { return undef; }
9938:
9939: my $hashid="$udom:$uname";
9940: my ($result,$cached)=&is_cached_new('userres',$hashid);
9941: if (!defined($cached)) {
9942: my %resourcedata=&dump('resourcedata',$udom,$uname);
9943: $result=\%resourcedata;
9944: &do_cache_new('userres',$hashid,$result,600);
9945: }
9946: my ($tmp)=keys(%$result);
9947: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9948: return $result;
9949: }
9950: #error 2 occurs when the .db doesn't exist
9951: if ($tmp!~/error: 2 /) {
9952: &logthis("<font color=\"blue\">WARNING:".
9953: " Trying to get resource data for ".
9954: $uname." at ".$udom.": ".
9955: $tmp."</font>");
9956: } elsif ($tmp=~/error: 2 /) {
9957: #&EXT_cache_set($udom,$uname);
9958: &do_cache_new('userres',$hashid,undef,600);
9959: undef($tmp); # not really an error so don't send it back
9960: }
9961: return $tmp;
9962: }
9963: #----------------------------------------------- resdata - return resource data
9964: # Purpose:
9965: # Return resource data for either users or for a course.
9966: # Parameters:
9967: # $name - Course/user name.
9968: # $domain - Name of the domain the user/course is registered on.
9969: # $type - Type of thing $name is (must be 'course' or 'user'
9970: # @which - Array of names of resources desired.
9971: # Returns:
9972: # The value of the first reasource in @which that is found in the
9973: # resource hash.
9974: # Exceptional Conditions:
9975: # If the $type passed in is not valid (not the string 'course' or
9976: # 'user', an undefined reference is returned.
9977: # If none of the resources are found, an undef is returned
9978: sub resdata {
9979: my ($name,$domain,$type,@which)=@_;
9980: my $result;
9981: if ($type eq 'course') {
9982: $result=&get_courseresdata($name,$domain);
9983: } elsif ($type eq 'user') {
9984: $result=&get_userresdata($name,$domain);
9985: }
9986: if (!ref($result)) { return $result; }
9987: foreach my $item (@which) {
9988: if (defined($result->{$item->[0]})) {
9989: return [$result->{$item->[0]},$item->[1]];
9990: }
9991: }
9992: return undef;
9993: }
9994:
9995: sub get_numsuppfiles {
9996: my ($cnum,$cdom,$ignorecache)=@_;
9997: my $hashid=$cnum.':'.$cdom;
9998: my ($suppcount,$cached);
9999: unless ($ignorecache) {
10000: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
10001: }
10002: unless (defined($cached)) {
10003: my $chome=&homeserver($cnum,$cdom);
10004: unless ($chome eq 'no_host') {
10005: ($suppcount,my $errors) = (0,0);
10006: my $suppmap = 'supplemental.sequence';
10007: ($suppcount,$errors) =
10008: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
10009: }
10010: &do_cache_new('suppcount',$hashid,$suppcount,600);
10011: }
10012: return $suppcount;
10013: }
10014:
10015: #
10016: # EXT resource caching routines
10017: #
10018:
10019: sub clear_EXT_cache_status {
10020: &delenv('cache.EXT.');
10021: }
10022:
10023: sub EXT_cache_status {
10024: my ($target_domain,$target_user) = @_;
10025: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10026: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
10027: # We know already the user has no data
10028: return 1;
10029: } else {
10030: return 0;
10031: }
10032: }
10033:
10034: sub EXT_cache_set {
10035: my ($target_domain,$target_user) = @_;
10036: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
10037: #&appenv({$cachename => time});
10038: }
10039:
10040: # --------------------------------------------------------- Value of a Variable
10041: sub EXT {
10042:
10043: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
10044: unless ($varname) { return ''; }
10045: #get real user name/domain, courseid and symb
10046: my $courseid;
10047: my $publicuser;
10048: if ($symbparm) {
10049: $symbparm=&get_symb_from_alias($symbparm);
10050: }
10051: if (!($uname && $udom)) {
10052: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
10053: if (!$symbparm) { $symbparm=$cursymb; }
10054: } else {
10055: $courseid=$env{'request.course.id'};
10056: }
10057: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
10058: my $rest;
10059: if (defined($therest[0])) {
10060: $rest=join('.',@therest);
10061: } else {
10062: $rest='';
10063: }
10064:
10065: my $qualifierrest=$qualifier;
10066: if ($rest) { $qualifierrest.='.'.$rest; }
10067: my $spacequalifierrest=$space;
10068: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
10069: if ($realm eq 'user') {
10070: # --------------------------------------------------------------- user.resource
10071: if ($space eq 'resource') {
10072: if ( (defined($Apache::lonhomework::parsing_a_problem)
10073: || defined($Apache::lonhomework::parsing_a_task))
10074: &&
10075: ($symbparm eq &symbread()) ) {
10076: # if we are in the middle of processing the resource the
10077: # get the value we are planning on committing
10078: if (defined($Apache::lonhomework::results{$qualifierrest})) {
10079: return $Apache::lonhomework::results{$qualifierrest};
10080: } else {
10081: return $Apache::lonhomework::history{$qualifierrest};
10082: }
10083: } else {
10084: my %restored;
10085: if ($publicuser || $env{'request.state'} eq 'construct') {
10086: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
10087: } else {
10088: %restored=&restore($symbparm,$courseid,$udom,$uname);
10089: }
10090: return $restored{$qualifierrest};
10091: }
10092: # ----------------------------------------------------------------- user.access
10093: } elsif ($space eq 'access') {
10094: # FIXME - not supporting calls for a specific user
10095: return &allowed($qualifier,$rest);
10096: # ------------------------------------------ user.preferences, user.environment
10097: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
10098: if (($uname eq $env{'user.name'}) &&
10099: ($udom eq $env{'user.domain'})) {
10100: return $env{join('.',('environment',$qualifierrest))};
10101: } else {
10102: my %returnhash;
10103: if (!$publicuser) {
10104: %returnhash=&userenvironment($udom,$uname,
10105: $qualifierrest);
10106: }
10107: return $returnhash{$qualifierrest};
10108: }
10109: # ----------------------------------------------------------------- user.course
10110: } elsif ($space eq 'course') {
10111: # FIXME - not supporting calls for a specific user
10112: return $env{join('.',('request.course',$qualifier))};
10113: # ------------------------------------------------------------------- user.role
10114: } elsif ($space eq 'role') {
10115: # FIXME - not supporting calls for a specific user
10116: my ($role,$where)=split(/\./,$env{'request.role'});
10117: if ($qualifier eq 'value') {
10118: return $role;
10119: } elsif ($qualifier eq 'extent') {
10120: return $where;
10121: }
10122: # ----------------------------------------------------------------- user.domain
10123: } elsif ($space eq 'domain') {
10124: return $udom;
10125: # ------------------------------------------------------------------- user.name
10126: } elsif ($space eq 'name') {
10127: return $uname;
10128: # ---------------------------------------------------- Any other user namespace
10129: } else {
10130: my %reply;
10131: if (!$publicuser) {
10132: %reply=&get($space,[$qualifierrest],$udom,$uname);
10133: }
10134: return $reply{$qualifierrest};
10135: }
10136: } elsif ($realm eq 'query') {
10137: # ---------------------------------------------- pull stuff out of query string
10138: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
10139: [$spacequalifierrest]);
10140: return $env{'form.'.$spacequalifierrest};
10141: } elsif ($realm eq 'request') {
10142: # ------------------------------------------------------------- request.browser
10143: if ($space eq 'browser') {
10144: return $env{'browser.'.$qualifier};
10145: # ------------------------------------------------------------ request.filename
10146: } else {
10147: return $env{'request.'.$spacequalifierrest};
10148: }
10149: } elsif ($realm eq 'course') {
10150: # ---------------------------------------------------------- course.description
10151: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
10152: } elsif ($realm eq 'resource') {
10153:
10154: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
10155: if (!$symbparm) { $symbparm=&symbread(); }
10156: }
10157:
10158: if ($qualifier eq '') {
10159: if ($space eq 'title') {
10160: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
10161: return &gettitle($symbparm);
10162: }
10163:
10164: if ($space eq 'map') {
10165: my ($map) = &decode_symb($symbparm);
10166: return &symbread($map);
10167: }
10168: if ($space eq 'maptitle') {
10169: my ($map) = &decode_symb($symbparm);
10170: return &gettitle($map);
10171: }
10172: if ($space eq 'filename') {
10173: if ($symbparm) {
10174: return &clutter((&decode_symb($symbparm))[2]);
10175: }
10176: return &hreflocation('',$env{'request.filename'});
10177: }
10178:
10179: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
10180: if ($space eq 'visibleparts') {
10181: my $navmap = Apache::lonnavmaps::navmap->new();
10182: my $item;
10183: if (ref($navmap)) {
10184: my $res = $navmap->getBySymb($symbparm);
10185: my $parts = $res->parts();
10186: if (ref($parts) eq 'ARRAY') {
10187: $item = join(',',@{$parts});
10188: }
10189: undef($navmap);
10190: }
10191: return $item;
10192: }
10193: }
10194: }
10195:
10196: my ($section, $group, @groups);
10197: my ($courselevelm,$courselevel);
10198: if (($courseid eq '') && ($cid)) {
10199: $courseid = $cid;
10200: }
10201: if (($symbparm && $courseid) &&
10202: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
10203:
10204: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
10205:
10206: # ----------------------------------------------------- Cascading lookup scheme
10207: my $symbp=$symbparm;
10208: my $mapp=&deversion((&decode_symb($symbp))[0]);
10209:
10210: my $symbparm=$symbp.'.'.$spacequalifierrest;
10211: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
10212:
10213: if (($env{'user.name'} eq $uname) &&
10214: ($env{'user.domain'} eq $udom)) {
10215: $section=$env{'request.course.sec'};
10216: @groups = split(/:/,$env{'request.course.groups'});
10217: @groups=&sort_course_groups($courseid,@groups);
10218: } else {
10219: if (! defined($usection)) {
10220: $section=&getsection($udom,$uname,$courseid);
10221: } else {
10222: $section = $usection;
10223: }
10224: @groups = &get_users_groups($udom,$uname,$courseid);
10225: }
10226:
10227: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
10228: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
10229: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
10230:
10231: $courselevel=$courseid.'.'.$spacequalifierrest;
10232: my $courselevelr=$courseid.'.'.$symbparm;
10233: $courselevelm=$courseid.'.'.$mapparm;
10234:
10235: # ----------------------------------------------------------- first, check user
10236:
10237: my $userreply=&resdata($uname,$udom,'user',
10238: ([$courselevelr,'resource'],
10239: [$courselevelm,'map' ],
10240: [$courselevel, 'course' ]));
10241: if (defined($userreply)) { return &get_reply($userreply); }
10242:
10243: # ------------------------------------------------ second, check some of course
10244: my $coursereply;
10245: if (@groups > 0) {
10246: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
10247: $mapparm,$spacequalifierrest);
10248: if (defined($coursereply)) { return &get_reply($coursereply); }
10249: }
10250:
10251: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10252: $env{'course.'.$courseid.'.domain'},
10253: 'course',
10254: ([$seclevelr, 'resource'],
10255: [$seclevelm, 'map' ],
10256: [$seclevel, 'course' ],
10257: [$courselevelr,'resource']));
10258: if (defined($coursereply)) { return &get_reply($coursereply); }
10259:
10260: # ------------------------------------------------------ third, check map parms
10261: my %parmhash=();
10262: my $thisparm='';
10263: if (tie(%parmhash,'GDBM_File',
10264: $env{'request.course.fn'}.'_parms.db',
10265: &GDBM_READER(),0640)) {
10266: $thisparm=$parmhash{$symbparm};
10267: untie(%parmhash);
10268: }
10269: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
10270: }
10271: # ------------------------------------------ fourth, look in resource metadata
10272:
10273: $spacequalifierrest=~s/\./\_/;
10274: my $filename;
10275: if (!$symbparm) { $symbparm=&symbread(); }
10276: if ($symbparm) {
10277: $filename=(&decode_symb($symbparm))[2];
10278: } else {
10279: $filename=$env{'request.filename'};
10280: }
10281: my $metadata=&metadata($filename,$spacequalifierrest);
10282: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10283: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
10284: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
10285:
10286: # ---------------------------------------------- fourth, look in rest of course
10287: if ($symbparm && defined($courseid) &&
10288: $courseid eq $env{'request.course.id'}) {
10289: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
10290: $env{'course.'.$courseid.'.domain'},
10291: 'course',
10292: ([$courselevelm,'map' ],
10293: [$courselevel, 'course']));
10294: if (defined($coursereply)) { return &get_reply($coursereply); }
10295: }
10296: # ------------------------------------------------------------------ Cascade up
10297: unless ($space eq '0') {
10298: my @parts=split(/_/,$space);
10299: my $id=pop(@parts);
10300: my $part=join('_',@parts);
10301: if ($part eq '') { $part='0'; }
10302: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
10303: $symbparm,$udom,$uname,$section,1);
10304: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
10305: }
10306: if ($recurse) { return undef; }
10307: my $pack_def=&packages_tab_default($filename,$varname);
10308: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
10309: # ---------------------------------------------------- Any other user namespace
10310: } elsif ($realm eq 'environment') {
10311: # ----------------------------------------------------------------- environment
10312: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
10313: return $env{'environment.'.$spacequalifierrest};
10314: } else {
10315: if ($uname eq 'anonymous' && $udom eq '') {
10316: return '';
10317: }
10318: my %returnhash=&userenvironment($udom,$uname,
10319: $spacequalifierrest);
10320: return $returnhash{$spacequalifierrest};
10321: }
10322: } elsif ($realm eq 'system') {
10323: # ----------------------------------------------------------------- system.time
10324: if ($space eq 'time') {
10325: return time;
10326: }
10327: } elsif ($realm eq 'server') {
10328: # ----------------------------------------------------------------- system.time
10329: if ($space eq 'name') {
10330: return $ENV{'SERVER_NAME'};
10331: }
10332: }
10333: return '';
10334: }
10335:
10336: sub get_reply {
10337: my ($reply_value) = @_;
10338: if (ref($reply_value) eq 'ARRAY') {
10339: if (wantarray) {
10340: return @$reply_value;
10341: }
10342: return $reply_value->[0];
10343: } else {
10344: return $reply_value;
10345: }
10346: }
10347:
10348: sub check_group_parms {
10349: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
10350: my @groupitems = ();
10351: my $resultitem;
10352: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
10353: foreach my $group (@{$groups}) {
10354: foreach my $level (@levels) {
10355: my $item = $courseid.'.['.$group.'].'.$level->[0];
10356: push(@groupitems,[$item,$level->[1]]);
10357: }
10358: }
10359: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
10360: $env{'course.'.$courseid.'.domain'},
10361: 'course',@groupitems);
10362: return $coursereply;
10363: }
10364:
10365: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
10366: my ($courseid,@groups) = @_;
10367: @groups = sort(@groups);
10368: return @groups;
10369: }
10370:
10371: sub packages_tab_default {
10372: my ($uri,$varname)=@_;
10373: my (undef,$part,$name)=split(/\./,$varname);
10374:
10375: my (@extension,@specifics,$do_default);
10376: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
10377: my ($pack_type,$pack_part)=split(/_/,$package,2);
10378: if ($pack_type eq 'default') {
10379: $do_default=1;
10380: } elsif ($pack_type eq 'extension') {
10381: push(@extension,[$package,$pack_type,$pack_part]);
10382: } elsif ($pack_part eq $part || $pack_type eq 'part') {
10383: # only look at packages defaults for packages that this id is
10384: push(@specifics,[$package,$pack_type,$pack_part]);
10385: }
10386: }
10387: # first look for a package that matches the requested part id
10388: foreach my $package (@specifics) {
10389: my (undef,$pack_type,$pack_part)=@{$package};
10390: next if ($pack_part ne $part);
10391: if (defined($packagetab{"$pack_type&$name&default"})) {
10392: return $packagetab{"$pack_type&$name&default"};
10393: }
10394: }
10395: # look for any possible matching non extension_ package
10396: foreach my $package (@specifics) {
10397: my (undef,$pack_type,$pack_part)=@{$package};
10398: if (defined($packagetab{"$pack_type&$name&default"})) {
10399: return $packagetab{"$pack_type&$name&default"};
10400: }
10401: if ($pack_type eq 'part') { $pack_part='0'; }
10402: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
10403: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
10404: }
10405: }
10406: # look for any posible extension_ match
10407: foreach my $package (@extension) {
10408: my ($package,$pack_type)=@{$package};
10409: if (defined($packagetab{"$pack_type&$name&default"})) {
10410: return $packagetab{"$pack_type&$name&default"};
10411: }
10412: if (defined($packagetab{$package."&$name&default"})) {
10413: return $packagetab{$package."&$name&default"};
10414: }
10415: }
10416: # look for a global default setting
10417: if ($do_default && defined($packagetab{"default&$name&default"})) {
10418: return $packagetab{"default&$name&default"};
10419: }
10420: return undef;
10421: }
10422:
10423: sub add_prefix_and_part {
10424: my ($prefix,$part)=@_;
10425: my $keyroot;
10426: if (defined($prefix) && $prefix !~ /^__/) {
10427: # prefix that has a part already
10428: $keyroot=$prefix;
10429: } elsif (defined($prefix)) {
10430: # prefix that is missing a part
10431: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
10432: } else {
10433: # no prefix at all
10434: if (defined($part)) { $keyroot='_'.$part; }
10435: }
10436: return $keyroot;
10437: }
10438:
10439: # ---------------------------------------------------------------- Get metadata
10440:
10441: my %metaentry;
10442: my %importedpartids;
10443: sub metadata {
10444: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
10445: $uri=&declutter($uri);
10446: # if it is a non metadata possible uri return quickly
10447: if (($uri eq '') ||
10448: (($uri =~ m|^/*adm/|) &&
10449: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
10450: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
10451: return undef;
10452: }
10453: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
10454: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
10455: return undef;
10456: }
10457: my $filename=$uri;
10458: $uri=~s/\.meta$//;
10459: #
10460: # Is the metadata already cached?
10461: # Look at timestamp of caching
10462: # Everything is cached by the main uri, libraries are never directly cached
10463: #
10464: if (!defined($liburi)) {
10465: my ($result,$cached)=&is_cached_new('meta',$uri);
10466: if (defined($cached)) { return $result->{':'.$what}; }
10467: }
10468: {
10469: # Imported parts would go here
10470: my %importedids=();
10471: my @origfileimportpartids=();
10472: my $importedparts=0;
10473: #
10474: # Is this a recursive call for a library?
10475: #
10476: # if (! exists($metacache{$uri})) {
10477: # $metacache{$uri}={};
10478: # }
10479: my $cachetime = 60*60;
10480: if ($liburi) {
10481: $liburi=&declutter($liburi);
10482: $filename=$liburi;
10483: } else {
10484: &devalidate_cache_new('meta',$uri);
10485: undef(%metaentry);
10486: }
10487: my %metathesekeys=();
10488: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
10489: my $metastring;
10490: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
10491: my $which = &hreflocation('','/'.($liburi || $uri));
10492: $metastring =
10493: &Apache::lonnet::ssi_body($which,
10494: ('grade_target' => 'meta'));
10495: $cachetime = 1; # only want this cached in the child not long term
10496: } elsif (($uri !~ m -^(editupload)/-) &&
10497: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
10498: my $file=&filelocation('',&clutter($filename));
10499: #push(@{$metaentry{$uri.'.file'}},$file);
10500: $metastring=&getfile($file);
10501: }
10502: my $parser=HTML::LCParser->new(\$metastring);
10503: my $token;
10504: undef %metathesekeys;
10505: while ($token=$parser->get_token) {
10506: if ($token->[0] eq 'S') {
10507: if (defined($token->[2]->{'package'})) {
10508: #
10509: # This is a package - get package info
10510: #
10511: my $package=$token->[2]->{'package'};
10512: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10513: if (defined($token->[2]->{'id'})) {
10514: $keyroot.='_'.$token->[2]->{'id'};
10515: }
10516: if ($metaentry{':packages'}) {
10517: $metaentry{':packages'}.=','.$package.$keyroot;
10518: } else {
10519: $metaentry{':packages'}=$package.$keyroot;
10520: }
10521: foreach my $pack_entry (keys(%packagetab)) {
10522: my $part=$keyroot;
10523: $part=~s/^\_//;
10524: if ($pack_entry=~/^\Q$package\E\&/ ||
10525: $pack_entry=~/^\Q$package\E_0\&/) {
10526: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
10527: # ignore package.tab specified default values
10528: # here &package_tab_default() will fetch those
10529: if ($subp eq 'default') { next; }
10530: my $value=$packagetab{$pack_entry};
10531: my $unikey;
10532: if ($pack =~ /_0$/) {
10533: $unikey='parameter_0_'.$name;
10534: $part=0;
10535: } else {
10536: $unikey='parameter'.$keyroot.'_'.$name;
10537: }
10538: if ($subp eq 'display') {
10539: $value.=' [Part: '.$part.']';
10540: }
10541: $metaentry{':'.$unikey.'.part'}=$part;
10542: $metathesekeys{$unikey}=1;
10543: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10544: $metaentry{':'.$unikey.'.'.$subp}=$value;
10545: }
10546: if (defined($metaentry{':'.$unikey.'.default'})) {
10547: $metaentry{':'.$unikey}=
10548: $metaentry{':'.$unikey.'.default'};
10549: }
10550: }
10551: }
10552: } else {
10553: #
10554: # This is not a package - some other kind of start tag
10555: #
10556: my $entry=$token->[1];
10557: my $unikey='';
10558:
10559: if ($entry eq 'import') {
10560: #
10561: # Importing a library here
10562: #
10563: my $location=$parser->get_text('/import');
10564: my $dir=$filename;
10565: $dir=~s|[^/]*$||;
10566: $location=&filelocation($dir,$location);
10567:
10568: my $importmode=$token->[2]->{'importmode'};
10569: if ($importmode eq 'problem') {
10570: # Import as problem/response
10571: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10572: } elsif ($importmode eq 'part') {
10573: # Import as part(s)
10574: $importedparts=1;
10575: # We need to get the original file and the imported file to get the part order correct
10576: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
10577: # Load and inspect original file
10578: if ($#origfileimportpartids<0) {
10579: undef(%importedpartids);
10580: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
10581: my $origfile=&getfile($origfilelocation);
10582: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10583: }
10584:
10585: # Load and inspect imported file
10586: my $impfile=&getfile($location);
10587: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
10588: if ($#impfilepartids>=0) {
10589: # This problem had parts
10590: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
10591: } else {
10592: # Importing by turning a single problem into a problem part
10593: # It gets the import-tags ID as part-ID
10594: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
10595: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
10596: }
10597: } else {
10598: # Normal import
10599: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
10600: if (defined($token->[2]->{'id'})) {
10601: $unikey.='_'.$token->[2]->{'id'};
10602: }
10603: }
10604:
10605: if ($depthcount<20) {
10606: my $metadata =
10607: &metadata($uri,'keys', $location,$unikey,
10608: $depthcount+1);
10609: foreach my $meta (split(',',$metadata)) {
10610: $metaentry{':'.$meta}=$metaentry{':'.$meta};
10611: $metathesekeys{$meta}=1;
10612: }
10613:
10614: }
10615: } else {
10616: #
10617: # Not importing, some other kind of non-package, non-library start tag
10618: #
10619: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
10620: if (defined($token->[2]->{'id'})) {
10621: $unikey.='_'.$token->[2]->{'id'};
10622: }
10623: if (defined($token->[2]->{'name'})) {
10624: $unikey.='_'.$token->[2]->{'name'};
10625: }
10626: $metathesekeys{$unikey}=1;
10627: foreach my $param (@{$token->[3]}) {
10628: $metaentry{':'.$unikey.'.'.$param} =
10629: $token->[2]->{$param};
10630: }
10631: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
10632: my $default=$metaentry{':'.$unikey.'.default'};
10633: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
10634: # only ws inside the tag, and not in default, so use default
10635: # as value
10636: $metaentry{':'.$unikey}=$default;
10637: } elsif ( $internaltext =~ /\S/ ) {
10638: # something interesting inside the tag
10639: $metaentry{':'.$unikey}=$internaltext;
10640: } else {
10641: # no interesting values, don't set a default
10642: }
10643: # end of not-a-package not-a-library import
10644: }
10645: # end of not-a-package start tag
10646: }
10647: # the next is the end of "start tag"
10648: }
10649: }
10650: my ($extension) = ($uri =~ /\.(\w+)$/);
10651: $extension = lc($extension);
10652: if ($extension eq 'htm') { $extension='html'; }
10653:
10654: foreach my $key (keys(%packagetab)) {
10655: #no specific packages #how's our extension
10656: if ($key!~/^extension_\Q$extension\E&/) { next; }
10657: &metadata_create_package_def($uri,$key,'extension_'.$extension,
10658: \%metathesekeys);
10659: }
10660:
10661: if (!exists($metaentry{':packages'})
10662: || $packagetab{"import_defaults&extension_$extension"}) {
10663: foreach my $key (keys(%packagetab)) {
10664: #no specific packages well let's get default then
10665: if ($key!~/^default&/) { next; }
10666: &metadata_create_package_def($uri,$key,'default',
10667: \%metathesekeys);
10668: }
10669: }
10670: # are there custom rights to evaluate
10671: if ($metaentry{':copyright'} eq 'custom') {
10672:
10673: #
10674: # Importing a rights file here
10675: #
10676: unless ($depthcount) {
10677: my $location=$metaentry{':customdistributionfile'};
10678: my $dir=$filename;
10679: $dir=~s|[^/]*$||;
10680: $location=&filelocation($dir,$location);
10681: my $rights_metadata =
10682: &metadata($uri,'keys',$location,'_rights',
10683: $depthcount+1);
10684: foreach my $rights (split(',',$rights_metadata)) {
10685: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
10686: $metathesekeys{$rights}=1;
10687: }
10688: }
10689: }
10690: # uniqifiy package listing
10691: my %seen;
10692: my @uniq_packages =
10693: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
10694: $metaentry{':packages'} = join(',',@uniq_packages);
10695:
10696: if ($importedparts) {
10697: # We had imported parts and need to rebuild partorder
10698: $metaentry{':partorder'}='';
10699: $metathesekeys{'partorder'}=1;
10700: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
10701: if ($origfileimportpartids[$index] eq 'part') {
10702: # original part, part of the problem
10703: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
10704: } else {
10705: # we have imported parts at this position
10706: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
10707: }
10708: }
10709: $metaentry{':partorder'}=~s/^\,//;
10710: }
10711:
10712: $metaentry{':keys'} = join(',',keys(%metathesekeys));
10713: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
10714: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
10715: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
10716: # this is the end of "was not already recently cached
10717: }
10718: return $metaentry{':'.$what};
10719: }
10720:
10721: sub metadata_create_package_def {
10722: my ($uri,$key,$package,$metathesekeys)=@_;
10723: my ($pack,$name,$subp)=split(/\&/,$key);
10724: if ($subp eq 'default') { next; }
10725:
10726: if (defined($metaentry{':packages'})) {
10727: $metaentry{':packages'}.=','.$package;
10728: } else {
10729: $metaentry{':packages'}=$package;
10730: }
10731: my $value=$packagetab{$key};
10732: my $unikey;
10733: $unikey='parameter_0_'.$name;
10734: $metaentry{':'.$unikey.'.part'}=0;
10735: $$metathesekeys{$unikey}=1;
10736: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
10737: $metaentry{':'.$unikey.'.'.$subp}=$value;
10738: }
10739: if (defined($metaentry{':'.$unikey.'.default'})) {
10740: $metaentry{':'.$unikey}=
10741: $metaentry{':'.$unikey.'.default'};
10742: }
10743: }
10744:
10745: sub metadata_generate_part0 {
10746: my ($metadata,$metacache,$uri) = @_;
10747: my %allnames;
10748: foreach my $metakey (keys(%$metadata)) {
10749: if ($metakey=~/^parameter\_(.*)/) {
10750: my $part=$$metacache{':'.$metakey.'.part'};
10751: my $name=$$metacache{':'.$metakey.'.name'};
10752: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
10753: $allnames{$name}=$part;
10754: }
10755: }
10756: }
10757: foreach my $name (keys(%allnames)) {
10758: $$metadata{"parameter_0_$name"}=1;
10759: my $key=":parameter_0_$name";
10760: $$metacache{"$key.part"}='0';
10761: $$metacache{"$key.name"}=$name;
10762: $$metacache{"$key.type"}=$$metacache{':parameter_'.
10763: $allnames{$name}.'_'.$name.
10764: '.type'};
10765: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
10766: '.display'};
10767: my $expr='[Part: '.$allnames{$name}.']';
10768: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
10769: $$metacache{"$key.display"}=$olddis;
10770: }
10771: }
10772:
10773: # ------------------------------------------------------ Devalidate title cache
10774:
10775: sub devalidate_title_cache {
10776: my ($url)=@_;
10777: if (!$env{'request.course.id'}) { return; }
10778: my $symb=&symbread($url);
10779: if (!$symb) { return; }
10780: my $key=$env{'request.course.id'}."\0".$symb;
10781: &devalidate_cache_new('title',$key);
10782: }
10783:
10784: # ------------------------------------------------- Get the title of a course
10785:
10786: sub current_course_title {
10787: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
10788: }
10789: # ------------------------------------------------- Get the title of a resource
10790:
10791: sub gettitle {
10792: my $urlsymb=shift;
10793: my $symb=&symbread($urlsymb);
10794: if ($symb) {
10795: my $key=$env{'request.course.id'}."\0".$symb;
10796: my ($result,$cached)=&is_cached_new('title',$key);
10797: if (defined($cached)) {
10798: return $result;
10799: }
10800: my ($map,$resid,$url)=&decode_symb($symb);
10801: my $title='';
10802: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
10803: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
10804: } else {
10805: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10806: &GDBM_READER(),0640)) {
10807: my $mapid=$bighash{'map_pc_'.&clutter($map)};
10808: $title=$bighash{'title_'.$mapid.'.'.$resid};
10809: untie(%bighash);
10810: }
10811: }
10812: $title=~s/\&colon\;/\:/gs;
10813: if ($title) {
10814: # Remember both $symb and $title for dynamic metadata
10815: $accesshash{$symb.'___crstitle'}=$title;
10816: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
10817: # Cache this title and then return it
10818: return &do_cache_new('title',$key,$title,600);
10819: }
10820: $urlsymb=$url;
10821: }
10822: my $title=&metadata($urlsymb,'title');
10823: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
10824: return $title;
10825: }
10826:
10827: sub get_slot {
10828: my ($which,$cnum,$cdom)=@_;
10829: if (!$cnum || !$cdom) {
10830: (undef,my $courseid)=&whichuser();
10831: $cdom=$env{'course.'.$courseid.'.domain'};
10832: $cnum=$env{'course.'.$courseid.'.num'};
10833: }
10834: my $key=join("\0",'slots',$cdom,$cnum,$which);
10835: my %slotinfo;
10836: if (exists($remembered{$key})) {
10837: $slotinfo{$which} = $remembered{$key};
10838: } else {
10839: %slotinfo=&get('slots',[$which],$cdom,$cnum);
10840: &Apache::lonhomework::showhash(%slotinfo);
10841: my ($tmp)=keys(%slotinfo);
10842: if ($tmp=~/^error:/) { return (); }
10843: $remembered{$key} = $slotinfo{$which};
10844: }
10845: if (ref($slotinfo{$which}) eq 'HASH') {
10846: return %{$slotinfo{$which}};
10847: }
10848: return $slotinfo{$which};
10849: }
10850:
10851: sub get_reservable_slots {
10852: my ($cnum,$cdom,$uname,$udom) = @_;
10853: my $now = time;
10854: my $reservable_info;
10855: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
10856: if (exists($remembered{$key})) {
10857: $reservable_info = $remembered{$key};
10858: } else {
10859: my %resv;
10860: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
10861: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
10862: $reservable_info = \%resv;
10863: $remembered{$key} = $reservable_info;
10864: }
10865: return $reservable_info;
10866: }
10867:
10868: sub get_course_slots {
10869: my ($cnum,$cdom) = @_;
10870: my $hashid=$cnum.':'.$cdom;
10871: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
10872: if (defined($cached)) {
10873: if (ref($result) eq 'HASH') {
10874: return %{$result};
10875: }
10876: } else {
10877: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
10878: my ($tmp) = keys(%slots);
10879: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
10880: &do_cache_new('allslots',$hashid,\%slots,600);
10881: return %slots;
10882: }
10883: }
10884: return;
10885: }
10886:
10887: sub devalidate_slots_cache {
10888: my ($cnum,$cdom)=@_;
10889: my $hashid=$cnum.':'.$cdom;
10890: &devalidate_cache_new('allslots',$hashid);
10891: }
10892:
10893: sub get_coursechange {
10894: my ($cdom,$cnum) = @_;
10895: if ($cdom eq '' || $cnum eq '') {
10896: return unless ($env{'request.course.id'});
10897: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
10898: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
10899: }
10900: my $hashid=$cdom.'_'.$cnum;
10901: my ($change,$cached)=&is_cached_new('crschange',$hashid);
10902: if ((defined($cached)) && ($change ne '')) {
10903: return $change;
10904: } else {
10905: my %crshash;
10906: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
10907: if ($crshash{'internal.contentchange'} eq '') {
10908: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
10909: if ($change eq '') {
10910: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
10911: $change = $crshash{'internal.created'};
10912: }
10913: } else {
10914: $change = $crshash{'internal.contentchange'};
10915: }
10916: my $cachetime = 600;
10917: &do_cache_new('crschange',$hashid,$change,$cachetime);
10918: }
10919: return $change;
10920: }
10921:
10922: sub devalidate_coursechange_cache {
10923: my ($cnum,$cdom)=@_;
10924: my $hashid=$cnum.':'.$cdom;
10925: &devalidate_cache_new('crschange',$hashid);
10926: }
10927:
10928: # ------------------------------------------------- Update symbolic store links
10929:
10930: sub symblist {
10931: my ($mapname,%newhash)=@_;
10932: $mapname=&deversion(&declutter($mapname));
10933: my %hash;
10934: if (($env{'request.course.fn'}) && (%newhash)) {
10935: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
10936: &GDBM_WRCREAT(),0640)) {
10937: foreach my $url (keys(%newhash)) {
10938: next if ($url eq 'last_known'
10939: && $env{'form.no_update_last_known'});
10940: $hash{declutter($url)}=&encode_symb($mapname,
10941: $newhash{$url}->[1],
10942: $newhash{$url}->[0]);
10943: }
10944: if (untie(%hash)) {
10945: return 'ok';
10946: }
10947: }
10948: }
10949: return 'error';
10950: }
10951:
10952: # --------------------------------------------------------------- Verify a symb
10953:
10954: sub symbverify {
10955: my ($symb,$thisurl,$encstate)=@_;
10956: my $thisfn=$thisurl;
10957: $thisfn=&declutter($thisfn);
10958: # direct jump to resource in page or to a sequence - will construct own symbs
10959: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
10960: # check URL part
10961: my ($map,$resid,$url)=&decode_symb($symb);
10962:
10963: unless ($url eq $thisfn) { return 0; }
10964:
10965: $symb=&symbclean($symb);
10966: $thisurl=&deversion($thisurl);
10967: $thisfn=&deversion($thisfn);
10968:
10969: my %bighash;
10970: my $okay=0;
10971:
10972: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10973: &GDBM_READER(),0640)) {
10974: my $noclutter;
10975: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
10976: $thisurl =~ s/\?.+$//;
10977: if ($map =~ m{^uploaded/.+\.page$}) {
10978: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
10979: $thisurl =~ s{^\Qhttp://https://\E}{https://};
10980: $noclutter = 1;
10981: }
10982: }
10983: my $ids;
10984: if ($noclutter) {
10985: $ids=$bighash{'ids_'.$thisurl};
10986: } else {
10987: $ids=$bighash{'ids_'.&clutter($thisurl)};
10988: }
10989: unless ($ids) {
10990: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
10991: $ids=$bighash{$idkey};
10992: }
10993: if ($ids) {
10994: # ------------------------------------------------------------------- Has ID(s)
10995: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10996: $symb =~ s/\?.+$//;
10997: }
10998: foreach my $id (split(/\,/,$ids)) {
10999: my ($mapid,$resid)=split(/\./,$id);
11000: if (
11001: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
11002: eq $symb) {
11003: if (ref($encstate)) {
11004: $$encstate = $bighash{'encrypted_'.$id};
11005: }
11006: if (($env{'request.role.adv'}) ||
11007: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
11008: ($thisurl eq '/adm/navmaps')) {
11009: $okay=1;
11010: last;
11011: }
11012: }
11013: }
11014: }
11015: untie(%bighash);
11016: }
11017: return $okay;
11018: }
11019:
11020: # --------------------------------------------------------------- Clean-up symb
11021:
11022: sub symbclean {
11023: my $symb=shift;
11024: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11025: # remove version from map
11026: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
11027:
11028: # remove version from URL
11029: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
11030:
11031: # remove wrapper
11032:
11033: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
11034: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
11035: return $symb;
11036: }
11037:
11038: # ---------------------------------------------- Split symb to find map and url
11039:
11040: sub encode_symb {
11041: my ($map,$resid,$url)=@_;
11042: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
11043: }
11044:
11045: sub decode_symb {
11046: my $symb=shift;
11047: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
11048: my ($map,$resid,$url)=split(/___/,$symb);
11049: return (&fixversion($map),$resid,&fixversion($url));
11050: }
11051:
11052: sub fixversion {
11053: my $fn=shift;
11054: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
11055: my %bighash;
11056: my $uri=&clutter($fn);
11057: my $key=$env{'request.course.id'}.'_'.$uri;
11058: # is this cached?
11059: my ($result,$cached)=&is_cached_new('courseresversion',$key);
11060: if (defined($cached)) { return $result; }
11061: # unfortunately not cached, or expired
11062: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11063: &GDBM_READER(),0640)) {
11064: if ($bighash{'version_'.$uri}) {
11065: my $version=$bighash{'version_'.$uri};
11066: unless (($version eq 'mostrecent') ||
11067: ($version==&getversion($uri))) {
11068: $uri=~s/\.(\w+)$/\.$version\.$1/;
11069: }
11070: }
11071: untie %bighash;
11072: }
11073: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
11074: }
11075:
11076: sub deversion {
11077: my $url=shift;
11078: $url=~s/\.\d+\.(\w+)$/\.$1/;
11079: return $url;
11080: }
11081:
11082: # ------------------------------------------------------ Return symb list entry
11083:
11084: sub symbread {
11085: my ($thisfn,$donotrecurse)=@_;
11086: my $cache_str='request.symbread.cached.'.$thisfn;
11087: if (defined($env{$cache_str})) { return $env{$cache_str}; }
11088: # no filename provided? try from environment
11089: unless ($thisfn) {
11090: if ($env{'request.symb'}) {
11091: return $env{$cache_str}=&symbclean($env{'request.symb'});
11092: }
11093: $thisfn=$env{'request.filename'};
11094: }
11095: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11096: # is that filename actually a symb? Verify, clean, and return
11097: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
11098: if (&symbverify($thisfn,$1)) {
11099: return $env{$cache_str}=&symbclean($thisfn);
11100: }
11101: }
11102: $thisfn=declutter($thisfn);
11103: my %hash;
11104: my %bighash;
11105: my $syval='';
11106: if (($env{'request.course.fn'}) && ($thisfn)) {
11107: my $targetfn = $thisfn;
11108: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
11109: $targetfn = 'adm/wrapper/'.$thisfn;
11110: }
11111: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
11112: $targetfn=$1;
11113: }
11114: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
11115: &GDBM_READER(),0640)) {
11116: $syval=$hash{$targetfn};
11117: untie(%hash);
11118: }
11119: # ---------------------------------------------------------- There was an entry
11120: if ($syval) {
11121: #unless ($syval=~/\_\d+$/) {
11122: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
11123: #&appenv({'request.ambiguous' => $thisfn});
11124: #return $env{$cache_str}='';
11125: #}
11126: #$syval.=$1;
11127: #}
11128: } else {
11129: # ------------------------------------------------------- Was not in symb table
11130: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11131: &GDBM_READER(),0640)) {
11132: # ---------------------------------------------- Get ID(s) for current resource
11133: my $ids=$bighash{'ids_'.&clutter($thisfn)};
11134: unless ($ids) {
11135: $ids=$bighash{'ids_/'.$thisfn};
11136: }
11137: unless ($ids) {
11138: # alias?
11139: $ids=$bighash{'mapalias_'.$thisfn};
11140: }
11141: if ($ids) {
11142: # ------------------------------------------------------------------- Has ID(s)
11143: my @possibilities=split(/\,/,$ids);
11144: if ($#possibilities==0) {
11145: # ----------------------------------------------- There is only one possibility
11146: my ($mapid,$resid)=split(/\./,$ids);
11147: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11148: $resid,$thisfn);
11149: } elsif (!$donotrecurse) {
11150: # ------------------------------------------ There is more than one possibility
11151: my $realpossible=0;
11152: foreach my $id (@possibilities) {
11153: my $file=$bighash{'src_'.$id};
11154: if (&allowed('bre',$file)) {
11155: my ($mapid,$resid)=split(/\./,$id);
11156: if ($bighash{'map_type_'.$mapid} ne 'page') {
11157: $realpossible++;
11158: $syval=&encode_symb($bighash{'map_id_'.$mapid},
11159: $resid,$thisfn);
11160: }
11161: }
11162: }
11163: if ($realpossible!=1) { $syval=''; }
11164: } else {
11165: $syval='';
11166: }
11167: }
11168: untie(%bighash)
11169: }
11170: }
11171: if ($syval) {
11172: return $env{$cache_str}=$syval;
11173: }
11174: }
11175: &appenv({'request.ambiguous' => $thisfn});
11176: return $env{$cache_str}='';
11177: }
11178:
11179: # ---------------------------------------------------------- Return random seed
11180:
11181: sub numval {
11182: my $txt=shift;
11183: $txt=~tr/A-J/0-9/;
11184: $txt=~tr/a-j/0-9/;
11185: $txt=~tr/K-T/0-9/;
11186: $txt=~tr/k-t/0-9/;
11187: $txt=~tr/U-Z/0-5/;
11188: $txt=~tr/u-z/0-5/;
11189: $txt=~s/\D//g;
11190: if ($_64bit) { if ($txt > 2**32) { return -1; } }
11191: return int($txt);
11192: }
11193:
11194: sub numval2 {
11195: my $txt=shift;
11196: $txt=~tr/A-J/0-9/;
11197: $txt=~tr/a-j/0-9/;
11198: $txt=~tr/K-T/0-9/;
11199: $txt=~tr/k-t/0-9/;
11200: $txt=~tr/U-Z/0-5/;
11201: $txt=~tr/u-z/0-5/;
11202: $txt=~s/\D//g;
11203: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11204: my $total;
11205: foreach my $val (@txts) { $total+=$val; }
11206: if ($_64bit) { if ($total > 2**32) { return -1; } }
11207: return int($total);
11208: }
11209:
11210: sub numval3 {
11211: use integer;
11212: my $txt=shift;
11213: $txt=~tr/A-J/0-9/;
11214: $txt=~tr/a-j/0-9/;
11215: $txt=~tr/K-T/0-9/;
11216: $txt=~tr/k-t/0-9/;
11217: $txt=~tr/U-Z/0-5/;
11218: $txt=~tr/u-z/0-5/;
11219: $txt=~s/\D//g;
11220: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
11221: my $total;
11222: foreach my $val (@txts) { $total+=$val; }
11223: if ($_64bit) { $total=(($total<<32)>>32); }
11224: return $total;
11225: }
11226:
11227: sub digest {
11228: my ($data)=@_;
11229: my $digest=&Digest::MD5::md5($data);
11230: my ($a,$b,$c,$d)=unpack("iiii",$digest);
11231: my ($e,$f);
11232: {
11233: use integer;
11234: $e=($a+$b);
11235: $f=($c+$d);
11236: if ($_64bit) {
11237: $e=(($e<<32)>>32);
11238: $f=(($f<<32)>>32);
11239: }
11240: }
11241: if (wantarray) {
11242: return ($e,$f);
11243: } else {
11244: my $g;
11245: {
11246: use integer;
11247: $g=($e+$f);
11248: if ($_64bit) {
11249: $g=(($g<<32)>>32);
11250: }
11251: }
11252: return $g;
11253: }
11254: }
11255:
11256: sub latest_rnd_algorithm_id {
11257: return '64bit5';
11258: }
11259:
11260: sub get_rand_alg {
11261: my ($courseid)=@_;
11262: if (!$courseid) { $courseid=(&whichuser())[1]; }
11263: if ($courseid) {
11264: return $env{"course.$courseid.rndseed"};
11265: }
11266: return &latest_rnd_algorithm_id();
11267: }
11268:
11269: sub validCODE {
11270: my ($CODE)=@_;
11271: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
11272: return 0;
11273: }
11274:
11275: sub getCODE {
11276: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
11277: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
11278: defined($Apache::lonhomework::parsing_a_task) ) &&
11279: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
11280: return $Apache::lonhomework::history{'resource.CODE'};
11281: }
11282: return undef;
11283: }
11284: #
11285: # Determines the random seed for a specific context:
11286: #
11287: # parameters:
11288: # symb - in course context the symb for the seed.
11289: # course_id - The course id of the form domain_coursenum.
11290: # domain - Domain for the user.
11291: # course - Course for the user.
11292: # cenv - environment of the course.
11293: #
11294: # NOTE:
11295: # All parameters are picked out of the environment if missing
11296: # or not defined.
11297: # If a symb cannot be determined the current time is used instead.
11298: #
11299: # For a given well defined symb, courside, domain, username,
11300: # and course environment, the seed is reproducible.
11301: #
11302: sub rndseed {
11303: my ($symb,$courseid,$domain,$username, $cenv)=@_;
11304: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
11305: if (!defined($symb)) {
11306: unless ($symb=$wsymb) { return time; }
11307: }
11308: if (!defined $courseid) {
11309: $courseid=$wcourseid;
11310: }
11311: if (!defined $domain) { $domain=$wdomain; }
11312: if (!defined $username) { $username=$wusername }
11313:
11314: my $which;
11315: if (defined($cenv->{'rndseed'})) {
11316: $which = $cenv->{'rndseed'};
11317: } else {
11318: $which =&get_rand_alg($courseid);
11319: }
11320: if (defined(&getCODE())) {
11321:
11322: if ($which eq '64bit5') {
11323: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
11324: } elsif ($which eq '64bit4') {
11325: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
11326: } else {
11327: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
11328: }
11329: } elsif ($which eq '64bit5') {
11330: return &rndseed_64bit5($symb,$courseid,$domain,$username);
11331: } elsif ($which eq '64bit4') {
11332: return &rndseed_64bit4($symb,$courseid,$domain,$username);
11333: } elsif ($which eq '64bit3') {
11334: return &rndseed_64bit3($symb,$courseid,$domain,$username);
11335: } elsif ($which eq '64bit2') {
11336: return &rndseed_64bit2($symb,$courseid,$domain,$username);
11337: } elsif ($which eq '64bit') {
11338: return &rndseed_64bit($symb,$courseid,$domain,$username);
11339: }
11340: return &rndseed_32bit($symb,$courseid,$domain,$username);
11341: }
11342:
11343: sub rndseed_32bit {
11344: my ($symb,$courseid,$domain,$username)=@_;
11345: {
11346: use integer;
11347: my $symbchck=unpack("%32C*",$symb) << 27;
11348: my $symbseed=numval($symb) << 22;
11349: my $namechck=unpack("%32C*",$username) << 17;
11350: my $nameseed=numval($username) << 12;
11351: my $domainseed=unpack("%32C*",$domain) << 7;
11352: my $courseseed=unpack("%32C*",$courseid);
11353: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
11354: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11355: #&logthis("rndseed :$num:$symb");
11356: if ($_64bit) { $num=(($num<<32)>>32); }
11357: return $num;
11358: }
11359: }
11360:
11361: sub rndseed_64bit {
11362: my ($symb,$courseid,$domain,$username)=@_;
11363: {
11364: use integer;
11365: my $symbchck=unpack("%32S*",$symb) << 21;
11366: my $symbseed=numval($symb) << 10;
11367: my $namechck=unpack("%32S*",$username);
11368:
11369: my $nameseed=numval($username) << 21;
11370: my $domainseed=unpack("%32S*",$domain) << 10;
11371: my $courseseed=unpack("%32S*",$courseid);
11372:
11373: my $num1=$symbchck+$symbseed+$namechck;
11374: my $num2=$nameseed+$domainseed+$courseseed;
11375: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11376: #&logthis("rndseed :$num:$symb");
11377: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11378: return "$num1,$num2";
11379: }
11380: }
11381:
11382: sub rndseed_64bit2 {
11383: my ($symb,$courseid,$domain,$username)=@_;
11384: {
11385: use integer;
11386: # strings need to be an even # of cahracters long, it it is odd the
11387: # last characters gets thrown away
11388: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11389: my $symbseed=numval($symb) << 10;
11390: my $namechck=unpack("%32S*",$username.' ');
11391:
11392: my $nameseed=numval($username) << 21;
11393: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11394: my $courseseed=unpack("%32S*",$courseid.' ');
11395:
11396: my $num1=$symbchck+$symbseed+$namechck;
11397: my $num2=$nameseed+$domainseed+$courseseed;
11398: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11399: #&logthis("rndseed :$num:$symb");
11400: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11401: return "$num1,$num2";
11402: }
11403: }
11404:
11405: sub rndseed_64bit3 {
11406: my ($symb,$courseid,$domain,$username)=@_;
11407: {
11408: use integer;
11409: # strings need to be an even # of cahracters long, it it is odd the
11410: # last characters gets thrown away
11411: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11412: my $symbseed=numval2($symb) << 10;
11413: my $namechck=unpack("%32S*",$username.' ');
11414:
11415: my $nameseed=numval2($username) << 21;
11416: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11417: my $courseseed=unpack("%32S*",$courseid.' ');
11418:
11419: my $num1=$symbchck+$symbseed+$namechck;
11420: my $num2=$nameseed+$domainseed+$courseseed;
11421: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11422: #&logthis("rndseed :$num1:$num2:$_64bit");
11423: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11424:
11425: return "$num1:$num2";
11426: }
11427: }
11428:
11429: sub rndseed_64bit4 {
11430: my ($symb,$courseid,$domain,$username)=@_;
11431: {
11432: use integer;
11433: # strings need to be an even # of cahracters long, it it is odd the
11434: # last characters gets thrown away
11435: my $symbchck=unpack("%32S*",$symb.' ') << 21;
11436: my $symbseed=numval3($symb) << 10;
11437: my $namechck=unpack("%32S*",$username.' ');
11438:
11439: my $nameseed=numval3($username) << 21;
11440: my $domainseed=unpack("%32S*",$domain.' ') << 10;
11441: my $courseseed=unpack("%32S*",$courseid.' ');
11442:
11443: my $num1=$symbchck+$symbseed+$namechck;
11444: my $num2=$nameseed+$domainseed+$courseseed;
11445: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
11446: #&logthis("rndseed :$num1:$num2:$_64bit");
11447: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
11448:
11449: return "$num1:$num2";
11450: }
11451: }
11452:
11453: sub rndseed_64bit5 {
11454: my ($symb,$courseid,$domain,$username)=@_;
11455: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
11456: return "$num1:$num2";
11457: }
11458:
11459: sub rndseed_CODE_64bit {
11460: my ($symb,$courseid,$domain,$username)=@_;
11461: {
11462: use integer;
11463: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11464: my $symbseed=numval2($symb);
11465: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11466: my $CODEseed=numval(&getCODE());
11467: my $courseseed=unpack("%32S*",$courseid.' ');
11468: my $num1=$symbseed+$CODEchck;
11469: my $num2=$CODEseed+$courseseed+$symbchck;
11470: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11471: #&logthis("rndseed :$num1:$num2:$symb");
11472: if ($_64bit) { $num1=(($num1<<32)>>32); }
11473: if ($_64bit) { $num2=(($num2<<32)>>32); }
11474: return "$num1:$num2";
11475: }
11476: }
11477:
11478: sub rndseed_CODE_64bit4 {
11479: my ($symb,$courseid,$domain,$username)=@_;
11480: {
11481: use integer;
11482: my $symbchck=unpack("%32S*",$symb.' ') << 16;
11483: my $symbseed=numval3($symb);
11484: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
11485: my $CODEseed=numval3(&getCODE());
11486: my $courseseed=unpack("%32S*",$courseid.' ');
11487: my $num1=$symbseed+$CODEchck;
11488: my $num2=$CODEseed+$courseseed+$symbchck;
11489: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
11490: #&logthis("rndseed :$num1:$num2:$symb");
11491: if ($_64bit) { $num1=(($num1<<32)>>32); }
11492: if ($_64bit) { $num2=(($num2<<32)>>32); }
11493: return "$num1:$num2";
11494: }
11495: }
11496:
11497: sub rndseed_CODE_64bit5 {
11498: my ($symb,$courseid,$domain,$username)=@_;
11499: my $code = &getCODE();
11500: my ($num1,$num2)=&digest("$symb,$courseid,$code");
11501: return "$num1:$num2";
11502: }
11503:
11504: sub setup_random_from_rndseed {
11505: my ($rndseed)=@_;
11506: if ($rndseed =~/([,:])/) {
11507: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
11508: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
11509: &Math::Random::random_set_seed_from_phrase($rndseed);
11510: } else {
11511: &Math::Random::random_set_seed($num1,$num2);
11512: }
11513: } else {
11514: &Math::Random::random_set_seed_from_phrase($rndseed);
11515: }
11516: }
11517:
11518: sub latest_receipt_algorithm_id {
11519: return 'receipt3';
11520: }
11521:
11522: sub recunique {
11523: my $fucourseid=shift;
11524: my $unique;
11525: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
11526: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11527: $unique=$env{"course.$fucourseid.internal.encseed"};
11528: } else {
11529: $unique=$perlvar{'lonReceipt'};
11530: }
11531: return unpack("%32C*",$unique);
11532: }
11533:
11534: sub recprefix {
11535: my $fucourseid=shift;
11536: my $prefix;
11537: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
11538: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
11539: $prefix=$env{"course.$fucourseid.internal.encpref"};
11540: } else {
11541: $prefix=$perlvar{'lonHostID'};
11542: }
11543: return unpack("%32C*",$prefix);
11544: }
11545:
11546: sub ireceipt {
11547: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
11548:
11549: my $return =&recprefix($fucourseid).'-';
11550:
11551: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
11552: $env{'request.state'} eq 'construct') {
11553: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
11554: return $return;
11555: }
11556:
11557: my $cuname=unpack("%32C*",$funame);
11558: my $cudom=unpack("%32C*",$fudom);
11559: my $cucourseid=unpack("%32C*",$fucourseid);
11560: my $cusymb=unpack("%32C*",$fusymb);
11561: my $cunique=&recunique($fucourseid);
11562: my $cpart=unpack("%32S*",$part);
11563: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
11564:
11565: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
11566:
11567: $return.= ($cunique%$cuname+
11568: $cunique%$cudom+
11569: $cusymb%$cuname+
11570: $cusymb%$cudom+
11571: $cucourseid%$cuname+
11572: $cucourseid%$cudom+
11573: $cpart%$cuname+
11574: $cpart%$cudom);
11575: } else {
11576: $return.= ($cunique%$cuname+
11577: $cunique%$cudom+
11578: $cusymb%$cuname+
11579: $cusymb%$cudom+
11580: $cucourseid%$cuname+
11581: $cucourseid%$cudom);
11582: }
11583: return $return;
11584: }
11585:
11586: sub receipt {
11587: my ($part)=@_;
11588: my ($symb,$courseid,$domain,$name) = &whichuser();
11589: return &ireceipt($name,$domain,$courseid,$symb,$part);
11590: }
11591:
11592: sub whichuser {
11593: my ($passedsymb)=@_;
11594: my ($symb,$courseid,$domain,$name,$publicuser);
11595: if (defined($env{'form.grade_symb'})) {
11596: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
11597: my $allowed=&allowed('vgr',$tmp_courseid);
11598: if (!$allowed &&
11599: exists($env{'request.course.sec'}) &&
11600: $env{'request.course.sec'} !~ /^\s*$/) {
11601: $allowed=&allowed('vgr',$tmp_courseid.
11602: '/'.$env{'request.course.sec'});
11603: }
11604: if ($allowed) {
11605: ($symb)=&get_env_multiple('form.grade_symb');
11606: $courseid=$tmp_courseid;
11607: ($domain)=&get_env_multiple('form.grade_domain');
11608: ($name)=&get_env_multiple('form.grade_username');
11609: return ($symb,$courseid,$domain,$name,$publicuser);
11610: }
11611: }
11612: if (!$passedsymb) {
11613: $symb=&symbread();
11614: } else {
11615: $symb=$passedsymb;
11616: }
11617: $courseid=$env{'request.course.id'};
11618: $domain=$env{'user.domain'};
11619: $name=$env{'user.name'};
11620: if ($name eq 'public' && $domain eq 'public') {
11621: if (!defined($env{'form.username'})) {
11622: $env{'form.username'}.=time.rand(10000000);
11623: }
11624: $name.=$env{'form.username'};
11625: }
11626: return ($symb,$courseid,$domain,$name,$publicuser);
11627:
11628: }
11629:
11630: # ------------------------------------------------------------ Serves up a file
11631: # returns either the contents of the file or
11632: # -1 if the file doesn't exist
11633: #
11634: # if the target is a file that was uploaded via DOCS,
11635: # a check will be made to see if a current copy exists on the local server,
11636: # if it does this will be served, otherwise a copy will be retrieved from
11637: # the home server for the course and stored in /home/httpd/html/userfiles on
11638: # the local server.
11639:
11640: sub getfile {
11641: my ($file) = @_;
11642: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
11643: &repcopy($file);
11644: return &readfile($file);
11645: }
11646:
11647: sub repcopy_userfile {
11648: my ($file)=@_;
11649: my $londocroot = $perlvar{'lonDocRoot'};
11650: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
11651: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
11652: my ($cdom,$cnum,$filename) =
11653: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
11654: my $uri="/uploaded/$cdom/$cnum/$filename";
11655: if (-e "$file") {
11656: # we already have a local copy, check it out
11657: my @fileinfo = stat($file);
11658: my $rtncode;
11659: my $info;
11660: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
11661: if ($lwpresp ne 'ok') {
11662: # there is no such file anymore, even though we had a local copy
11663: if ($rtncode eq '404') {
11664: unlink($file);
11665: }
11666: return -1;
11667: }
11668: if ($info < $fileinfo[9]) {
11669: # nice, the file we have is up-to-date, just say okay
11670: return 'ok';
11671: } else {
11672: # the file is outdated, get rid of it
11673: unlink($file);
11674: }
11675: }
11676: # one way or the other, at this point, we don't have the file
11677: # construct the correct path for the file
11678: my @parts = ($cdom,$cnum);
11679: if ($filename =~ m|^(.+)/[^/]+$|) {
11680: push @parts, split(/\//,$1);
11681: }
11682: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
11683: foreach my $part (@parts) {
11684: $path .= '/'.$part;
11685: if (!-e $path) {
11686: mkdir($path,0770);
11687: }
11688: }
11689: # now the path exists for sure
11690: # get a user agent
11691: my $ua=new LWP::UserAgent;
11692: my $transferfile=$file.'.in.transfer';
11693: # FIXME: this should flock
11694: if (-e $transferfile) { return 'ok'; }
11695: my $request;
11696: $uri=~s/^\///;
11697: my $homeserver = &homeserver($cnum,$cdom);
11698: my $protocol = $protocol{$homeserver};
11699: $protocol = 'http' if ($protocol ne 'https');
11700: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
11701: my $response=$ua->request($request,$transferfile);
11702: # did it work?
11703: if ($response->is_error()) {
11704: unlink($transferfile);
11705: &logthis("Userfile repcopy failed for $uri");
11706: return -1;
11707: }
11708: # worked, rename the transfer file
11709: rename($transferfile,$file);
11710: return 'ok';
11711: }
11712:
11713: sub tokenwrapper {
11714: my $uri=shift;
11715: $uri=~s|^https?\://([^/]+)||;
11716: $uri=~s|^/||;
11717: $env{'user.environment'}=~/\/([^\/]+)\.id/;
11718: my $token=$1;
11719: my (undef,$udom,$uname,$file)=split('/',$uri,4);
11720: if ($udom && $uname && $file) {
11721: $file=~s|(\?\.*)*$||;
11722: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
11723: my $homeserver = &homeserver($uname,$udom);
11724: my $protocol = $protocol{$homeserver};
11725: $protocol = 'http' if ($protocol ne 'https');
11726: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
11727: (($uri=~/\?/)?'&':'?').'token='.$token.
11728: '&tokenissued='.$perlvar{'lonHostID'};
11729: } else {
11730: return '/adm/notfound.html';
11731: }
11732: }
11733:
11734: # call with reqtype HEAD: get last modification time
11735: # call with reqtype GET: get the file contents
11736: # Do not call this with reqtype GET for large files! It loads everything into memory
11737: #
11738: sub getuploaded {
11739: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
11740: $uri=~s/^\///;
11741: my $homeserver = &homeserver($cnum,$cdom);
11742: my $protocol = $protocol{$homeserver};
11743: $protocol = 'http' if ($protocol ne 'https');
11744: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
11745: my $ua=new LWP::UserAgent;
11746: my $request=new HTTP::Request($reqtype,$uri);
11747: my $response=$ua->request($request);
11748: $$rtncode = $response->code;
11749: if (! $response->is_success()) {
11750: return 'failed';
11751: }
11752: if ($reqtype eq 'HEAD') {
11753: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
11754: } elsif ($reqtype eq 'GET') {
11755: $$info = $response->content;
11756: }
11757: return 'ok';
11758: }
11759:
11760: sub readfile {
11761: my $file = shift;
11762: if ( (! -e $file ) || ($file eq '') ) { return -1; };
11763: my $fh;
11764: open($fh,"<$file");
11765: my $a='';
11766: while (my $line = <$fh>) { $a .= $line; }
11767: return $a;
11768: }
11769:
11770: sub filelocation {
11771: my ($dir,$file) = @_;
11772: my $location;
11773: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
11774:
11775: if ($file =~ m-^/adm/-) {
11776: $file=~s-^/adm/wrapper/-/-;
11777: $file=~s-^/adm/coursedocs/showdoc/-/-;
11778: }
11779:
11780: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
11781: $location = $file;
11782: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
11783: my ($udom,$uname,$filename)=
11784: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
11785: my $home=&homeserver($uname,$udom);
11786: my $is_me=0;
11787: my @ids=¤t_machine_ids();
11788: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
11789: if ($is_me) {
11790: $location=propath($udom,$uname).'/userfiles/'.$filename;
11791: } else {
11792: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
11793: $udom.'/'.$uname.'/'.$filename;
11794: }
11795: } elsif ($file =~ m-^/adm/-) {
11796: $location = $perlvar{'lonDocRoot'}.'/'.$file;
11797: } else {
11798: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
11799: $file=~s:^/(res|priv)/:/:;
11800: my $space=$1;
11801: if ( !( $file =~ m:^/:) ) {
11802: $location = $dir. '/'.$file;
11803: } else {
11804: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
11805: }
11806: }
11807: $location=~s://+:/:g; # remove duplicate /
11808: while ($location=~m{/\.\./}) {
11809: if ($location =~ m{/[^/]+/\.\./}) {
11810: $location=~ s{/[^/]+/\.\./}{/}g;
11811: } else {
11812: $location=~ s{/\.\./}{/}g;
11813: }
11814: } #remove dir/..
11815: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
11816: return $location;
11817: }
11818:
11819: sub hreflocation {
11820: my ($dir,$file)=@_;
11821: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
11822: $file=filelocation($dir,$file);
11823: } elsif ($file=~m-^/adm/-) {
11824: $file=~s-^/adm/wrapper/-/-;
11825: $file=~s-^/adm/coursedocs/showdoc/-/-;
11826: }
11827: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
11828: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
11829: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
11830: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
11831: {/uploaded/$1/$2/}x;
11832: }
11833: if ($file=~ m{^/userfiles/}) {
11834: $file =~ s{^/userfiles/}{/uploaded/};
11835: }
11836: return $file;
11837: }
11838:
11839:
11840:
11841:
11842:
11843: sub current_machine_domains {
11844: return &machine_domains(&hostname($perlvar{'lonHostID'}));
11845: }
11846:
11847: sub machine_domains {
11848: my ($hostname) = @_;
11849: my @domains;
11850: my %hostname = &all_hostnames();
11851: while( my($id, $name) = each(%hostname)) {
11852: # &logthis("-$id-$name-$hostname-");
11853: if ($hostname eq $name) {
11854: push(@domains,&host_domain($id));
11855: }
11856: }
11857: return @domains;
11858: }
11859:
11860: sub current_machine_ids {
11861: return &machine_ids(&hostname($perlvar{'lonHostID'}));
11862: }
11863:
11864: sub machine_ids {
11865: my ($hostname) = @_;
11866: $hostname ||= &hostname($perlvar{'lonHostID'});
11867: my @ids;
11868: my %name_to_host = &all_names();
11869: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
11870: return @{ $name_to_host{$hostname} };
11871: }
11872: return;
11873: }
11874:
11875: sub additional_machine_domains {
11876: my @domains;
11877: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
11878: while( my $line = <$fh>) {
11879: $line =~ s/\s//g;
11880: push(@domains,$line);
11881: }
11882: return @domains;
11883: }
11884:
11885: sub default_login_domain {
11886: my $domain = $perlvar{'lonDefDomain'};
11887: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
11888: foreach my $posdom (¤t_machine_domains(),
11889: &additional_machine_domains()) {
11890: if (lc($posdom) eq lc($testdomain)) {
11891: $domain=$posdom;
11892: last;
11893: }
11894: }
11895: return $domain;
11896: }
11897:
11898: # ------------------------------------------------------------- Declutters URLs
11899:
11900: sub declutter {
11901: my $thisfn=shift;
11902: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
11903: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
11904: $thisfn=~s{^/home/httpd/html}{};
11905: }
11906: $thisfn=~s/^\///;
11907: $thisfn=~s|^adm/wrapper/||;
11908: $thisfn=~s|^adm/coursedocs/showdoc/||;
11909: $thisfn=~s/^res\///;
11910: $thisfn=~s/^priv\///;
11911: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
11912: $thisfn=~s/\?.+$//;
11913: }
11914: return $thisfn;
11915: }
11916:
11917: # ------------------------------------------------------------- Clutter up URLs
11918:
11919: sub clutter {
11920: my $thisfn='/'.&declutter(shift);
11921: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
11922: || $thisfn =~ m{^/adm/(includes|pages)} ) {
11923: $thisfn='/res'.$thisfn;
11924: }
11925: if ($thisfn !~m|^/adm|) {
11926: if ($thisfn =~ m|^/ext/|) {
11927: $thisfn='/adm/wrapper'.$thisfn;
11928: } else {
11929: my ($ext) = ($thisfn =~ /\.(\w+)$/);
11930: my $embstyle=&Apache::loncommon::fileembstyle($ext);
11931: if ($embstyle eq 'ssi'
11932: || ($embstyle eq 'hdn')
11933: || ($embstyle eq 'rat')
11934: || ($embstyle eq 'prv')
11935: || ($embstyle eq 'ign')) {
11936: #do nothing with these
11937: } elsif (($embstyle eq 'img')
11938: || ($embstyle eq 'emb')
11939: || ($embstyle eq 'wrp')) {
11940: $thisfn='/adm/wrapper'.$thisfn;
11941: } elsif ($embstyle eq 'unk'
11942: && $thisfn!~/\.(sequence|page)$/) {
11943: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
11944: } else {
11945: # &logthis("Got a blank emb style");
11946: }
11947: }
11948: }
11949: return $thisfn;
11950: }
11951:
11952: sub clutter_with_no_wrapper {
11953: my $uri = &clutter(shift);
11954: if ($uri =~ m-^/adm/-) {
11955: $uri =~ s-^/adm/wrapper/-/-;
11956: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
11957: }
11958: return $uri;
11959: }
11960:
11961: sub freeze_escape {
11962: my ($value)=@_;
11963: if (ref($value)) {
11964: $value=&nfreeze($value);
11965: return '__FROZEN__'.&escape($value);
11966: }
11967: return &escape($value);
11968: }
11969:
11970:
11971: sub thaw_unescape {
11972: my ($value)=@_;
11973: if ($value =~ /^__FROZEN__/) {
11974: substr($value,0,10,undef);
11975: $value=&unescape($value);
11976: return &thaw($value);
11977: }
11978: return &unescape($value);
11979: }
11980:
11981: sub correct_line_ends {
11982: my ($result)=@_;
11983: $$result =~s/\r\n/\n/mg;
11984: $$result =~s/\r/\n/mg;
11985: }
11986: # ================================================================ Main Program
11987:
11988: sub goodbye {
11989: &logthis("Starting Shut down");
11990: #not converted to using infrastruture and probably shouldn't be
11991: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
11992: #converted
11993: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
11994: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
11995: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
11996: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
11997: #1.1 only
11998: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
11999: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
12000: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
12001: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
12002: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
12003: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
12004: &logthis(sprintf("%-20s is %s",'hits',$hits));
12005: &flushcourselogs();
12006: &logthis("Shutting down");
12007: }
12008:
12009: sub get_dns {
12010: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
12011: if (!$ignore_cache) {
12012: my ($content,$cached)=
12013: &Apache::lonnet::is_cached_new('dns',$url);
12014: if ($cached) {
12015: &$func($content,$hashref);
12016: return;
12017: }
12018: }
12019:
12020: my %alldns;
12021: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12022: foreach my $dns (<$config>) {
12023: next if ($dns !~ /^\^(\S*)/x);
12024: my $line = $1;
12025: my ($host,$protocol) = split(/:/,$line);
12026: if ($protocol ne 'https') {
12027: $protocol = 'http';
12028: }
12029: $alldns{$host} = $protocol;
12030: }
12031: while (%alldns) {
12032: my ($dns) = sort { $b cmp $a } keys(%alldns);
12033: my $ua=new LWP::UserAgent;
12034: $ua->timeout(30);
12035: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
12036: my $response=$ua->request($request);
12037: delete($alldns{$dns});
12038: next if ($response->is_error());
12039: my @content = split("\n",$response->content);
12040: unless ($nocache) {
12041: &do_cache_new('dns',$url,\@content,30*24*60*60);
12042: }
12043: &$func(\@content,$hashref);
12044: return;
12045: }
12046: close($config);
12047: my $which = (split('/',$url))[3];
12048: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
12049: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
12050: my @content = <$config>;
12051: &$func(\@content,$hashref);
12052: return;
12053: }
12054:
12055: # ------------------------------------------------------Get DNS checksums file
12056: sub parse_dns_checksums_tab {
12057: my ($lines,$hashref) = @_;
12058: my $lonhost = $perlvar{'lonHostID'};
12059: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
12060: my $loncaparev = &get_server_loncaparev($machine_dom);
12061: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
12062: my $webconfdir = '/etc/httpd/conf';
12063: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
12064: $webconfdir = '/etc/apache2';
12065: } elsif ($distro =~ /^sles(\d+)$/) {
12066: if ($1 >= 10) {
12067: $webconfdir = '/etc/apache2';
12068: }
12069: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
12070: if ($1 >= 10.0) {
12071: $webconfdir = '/etc/apache2';
12072: }
12073: }
12074: my ($release,$timestamp) = split(/\-/,$loncaparev);
12075: my (%chksum,%revnum);
12076: if (ref($lines) eq 'ARRAY') {
12077: chomp(@{$lines});
12078: my $version = shift(@{$lines});
12079: if ($version eq $release) {
12080: foreach my $line (@{$lines}) {
12081: my ($file,$version,$shasum) = split(/,/,$line);
12082: if ($file =~ m{^/etc/httpd/conf}) {
12083: if ($webconfdir eq '/etc/apache2') {
12084: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
12085: }
12086: }
12087: $chksum{$file} = $shasum;
12088: $revnum{$file} = $version;
12089: }
12090: if (ref($hashref) eq 'HASH') {
12091: %{$hashref} = (
12092: sums => \%chksum,
12093: versions => \%revnum,
12094: );
12095: }
12096: }
12097: }
12098: return;
12099: }
12100:
12101: sub fetch_dns_checksums {
12102: my %checksums;
12103: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
12104: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
12105: my ($release,$timestamp) = split(/\-/,$loncaparev);
12106: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
12107: \%checksums);
12108: return \%checksums;
12109: }
12110:
12111: # ------------------------------------------------------------ Read domain file
12112: {
12113: my $loaded;
12114: my %domain;
12115:
12116: sub parse_domain_tab {
12117: my ($lines) = @_;
12118: foreach my $line (@$lines) {
12119: next if ($line =~ /^(\#|\s*$ )/x);
12120:
12121: chomp($line);
12122: my ($name,@elements) = split(/:/,$line,9);
12123: my %this_domain;
12124: foreach my $field ('description', 'auth_def', 'auth_arg_def',
12125: 'lang_def', 'city', 'longi', 'lati',
12126: 'primary') {
12127: $this_domain{$field} = shift(@elements);
12128: }
12129: $domain{$name} = \%this_domain;
12130: }
12131: }
12132:
12133: sub reset_domain_info {
12134: undef($loaded);
12135: undef(%domain);
12136: }
12137:
12138: sub load_domain_tab {
12139: my ($ignore_cache) = @_;
12140: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
12141: my $fh;
12142: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
12143: my @lines = <$fh>;
12144: &parse_domain_tab(\@lines);
12145: }
12146: close($fh);
12147: $loaded = 1;
12148: }
12149:
12150: sub domain {
12151: &load_domain_tab() if (!$loaded);
12152:
12153: my ($name,$what) = @_;
12154: return if ( !exists($domain{$name}) );
12155:
12156: if (!$what) {
12157: return $domain{$name}{'description'};
12158: }
12159: return $domain{$name}{$what};
12160: }
12161:
12162: sub domain_info {
12163: &load_domain_tab() if (!$loaded);
12164: return %domain;
12165: }
12166:
12167: }
12168:
12169:
12170: # ------------------------------------------------------------- Read hosts file
12171: {
12172: my %hostname;
12173: my %hostdom;
12174: my %libserv;
12175: my $loaded;
12176: my %name_to_host;
12177: my %internetdom;
12178: my %LC_dns_serv;
12179:
12180: sub parse_hosts_tab {
12181: my ($file) = @_;
12182: foreach my $configline (@$file) {
12183: next if ($configline =~ /^(\#|\s*$ )/x);
12184: chomp($configline);
12185: if ($configline =~ /^\^/) {
12186: if ($configline =~ /^\^([\w.\-]+)/) {
12187: $LC_dns_serv{$1} = 1;
12188: }
12189: next;
12190: }
12191: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
12192: $name=~s/\s//g;
12193: if ($id && $domain && $role && $name) {
12194: $hostname{$id}=$name;
12195: push(@{$name_to_host{$name}}, $id);
12196: $hostdom{$id}=$domain;
12197: if ($role eq 'library') { $libserv{$id}=$name; }
12198: if (defined($protocol)) {
12199: if ($protocol eq 'https') {
12200: $protocol{$id} = $protocol;
12201: } else {
12202: $protocol{$id} = 'http';
12203: }
12204: } else {
12205: $protocol{$id} = 'http';
12206: }
12207: if (defined($intdom)) {
12208: $internetdom{$id} = $intdom;
12209: }
12210: }
12211: }
12212: }
12213:
12214: sub reset_hosts_info {
12215: &purge_remembered();
12216: &reset_domain_info();
12217: &reset_hosts_ip_info();
12218: undef(%name_to_host);
12219: undef(%hostname);
12220: undef(%hostdom);
12221: undef(%libserv);
12222: undef($loaded);
12223: }
12224:
12225: sub load_hosts_tab {
12226: my ($ignore_cache) = @_;
12227: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
12228: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
12229: my @config = <$config>;
12230: &parse_hosts_tab(\@config);
12231: close($config);
12232: $loaded=1;
12233: }
12234:
12235: sub hostname {
12236: &load_hosts_tab() if (!$loaded);
12237:
12238: my ($lonid) = @_;
12239: return $hostname{$lonid};
12240: }
12241:
12242: sub all_hostnames {
12243: &load_hosts_tab() if (!$loaded);
12244:
12245: return %hostname;
12246: }
12247:
12248: sub all_names {
12249: &load_hosts_tab() if (!$loaded);
12250:
12251: return %name_to_host;
12252: }
12253:
12254: sub all_host_domain {
12255: &load_hosts_tab() if (!$loaded);
12256: return %hostdom;
12257: }
12258:
12259: sub is_library {
12260: &load_hosts_tab() if (!$loaded);
12261:
12262: return exists($libserv{$_[0]});
12263: }
12264:
12265: sub all_library {
12266: &load_hosts_tab() if (!$loaded);
12267:
12268: return %libserv;
12269: }
12270:
12271: sub unique_library {
12272: #2x reverse removes all hostnames that appear more than once
12273: my %unique = reverse &all_library();
12274: return reverse %unique;
12275: }
12276:
12277: sub get_servers {
12278: &load_hosts_tab() if (!$loaded);
12279:
12280: my ($domain,$type) = @_;
12281: my %possible_hosts = ($type eq 'library') ? %libserv
12282: : %hostname;
12283: my %result;
12284: if (ref($domain) eq 'ARRAY') {
12285: while ( my ($host,$hostname) = each(%possible_hosts)) {
12286: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
12287: $result{$host} = $hostname;
12288: }
12289: }
12290: } else {
12291: while ( my ($host,$hostname) = each(%possible_hosts)) {
12292: if ($hostdom{$host} eq $domain) {
12293: $result{$host} = $hostname;
12294: }
12295: }
12296: }
12297: return %result;
12298: }
12299:
12300: sub get_unique_servers {
12301: my %unique = reverse &get_servers(@_);
12302: return reverse %unique;
12303: }
12304:
12305: sub host_domain {
12306: &load_hosts_tab() if (!$loaded);
12307:
12308: my ($lonid) = @_;
12309: return $hostdom{$lonid};
12310: }
12311:
12312: sub all_domains {
12313: &load_hosts_tab() if (!$loaded);
12314:
12315: my %seen;
12316: my @uniq = grep(!$seen{$_}++, values(%hostdom));
12317: return @uniq;
12318: }
12319:
12320: sub internet_dom {
12321: &load_hosts_tab() if (!$loaded);
12322:
12323: my ($lonid) = @_;
12324: return $internetdom{$lonid};
12325: }
12326:
12327: sub is_LC_dns {
12328: &load_hosts_tab() if (!$loaded);
12329:
12330: my ($hostname) = @_;
12331: return exists($LC_dns_serv{$hostname});
12332: }
12333:
12334: }
12335:
12336: {
12337: my %iphost;
12338: my %name_to_ip;
12339: my %lonid_to_ip;
12340:
12341: sub get_hosts_from_ip {
12342: my ($ip) = @_;
12343: my %iphosts = &get_iphost();
12344: if (ref($iphosts{$ip})) {
12345: return @{$iphosts{$ip}};
12346: }
12347: return;
12348: }
12349:
12350: sub reset_hosts_ip_info {
12351: undef(%iphost);
12352: undef(%name_to_ip);
12353: undef(%lonid_to_ip);
12354: }
12355:
12356: sub get_host_ip {
12357: my ($lonid) = @_;
12358: if (exists($lonid_to_ip{$lonid})) {
12359: return $lonid_to_ip{$lonid};
12360: }
12361: my $name=&hostname($lonid);
12362: my $ip = gethostbyname($name);
12363: return if (!$ip || length($ip) ne 4);
12364: $ip=inet_ntoa($ip);
12365: $name_to_ip{$name} = $ip;
12366: $lonid_to_ip{$lonid} = $ip;
12367: return $ip;
12368: }
12369:
12370: sub get_iphost {
12371: my ($ignore_cache) = @_;
12372:
12373: if (!$ignore_cache) {
12374: if (%iphost) {
12375: return %iphost;
12376: }
12377: my ($ip_info,$cached)=
12378: &Apache::lonnet::is_cached_new('iphost','iphost');
12379: if ($cached) {
12380: %iphost = %{$ip_info->[0]};
12381: %name_to_ip = %{$ip_info->[1]};
12382: %lonid_to_ip = %{$ip_info->[2]};
12383: return %iphost;
12384: }
12385: }
12386:
12387: # get yesterday's info for fallback
12388: my %old_name_to_ip;
12389: my ($ip_info,$cached)=
12390: &Apache::lonnet::is_cached_new('iphost','iphost');
12391: if ($cached) {
12392: %old_name_to_ip = %{$ip_info->[1]};
12393: }
12394:
12395: my %name_to_host = &all_names();
12396: foreach my $name (keys(%name_to_host)) {
12397: my $ip;
12398: if (!exists($name_to_ip{$name})) {
12399: $ip = gethostbyname($name);
12400: if (!$ip || length($ip) ne 4) {
12401: if (defined($old_name_to_ip{$name})) {
12402: $ip = $old_name_to_ip{$name};
12403: &logthis("Can't find $name defaulting to old $ip");
12404: } else {
12405: &logthis("Name $name no IP found");
12406: next;
12407: }
12408: } else {
12409: $ip=inet_ntoa($ip);
12410: }
12411: $name_to_ip{$name} = $ip;
12412: } else {
12413: $ip = $name_to_ip{$name};
12414: }
12415: foreach my $id (@{ $name_to_host{$name} }) {
12416: $lonid_to_ip{$id} = $ip;
12417: }
12418: push(@{$iphost{$ip}},@{$name_to_host{$name}});
12419: }
12420: &do_cache_new('iphost','iphost',
12421: [\%iphost,\%name_to_ip,\%lonid_to_ip],
12422: 48*60*60);
12423:
12424: return %iphost;
12425: }
12426:
12427: #
12428: # Given a DNS returns the loncapa host name for that DNS
12429: #
12430: sub host_from_dns {
12431: my ($dns) = @_;
12432: my @hosts;
12433: my $ip;
12434:
12435: if (exists($name_to_ip{$dns})) {
12436: $ip = $name_to_ip{$dns};
12437: }
12438: if (!$ip) {
12439: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
12440: if (length($ip) == 4) {
12441: $ip = &IO::Socket::inet_ntoa($ip);
12442: }
12443: }
12444: if ($ip) {
12445: @hosts = get_hosts_from_ip($ip);
12446: return $hosts[0];
12447: }
12448: return undef;
12449: }
12450:
12451: sub get_internet_names {
12452: my ($lonid) = @_;
12453: return if ($lonid eq '');
12454: my ($idnref,$cached)=
12455: &Apache::lonnet::is_cached_new('internetnames',$lonid);
12456: if ($cached) {
12457: return $idnref;
12458: }
12459: my $ip = &get_host_ip($lonid);
12460: my @hosts = &get_hosts_from_ip($ip);
12461: my %iphost = &get_iphost();
12462: my (@idns,%seen);
12463: foreach my $id (@hosts) {
12464: my $dom = &host_domain($id);
12465: my $prim_id = &domain($dom,'primary');
12466: my $prim_ip = &get_host_ip($prim_id);
12467: next if ($seen{$prim_ip});
12468: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
12469: foreach my $id (@{$iphost{$prim_ip}}) {
12470: my $intdom = &internet_dom($id);
12471: unless (grep(/^\Q$intdom\E$/,@idns)) {
12472: push(@idns,$intdom);
12473: }
12474: }
12475: }
12476: $seen{$prim_ip} = 1;
12477: }
12478: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
12479: }
12480:
12481: }
12482:
12483: sub all_loncaparevs {
12484: 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 2.11);
12485: }
12486:
12487: # ---------------------------------------------------------- Read loncaparev table
12488: {
12489: sub load_loncaparevs {
12490: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
12491: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
12492: while (my $configline=<$config>) {
12493: chomp($configline);
12494: my ($hostid,$loncaparev)=split(/:/,$configline);
12495: $loncaparevs{$hostid}=$loncaparev;
12496: }
12497: close($config);
12498: }
12499: }
12500: }
12501: }
12502:
12503: # ---------------------------------------------------------- Read serverhostID table
12504: {
12505: sub load_serverhomeIDs {
12506: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
12507: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
12508: while (my $configline=<$config>) {
12509: chomp($configline);
12510: my ($name,$id)=split(/:/,$configline);
12511: $serverhomeIDs{$name}=$id;
12512: }
12513: close($config);
12514: }
12515: }
12516: }
12517: }
12518:
12519:
12520: BEGIN {
12521:
12522: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
12523: unless ($readit) {
12524: {
12525: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
12526: %perlvar = (%perlvar,%{$configvars});
12527: }
12528:
12529:
12530: # ------------------------------------------------------ Read spare server file
12531: {
12532: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
12533:
12534: while (my $configline=<$config>) {
12535: chomp($configline);
12536: if ($configline) {
12537: my ($host,$type) = split(':',$configline,2);
12538: if (!defined($type) || $type eq '') { $type = 'default' };
12539: push(@{ $spareid{$type} }, $host);
12540: }
12541: }
12542: close($config);
12543: }
12544: # ------------------------------------------------------------ Read permissions
12545: {
12546: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
12547:
12548: while (my $configline=<$config>) {
12549: chomp($configline);
12550: if ($configline) {
12551: my ($role,$perm)=split(/ /,$configline);
12552: if ($perm ne '') { $pr{$role}=$perm; }
12553: }
12554: }
12555: close($config);
12556: }
12557:
12558: # -------------------------------------------- Read plain texts for permissions
12559: {
12560: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
12561:
12562: while (my $configline=<$config>) {
12563: chomp($configline);
12564: if ($configline) {
12565: my ($short,@plain)=split(/:/,$configline);
12566: %{$prp{$short}} = ();
12567: if (@plain > 0) {
12568: $prp{$short}{'std'} = $plain[0];
12569: for (my $i=1; $i<@plain; $i++) {
12570: $prp{$short}{'alt'.$i} = $plain[$i];
12571: }
12572: }
12573: }
12574: }
12575: close($config);
12576: }
12577:
12578: # ---------------------------------------------------------- Read package table
12579: {
12580: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
12581:
12582: while (my $configline=<$config>) {
12583: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
12584: chomp($configline);
12585: my ($short,$plain)=split(/:/,$configline);
12586: my ($pack,$name)=split(/\&/,$short);
12587: if ($plain ne '') {
12588: $packagetab{$pack.'&'.$name.'&name'}=$name;
12589: $packagetab{$short}=$plain;
12590: }
12591: }
12592: close($config);
12593: }
12594:
12595: # ---------------------------------------------------------- Read loncaparev table
12596:
12597: &load_loncaparevs();
12598:
12599: # ---------------------------------------------------------- Read serverhostID table
12600:
12601: &load_serverhomeIDs();
12602:
12603: # ---------------------------------------------------------- Read releaseslist XML
12604: {
12605: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
12606: if (-e $file) {
12607: my $parser = HTML::LCParser->new($file);
12608: while (my $token = $parser->get_token()) {
12609: if ($token->[0] eq 'S') {
12610: my $item = $token->[1];
12611: my $name = $token->[2]{'name'};
12612: my $value = $token->[2]{'value'};
12613: if ($item ne '' && $name ne '' && $value ne '') {
12614: my $release = $parser->get_text();
12615: $release =~ s/(^\s*|\s*$ )//gx;
12616: $needsrelease{$item.':'.$name.':'.$value} = $release;
12617: }
12618: }
12619: }
12620: }
12621: }
12622:
12623: # ---------------------------------------------------------- Read managers table
12624: {
12625: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
12626: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
12627: while (my $configline=<$config>) {
12628: chomp($configline);
12629: next if ($configline =~ /^\#/);
12630: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
12631: $managerstab{$configline} = 1;
12632: }
12633: }
12634: close($config);
12635: }
12636: }
12637: }
12638:
12639: # ------------- set up temporary directory
12640: {
12641: $tmpdir = LONCAPA::tempdir();
12642:
12643: }
12644:
12645: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
12646: 'compress_threshold'=> 20_000,
12647: });
12648:
12649: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
12650: $dumpcount=0;
12651: $locknum=0;
12652:
12653: &logtouch();
12654: &logthis('<font color="yellow">INFO: Read configuration</font>');
12655: $readit=1;
12656: {
12657: use integer;
12658: my $test=(2**32)+1;
12659: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
12660: &logthis(" Detected 64bit platform ($_64bit)");
12661: }
12662: }
12663: }
12664:
12665: 1;
12666: __END__
12667:
12668: =pod
12669:
12670: =head1 NAME
12671:
12672: Apache::lonnet - Subroutines to ask questions about things in the network.
12673:
12674: =head1 SYNOPSIS
12675:
12676: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
12677:
12678: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
12679:
12680: Common parameters:
12681:
12682: =over 4
12683:
12684: =item *
12685:
12686: $uname : an internal username (if $cname expecting a course Id specifically)
12687:
12688: =item *
12689:
12690: $udom : a domain (if $cdom expecting a course's domain specifically)
12691:
12692: =item *
12693:
12694: $symb : a resource instance identifier
12695:
12696: =item *
12697:
12698: $namespace : the name of a .db file that contains the data needed or
12699: being set.
12700:
12701: =back
12702:
12703: =head1 OVERVIEW
12704:
12705: lonnet provides subroutines which interact with the
12706: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
12707: about classes, users, and resources.
12708:
12709: For many of these objects you can also use this to store data about
12710: them or modify them in various ways.
12711:
12712: =head2 Symbs
12713:
12714: To identify a specific instance of a resource, LON-CAPA uses symbols
12715: or "symbs"X<symb>. These identifiers are built from the URL of the
12716: map, the resource number of the resource in the map, and the URL of
12717: the resource itself. The latter is somewhat redundant, but might help
12718: if maps change.
12719:
12720: An example is
12721:
12722: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
12723:
12724: The respective map entry is
12725:
12726: <resource id="19" src="/res/msu/korte/tests/part12.problem"
12727: title="Problem 2">
12728: </resource>
12729:
12730: Symbs are used by the random number generator, as well as to store and
12731: restore data specific to a certain instance of for example a problem.
12732:
12733: =head2 Storing And Retrieving Data
12734:
12735: X<store()>X<cstore()>X<restore()>Three of the most important functions
12736: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
12737: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
12738: is is the non-critical message twin of cstore. These functions are for
12739: handlers to store a perl hash to a user's permanent data space in an
12740: easy manner, and to retrieve it again on another call. It is expected
12741: that a handler would use this once at the beginning to retrieve data,
12742: and then again once at the end to send only the new data back.
12743:
12744: The data is stored in the user's data directory on the user's
12745: homeserver under the ID of the course.
12746:
12747: The hash that is returned by restore will have all of the previous
12748: value for all of the elements of the hash.
12749:
12750: Example:
12751:
12752: #creating a hash
12753: my %hash;
12754: $hash{'foo'}='bar';
12755:
12756: #storing it
12757: &Apache::lonnet::cstore(\%hash);
12758:
12759: #changing a value
12760: $hash{'foo'}='notbar';
12761:
12762: #adding a new value
12763: $hash{'bar'}='foo';
12764: &Apache::lonnet::cstore(\%hash);
12765:
12766: #retrieving the hash
12767: my %history=&Apache::lonnet::restore();
12768:
12769: #print the hash
12770: foreach my $key (sort(keys(%history))) {
12771: print("\%history{$key} = $history{$key}");
12772: }
12773:
12774: Will print out:
12775:
12776: %history{1:foo} = bar
12777: %history{1:keys} = foo:timestamp
12778: %history{1:timestamp} = 990455579
12779: %history{2:bar} = foo
12780: %history{2:foo} = notbar
12781: %history{2:keys} = foo:bar:timestamp
12782: %history{2:timestamp} = 990455580
12783: %history{bar} = foo
12784: %history{foo} = notbar
12785: %history{timestamp} = 990455580
12786: %history{version} = 2
12787:
12788: Note that the special hash entries C<keys>, C<version> and
12789: C<timestamp> were added to the hash. C<version> will be equal to the
12790: total number of versions of the data that have been stored. The
12791: C<timestamp> attribute will be the UNIX time the hash was
12792: stored. C<keys> is available in every historical section to list which
12793: keys were added or changed at a specific historical revision of a
12794: hash.
12795:
12796: B<Warning>: do not store the hash that restore returns directly. This
12797: will cause a mess since it will restore the historical keys as if the
12798: were new keys. I.E. 1:foo will become 1:1:foo etc.
12799:
12800: Calling convention:
12801:
12802: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
12803: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
12804:
12805: For more detailed information, see lonnet specific documentation.
12806:
12807: =head1 RETURN MESSAGES
12808:
12809: =over 4
12810:
12811: =item * B<con_lost>: unable to contact remote host
12812:
12813: =item * B<con_delayed>: unable to contact remote host, message will be delivered
12814: when the connection is brought back up
12815:
12816: =item * B<con_failed>: unable to contact remote host and unable to save message
12817: for later delivery
12818:
12819: =item * B<error:>: an error a occurred, a description of the error follows the :
12820:
12821: =item * B<no_such_host>: unable to fund a host associated with the user/domain
12822: that was requested
12823:
12824: =back
12825:
12826: =head1 PUBLIC SUBROUTINES
12827:
12828: =head2 Session Environment Functions
12829:
12830: =over 4
12831:
12832: =item *
12833: X<appenv()>
12834: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
12835: the user envirnoment file, and will be restored for each access this
12836: user makes during this session, also modifies the %env for the current
12837: process. Optional rolesarrayref - if defined contains a reference to an array
12838: of roles which are exempt from the restriction on modifying user.role entries
12839: in the user's environment.db and in %env.
12840:
12841: =item *
12842: X<delenv()>
12843: B<delenv($delthis,$regexp)>: removes all items from the session
12844: environment file that begin with $delthis. If the
12845: optional second arg - $regexp - is true, $delthis is treated as a
12846: regular expression, otherwise \Q$delthis\E is used.
12847: The values are also deleted from the current processes %env.
12848:
12849: =item * get_env_multiple($name)
12850:
12851: gets $name from the %env hash, it seemlessly handles the cases where multiple
12852: values may be defined and end up as an array ref.
12853:
12854: returns an array of values
12855:
12856: =back
12857:
12858: =head2 User Information
12859:
12860: =over 4
12861:
12862: =item *
12863: X<queryauthenticate()>
12864: B<queryauthenticate($uname,$udom)>: try to determine user's current
12865: authentication scheme
12866:
12867: =item *
12868: X<authenticate()>
12869: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
12870: authenticate user from domain's lib servers (first use the current
12871: one). C<$upass> should be the users password.
12872: $checkdefauth is optional (value is 1 if a check should be made to
12873: authenticate user using default authentication method, and allow
12874: account creation if username does not have account in the domain).
12875: $clientcancheckhost is optional (value is 1 if checking whether the
12876: server can host will occur on the client side in lonauth.pm).
12877:
12878: =item *
12879: X<homeserver()>
12880: B<homeserver($uname,$udom)>: find the server which has
12881: the user's directory and files (there must be only one), this caches
12882: the answer, and also caches if there is a borken connection.
12883:
12884: =item *
12885: X<idget()>
12886: B<idget($udom,@ids)>: find the usernames behind a list of IDs
12887: (IDs are a unique resource in a domain, there must be only 1 ID per
12888: username, and only 1 username per ID in a specific domain) (returns
12889: hash: id=>name,id=>name)
12890:
12891: =item *
12892: X<idrget()>
12893: B<idrget($udom,@unames)>: find the IDs behind a list of
12894: usernames (returns hash: name=>id,name=>id)
12895:
12896: =item *
12897: X<idput()>
12898: B<idput($udom,%ids)>: store away a list of names and associated IDs
12899:
12900: =item *
12901: X<rolesinit()>
12902: B<rolesinit($udom,$username)>: get user privileges.
12903: returns user role, first access and timer interval hashes
12904:
12905: =item *
12906: X<privileged()>
12907: B<privileged($username,$domain)>: returns a true if user has a
12908: privileged and active role (i.e. su or dc), false otherwise.
12909:
12910: =item *
12911: X<getsection()>
12912: B<getsection($udom,$uname,$cname)>: finds the section of student in the
12913: course $cname, return section name/number or '' for "not in course"
12914: and '-1' for "no section"
12915:
12916: =item *
12917: X<userenvironment()>
12918: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
12919: passed in @what from the requested user's environment, returns a hash
12920:
12921: =item *
12922: X<userlog_query()>
12923: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
12924: activity.log file. %filters defines filters applied when parsing the
12925: log file. These can be start or end timestamps, or the type of action
12926: - log to look for Login or Logout events, check for Checkin or
12927: Checkout, role for role selection. The response is in the form
12928: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
12929: escaped strings of the action recorded in the activity.log file.
12930:
12931: =back
12932:
12933: =head2 User Roles
12934:
12935: =over 4
12936:
12937: =item *
12938:
12939: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
12940: F: full access
12941: U,I,K: authentication modes (cxx only)
12942: '': forbidden
12943: 1: user needs to choose course
12944: 2: browse allowed
12945: A: passphrase authentication needed
12946:
12947: =item *
12948:
12949: constructaccess($url,$setpriv) : check for access to construction space URL
12950:
12951: See if the owner domain and name in the URL match those in the
12952: expected environment. If so, return three element list
12953: ($ownername,$ownerdomain,$ownerhome).
12954:
12955: Otherwise return the null string.
12956:
12957: If second argument 'setpriv' is true, it assigns the privileges,
12958: and returns the same three element list, unless the owner has
12959: blocked "ad hoc" Domain Coordinator access to the Author Space,
12960: in which case the null string is returned.
12961:
12962: =item *
12963:
12964: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
12965: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
12966: and course level
12967:
12968: =item *
12969:
12970: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
12971: (rolesplain.tab); plain text explanation of a user role term.
12972: $type is Course (default) or Community.
12973: If $forcedefault evaluates to true, text returned will be default
12974: text for $type. Otherwise, if this is a course, the text returned
12975: will be a custom name for the role (if defined in the course's
12976: environment). If no custom name is defined the default is returned.
12977:
12978: =item *
12979:
12980: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
12981: All arguments are optional. Returns a hash of a roles, either for
12982: co-author/assistant author roles for a user's Construction Space
12983: (default), or if $context is 'userroles', roles for the user himself,
12984: In the hash, keys are set to colon-separated $uname,$udom,$role, and
12985: (optionally) if $withsec is true, a fourth colon-separated item - $section.
12986: For each key, value is set to colon-separated start and end times for
12987: the role. If no username and domain are specified, will default to
12988: current user/domain. Types, roles, and roledoms are references to arrays
12989: of role statuses (active, future or previous), roles
12990: (e.g., cc,in, st etc.) and domains of the roles which can be used
12991: to restrict the list of roles reported. If no array ref is
12992: provided for types, will default to return only active roles.
12993:
12994: =item *
12995:
12996: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
12997: user: $uname:$udom has a role in the course: $cdom_$cnum.
12998:
12999: Additional optional arguments are: $type (if role checking is to be restricted
13000: to certain user status types -- previous (expired roles), active (currently
13001: available roles) or future (roles available in the future), and
13002: $hideprivileged -- if true will not report course roles for users who
13003: have active Domain Coordinator role in course's domain or in additional
13004: domains (specified in 'Domains to check for privileged users' in course
13005: environment -- set via: Course Settings -> Classlists and staff listing).
13006:
13007: =item *
13008:
13009: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
13010: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
13011: $possdomains and $possroles are optional array refs -- to domains to check and
13012: roles to check. If $possdomains is not specified, a dump will be done of the
13013: users' roles.db to check for a dc or su role in any domain. This can be
13014: time consuming if &privileged is called repeatedly (e.g., when displaying a
13015: classlist), so in such cases, supplying a $possdomains array is preferred, as
13016: this then allows &privileged_by_domain() to be used, which caches the identity
13017: of privileged users, eliminating the need for repeated calls to &dump().
13018:
13019: =item *
13020:
13021: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
13022: where the outer hash keys are domains specified in the $possdomains array ref,
13023: next inner hash keys are privileged roles specified in the $roles array ref,
13024: and the innermost hash contains key = value pairs for username:domain = end:start
13025: for active or future "privileged" users with that role in that domain. To avoid
13026: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
13027: innerhash are cached using priv_$role and $dom as the identifiers.
13028:
13029: =back
13030:
13031: =head2 User Modification
13032:
13033: =over 4
13034:
13035: =item *
13036:
13037: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
13038: user for the level given by URL. Optional start and end dates (leave empty
13039: string or zero for "no date")
13040:
13041: =item *
13042:
13043: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
13044: change a users, password, possible return values are: ok,
13045: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
13046: refused
13047:
13048: =item *
13049:
13050: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
13051:
13052: =item *
13053:
13054: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
13055: $forceid,$desiredhome,$email,$inststatus,$candelete) :
13056:
13057: will update user information (firstname,middlename,lastname,generation,
13058: permanentemail), and if forceid is true, student/employee ID also.
13059: A user's institutional affiliation(s) can also be updated.
13060: User information fields will not be overwritten with empty entries
13061: unless the field is included in the $candelete array reference.
13062: This array is included when a single user is modified via "Manage Users",
13063: or when Autoupdate.pl is run by cron in a domain.
13064:
13065: =item *
13066:
13067: modifystudent
13068:
13069: modify a student's enrollment and identification information.
13070: The course id is resolved based on the current user's environment.
13071: This means the invoking user must be a course coordinator or otherwise
13072: associated with a course.
13073:
13074: This call is essentially a wrapper for lonnet::modifyuser and
13075: lonnet::modify_student_enrollment
13076:
13077: Inputs:
13078:
13079: =over 4
13080:
13081: =item B<$udom> Student's loncapa domain
13082:
13083: =item B<$uname> Student's loncapa login name
13084:
13085: =item B<$uid> Student/Employee ID
13086:
13087: =item B<$umode> Student's authentication mode
13088:
13089: =item B<$upass> Student's password
13090:
13091: =item B<$first> Student's first name
13092:
13093: =item B<$middle> Student's middle name
13094:
13095: =item B<$last> Student's last name
13096:
13097: =item B<$gene> Student's generation
13098:
13099: =item B<$usec> Student's section in course
13100:
13101: =item B<$end> Unix time of the roles expiration
13102:
13103: =item B<$start> Unix time of the roles start date
13104:
13105: =item B<$forceid> If defined, allow $uid to be changed
13106:
13107: =item B<$desiredhome> server to use as home server for student
13108:
13109: =item B<$email> Student's permanent e-mail address
13110:
13111: =item B<$type> Type of enrollment (auto or manual)
13112:
13113: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
13114:
13115: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
13116:
13117: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
13118:
13119: =item B<$context> role change context (shown in User Management Logs display in a course)
13120:
13121: =item B<$inststatus> institutional status of user - : separated string of escaped status types
13122:
13123: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
13124:
13125: =back
13126:
13127: =item *
13128:
13129: modify_student_enrollment
13130:
13131: Change a student's enrollment status in a class. The environment variable
13132: 'role.request.course' must be defined for this function to proceed.
13133:
13134: Inputs:
13135:
13136: =over 4
13137:
13138: =item $udom, student's domain
13139:
13140: =item $uname, student's name
13141:
13142: =item $uid, student's user id
13143:
13144: =item $first, student's first name
13145:
13146: =item $middle
13147:
13148: =item $last
13149:
13150: =item $gene
13151:
13152: =item $usec
13153:
13154: =item $end
13155:
13156: =item $start
13157:
13158: =item $type
13159:
13160: =item $locktype
13161:
13162: =item $cid
13163:
13164: =item $selfenroll
13165:
13166: =item $context
13167:
13168: =item $credits, number of credits student will earn from this class
13169:
13170: =back
13171:
13172:
13173: =item *
13174:
13175: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
13176: custom role; give a custom role to a user for the level given by URL. Specify
13177: name and domain of role author, and role name
13178:
13179: =item *
13180:
13181: revokerole($udom,$uname,$url,$role) : revoke a role for url
13182:
13183: =item *
13184:
13185: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
13186:
13187: =back
13188:
13189: =head2 Course Infomation
13190:
13191: =over 4
13192:
13193: =item *
13194:
13195: coursedescription($courseid,$options) : returns a hash of information about the
13196: specified course id, including all environment settings for the
13197: course, the description of the course will be in the hash under the
13198: key 'description'
13199:
13200: $options is an optional parameter that if supplied is a hash reference that controls
13201: what how this function works. It has the following key/values:
13202:
13203: =over 4
13204:
13205: =item freshen_cache
13206:
13207: If defined, and the environment cache for the course is valid, it is
13208: returned in the returned hash.
13209:
13210: =item one_time
13211:
13212: If defined, the last cache time is set to _now_
13213:
13214: =item user
13215:
13216: If defined, the supplied username is used instead of the current user.
13217:
13218:
13219: =back
13220:
13221: =item *
13222:
13223: resdata($name,$domain,$type,@which) : request for current parameter
13224: setting for a specific $type, where $type is either 'course' or 'user',
13225: @what should be a list of parameters to ask about. This routine caches
13226: answers for 10 minutes.
13227:
13228: =item *
13229:
13230: get_courseresdata($courseid, $domain) : dump the entire course resource
13231: data base, returning a hash that is keyed by the resource name and has
13232: values that are the resource value. I believe that the timestamps and
13233: versions are also returned.
13234:
13235: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
13236: supplemental content area. This routine caches the number of files for
13237: 10 minutes.
13238:
13239: =back
13240:
13241: =head2 Course Modification
13242:
13243: =over 4
13244:
13245: =item *
13246:
13247: writecoursepref($courseid,%prefs) : write preferences (environment
13248: database) for a course
13249:
13250: =item *
13251:
13252: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
13253:
13254: =item *
13255:
13256: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
13257:
13258: =item *
13259:
13260: is_course($courseid), is_course($cdom, $cnum)
13261:
13262: Accepts either a combined $courseid (in the form of domain_courseid) or the
13263: two component version $cdom, $cnum. It checks if the specified course exists.
13264:
13265: Returns:
13266: undef if the course doesn't exist, otherwise
13267: in scalar context the combined courseid.
13268: in list context the two components of the course identifier, domain and
13269: courseid.
13270:
13271: =back
13272:
13273: =head2 Resource Subroutines
13274:
13275: =over 4
13276:
13277: =item *
13278:
13279: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
13280:
13281: =item *
13282:
13283: repcopy($filename) : subscribes to the requested file, and attempts to
13284: replicate from the owning library server, Might return
13285: 'unavailable', 'not_found', 'forbidden', 'ok', or
13286: 'bad_request', also attempts to grab the metadata for the
13287: resource. Expects the local filesystem pathname
13288: (/home/httpd/html/res/....)
13289:
13290: =back
13291:
13292: =head2 Resource Information
13293:
13294: =over 4
13295:
13296: =item *
13297:
13298: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
13299: and returns the value of a variety of different possible values,
13300: $varname should be a request string, and the other parameters can be
13301: used to specify who and what one is asking about. Ordinarily, $cid
13302: does not need to be specified, as it is retrived from
13303: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
13304: within lonuserstate::loadmap() when initializing a course, before
13305: $env{'request.course.id'} has been set, so it needs to be provided
13306: in that one case.
13307:
13308: Possible values for $varname are environment.lastname (or other item
13309: from the envirnment hash), user.name (or someother aspect about the
13310: user), resource.0.maxtries (or some other part and parameter of a
13311: resource)
13312:
13313: =item *
13314:
13315: directcondval($number) : get current value of a condition; reads from a state
13316: string
13317:
13318: =item *
13319:
13320: condval($condidx) : value of condition index based on state
13321:
13322: =item *
13323:
13324: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
13325: resource's metadata, $what should be either a specific key, or either
13326: 'keys' (to get a list of possible keys) or 'packages' to get a list of
13327: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
13328:
13329: this function automatically caches all requests
13330:
13331: =item *
13332:
13333: metadata_query($query,$custom,$customshow) : make a metadata query against the
13334: network of library servers; returns file handle of where SQL and regex results
13335: will be stored for query
13336:
13337: =item *
13338:
13339: symbread($filename) : return symbolic list entry (filename argument optional);
13340: returns the data handle
13341:
13342: =item *
13343:
13344: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
13345: and is a possible symb for the URL in $thisfn, and if is an encrypted
13346: resource that the user accessed using /enc/ returns a 1 on success, 0
13347: on failure, user must be in a course, as it assumes the existence of
13348: the course initial hash, and uses $env('request.course.id'}. The third
13349: arg is an optional reference to a scalar. If this arg is passed in the
13350: call to symbverify, it will be set to 1 if the symb has been set to be
13351: encrypted; otherwise it will be null.
13352:
13353: =item *
13354:
13355: symbclean($symb) : removes versions numbers from a symb, returns the
13356: cleaned symb
13357:
13358: =item *
13359:
13360: is_on_map($uri) : checks if the $uri is somewhere on the current
13361: course map, user must be in a course for it to work.
13362:
13363: =item *
13364:
13365: numval($salt) : return random seed value (addend for rndseed)
13366:
13367: =item *
13368:
13369: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
13370: a random seed, all arguments are optional, if they aren't sent it uses the
13371: environment to derive them. Note: if symb isn't sent and it can't get one
13372: from &symbread it will use the current time as its return value
13373:
13374: =item *
13375:
13376: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
13377: unfakeable, receipt
13378:
13379: =item *
13380:
13381: receipt() : API to ireceipt working off of env values; given out to users
13382:
13383: =item *
13384:
13385: countacc($url) : count the number of accesses to a given URL
13386:
13387: =item *
13388:
13389: 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
13390:
13391: =item *
13392:
13393: 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)
13394:
13395: =item *
13396:
13397: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
13398:
13399: =item *
13400:
13401: devalidate($symb) : devalidate temporary spreadsheet calculations,
13402: forcing spreadsheet to reevaluate the resource scores next time.
13403:
13404: =item *
13405:
13406: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
13407: when viewing in course context.
13408:
13409: input: six args -- filename (decluttered), course number, course domain,
13410: url, symb (if registered) and group (if this is a
13411: group item -- e.g., bulletin board, group page etc.).
13412:
13413: output: array of five scalars --
13414: $cfile -- url for file editing if editable on current server
13415: $home -- homeserver of resource (i.e., for author if published,
13416: or course if uploaded.).
13417: $switchserver -- 1 if server switch will be needed.
13418: $forceedit -- 1 if icon/link should be to go to edit mode
13419: $forceview -- 1 if icon/link should be to go to view mode
13420:
13421: =item *
13422:
13423: is_course_upload($file,$cnum,$cdom)
13424:
13425: Used in course context to determine if current file was uploaded to
13426: the course (i.e., would be found in /userfiles/docs on the course's
13427: homeserver.
13428:
13429: input: 3 args -- filename (decluttered), course number and course domain.
13430: output: boolean -- 1 if file was uploaded.
13431:
13432: =back
13433:
13434: =head2 Storing/Retreiving Data
13435:
13436: =over 4
13437:
13438: =item *
13439:
13440: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
13441: permanently for this url; hashref needs to be given and should be a \%hashname;
13442: the remaining args aren't required and if they aren't passed or are '' they will
13443: be derived from the env (with the exception of $laststore, which is an
13444: optional arg used when a user's submission is stored in grading).
13445: $laststore is $version=$timestamp, where $version is the most recent version
13446: number retrieved for the corresponding $symb in the $namespace db file, and
13447: $timestamp is the timestamp for that transaction (UNIX time).
13448: $laststore is currently only passed when cstore() is called by
13449: structuretags::finalize_storage().
13450:
13451: =item *
13452:
13453: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
13454: but uses critical subroutine
13455:
13456: =item *
13457:
13458: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
13459: all args are optional
13460:
13461: =item *
13462:
13463: dumpstore($namespace,$udom,$uname,$regexp,$range) :
13464: dumps the complete (or key matching regexp) namespace into a hash
13465: ($udom, $uname, $regexp, $range are optional) for a namespace that is
13466: normally &store()ed into
13467:
13468: $range should be either an integer '100' (give me the first 100
13469: matching records)
13470: or be two integers sperated by a - with no spaces
13471: '30-50' (give me the 30th through the 50th matching
13472: records)
13473:
13474:
13475: =item *
13476:
13477: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
13478: replaces a &store() version of data with a replacement set of data
13479: for a particular resource in a namespace passed in the $storehash hash
13480: reference. If $tolog is true, the transaction is logged in the courselog
13481: with an action=PUTSTORE.
13482:
13483: =item *
13484:
13485: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
13486: works very similar to store/cstore, but all data is stored in a
13487: temporary location and can be reset using tmpreset, $storehash should
13488: be a hash reference, returns nothing on success
13489:
13490: =item *
13491:
13492: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
13493: similar to restore, but all data is stored in a temporary location and
13494: can be reset using tmpreset. Returns a hash of values on success,
13495: error string otherwise.
13496:
13497: =item *
13498:
13499: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
13500: deltes all keys for $symb form the temporary storage hash.
13501:
13502: =item *
13503:
13504: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13505: reference filled in from namesp ($udom and $uname are optional)
13506:
13507: =item *
13508:
13509: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
13510: namesp ($udom and $uname are optional)
13511:
13512: =item *
13513:
13514: dump($namespace,$udom,$uname,$regexp,$range) :
13515: dumps the complete (or key matching regexp) namespace into a hash
13516: ($udom, $uname, $regexp, $range are optional)
13517:
13518: $range should be either an integer '100' (give me the first 100
13519: matching records)
13520: or be two integers sperated by a - with no spaces
13521: '30-50' (give me the 30th through the 50th matching
13522: records)
13523: =item *
13524:
13525: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
13526: $store can be a scalar, an array reference, or if the amount to be
13527: incremented is > 1, a hash reference.
13528:
13529: ($udom and $uname are optional)
13530:
13531: =item *
13532:
13533: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
13534: ($udom and $uname are optional)
13535:
13536: =item *
13537:
13538: cput($namespace,$storehash,$udom,$uname) : critical put
13539: ($udom and $uname are optional)
13540:
13541: =item *
13542:
13543: newput($namespace,$storehash,$udom,$uname) :
13544:
13545: Attempts to store the items in the $storehash, but only if they don't
13546: currently exist, if this succeeds you can be certain that you have
13547: successfully created a new key value pair in the $namespace db.
13548:
13549:
13550: Args:
13551: $namespace: name of database to store values to
13552: $storehash: hashref to store to the db
13553: $udom: (optional) domain of user containing the db
13554: $uname: (optional) name of user caontaining the db
13555:
13556: Returns:
13557: 'ok' -> succeeded in storing all keys of $storehash
13558: 'key_exists: <key>' -> failed to anything out of $storehash, as at
13559: least <key> already existed in the db (other
13560: requested keys may also already exist)
13561: 'error: <msg>' -> unable to tie the DB or other error occurred
13562: 'con_lost' -> unable to contact request server
13563: 'refused' -> action was not allowed by remote machine
13564:
13565:
13566: =item *
13567:
13568: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
13569: reference filled in from namesp (encrypts the return communication)
13570: ($udom and $uname are optional)
13571:
13572: =item *
13573:
13574: log($udom,$name,$home,$message) : write to permanent log for user; use
13575: critical subroutine
13576:
13577: =item *
13578:
13579: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
13580: array reference filled in from namespace found in domain level on either
13581: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
13582:
13583: =item *
13584:
13585: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
13586: domain level either on specified domain server ($uhome) or primary domain
13587: server ($udom and $uhome are optional)
13588:
13589: =item *
13590:
13591: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
13592: for: authentication, language, quotas, timezone, date locale, and portal URL in
13593: the target domain.
13594:
13595: May also include additional key => value pairs for the following groups:
13596:
13597: =over
13598:
13599: =item
13600: disk quotas (MB allocated by default to portfolios and authoring spaces).
13601:
13602: =over
13603:
13604: =item defaultquota, authorquota
13605:
13606: =back
13607:
13608: =item
13609: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
13610: portfolio for users).
13611:
13612: =over
13613:
13614: =item
13615: aboutme, blog, webdav, portfolio
13616:
13617: =back
13618:
13619: =item
13620: requestcourses: ability to request courses, and how requests are processed.
13621:
13622: =over
13623:
13624: =item
13625: official, unofficial, community, textbook
13626:
13627: =back
13628:
13629: =item
13630: inststatus: types of institutional affiliation, and order in which they are displayed.
13631:
13632: =over
13633:
13634: =item
13635: inststatustypes, inststatusorder, inststatusguest
13636:
13637: =back
13638:
13639: =item
13640: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
13641: for course's uploaded content.
13642:
13643: =over
13644:
13645: =item
13646: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
13647: communityquota, textbookquota
13648:
13649: =back
13650:
13651: =item
13652: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
13653: on your servers.
13654:
13655: =over
13656:
13657: =item
13658: remotesessions, hostedsessions
13659:
13660: =back
13661:
13662: =back
13663:
13664: In cases where a domain coordinator has never used the "Set Domain Configuration"
13665: utility to create a configuration.db file on a domain's primary library server
13666: only the following domain defaults: auth_def, auth_arg_def, lang_def
13667: -- corresponding values are authentication type (internal, krb4, krb5,
13668: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
13669: will be available. Values are retrieved from cache (if current), unless the
13670: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
13671: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
13672:
13673: Typical usage:
13674:
13675: %domdefaults = &get_domain_defaults($target_domain);
13676:
13677: =back
13678:
13679: =head2 Network Status Functions
13680:
13681: =over 4
13682:
13683: =item *
13684:
13685: dirlist() : return directory list based on URI (first arg).
13686:
13687: Inputs: 1 required, 5 optional.
13688:
13689: =over
13690:
13691: =item
13692: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
13693:
13694: =item
13695: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
13696:
13697: =item
13698: $username - username of user/course to be listed. Extracted from $uri if absent.
13699:
13700: =item
13701: $getpropath - boolean: 1 if prepend path using &propath().
13702:
13703: =item
13704: $getuserdir - boolean: 1 if prepend path for "userfiles".
13705:
13706: =item
13707: $alternateRoot - path to prepend in place of path from $uri.
13708:
13709: =back
13710:
13711: Returns: Array of up to two items.
13712:
13713: =over
13714:
13715: a reference to an array of files/subdirectories
13716:
13717: =over
13718:
13719: Each element in the array of files/subdirectories is a & separated list of
13720: item name and the result of running stat on the item. If dirlist was requested
13721: for a file instead of a directory, the item name will be ''. For a directory
13722: listing, if the item is a metadata file, the element will end &N&M
13723: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
13724: default copyright set (1).
13725:
13726: =back
13727:
13728: a scalar containing error condition (if encountered).
13729:
13730: =over
13731:
13732: =item
13733: no_host (no homeserver identified for $username:$domain).
13734:
13735: =item
13736: no_such_host (server contacted for listing not identified as valid host).
13737:
13738: =item
13739: con_lost (connection to remote server failed).
13740:
13741: =item
13742: refused (invalid $username:$domain received on lond side).
13743:
13744: =item
13745: no_such_dir (directory at specified path on lond side does not exist).
13746:
13747: =item
13748: empty (directory at specified path on lond side is empty).
13749:
13750: =over
13751:
13752: This is currently not encountered because the &ls3, &ls2,
13753: &ls (_handler) routines on the lond side do not filter out
13754: . and .. from a directory listing.
13755:
13756: =back
13757:
13758: =back
13759:
13760: =back
13761:
13762: =item *
13763:
13764: spareserver() : find server with least workload from spare.tab
13765:
13766:
13767: =item *
13768:
13769: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
13770: if there is no corresponding loncapa host.
13771:
13772: =back
13773:
13774:
13775: =head2 Apache Request
13776:
13777: =over 4
13778:
13779: =item *
13780:
13781: ssi($url,%hash) : server side include, does a complete request cycle on url to
13782: localhost, posts hash
13783:
13784: =back
13785:
13786: =head2 Data to String to Data
13787:
13788: =over 4
13789:
13790: =item *
13791:
13792: hash2str(%hash) : convert a hash into a string complete with escaping and '='
13793: and '&' separators, supports elements that are arrayrefs and hashrefs
13794:
13795: =item *
13796:
13797: hashref2str($hashref) : convert a hashref into a string complete with
13798: escaping and '=' and '&' separators, supports elements that are
13799: arrayrefs and hashrefs
13800:
13801: =item *
13802:
13803: arrayref2str($arrayref) : convert an arrayref into a string complete
13804: with escaping and '&' separators, supports elements that are arrayrefs
13805: and hashrefs
13806:
13807: =item *
13808:
13809: str2hash($string) : convert string to hash using unescaping and
13810: splitting on '=' and '&', supports elements that are arrayrefs and
13811: hashrefs
13812:
13813: =item *
13814:
13815: str2array($string) : convert string to hash using unescaping and
13816: splitting on '&', supports elements that are arrayrefs and hashrefs
13817:
13818: =back
13819:
13820: =head2 Logging Routines
13821:
13822:
13823: These routines allow one to make log messages in the lonnet.log and
13824: lonnet.perm logfiles.
13825:
13826: =over 4
13827:
13828: =item *
13829:
13830: logtouch() : make sure the logfile, lonnet.log, exists
13831:
13832: =item *
13833:
13834: logthis() : append message to the normal lonnet.log file, it gets
13835: preiodically rolled over and deleted.
13836:
13837: =item *
13838:
13839: logperm() : append a permanent message to lonnet.perm.log, this log
13840: file never gets deleted by any automated portion of the system, only
13841: messages of critical importance should go in here.
13842:
13843:
13844: =back
13845:
13846: =head2 General File Helper Routines
13847:
13848: =over 4
13849:
13850: =item *
13851:
13852: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
13853: (a) files in /uploaded
13854: (i) If a local copy of the file exists -
13855: compares modification date of local copy with last-modified date for
13856: definitive version stored on home server for course. If local copy is
13857: stale, requests a new version from the home server and stores it.
13858: If the original has been removed from the home server, then local copy
13859: is unlinked.
13860: (ii) If local copy does not exist -
13861: requests the file from the home server and stores it.
13862:
13863: If $caller is 'uploadrep':
13864: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
13865: for request for files originally uploaded via DOCS.
13866: - returns 'ok' if fresh local copy now available, -1 otherwise.
13867:
13868: Otherwise:
13869: This indicates a call from the content generation phase of the request.
13870: - returns the entire contents of the file or -1.
13871:
13872: (b) files in /res
13873: - returns the entire contents of a file or -1;
13874: it properly subscribes to and replicates the file if neccessary.
13875:
13876:
13877: =item *
13878:
13879: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
13880: reference
13881:
13882: returns either a stat() list of data about the file or an empty list
13883: if the file doesn't exist or couldn't find out about it (connection
13884: problems or user unknown)
13885:
13886: =item *
13887:
13888: filelocation($dir,$file) : returns file system location of a file
13889: based on URI; meant to be "fairly clean" absolute reference, $dir is a
13890: directory that relative $file lookups are to looked in ($dir of /a/dir
13891: and a file of ../bob will become /a/bob)
13892:
13893: =item *
13894:
13895: hreflocation($dir,$file) : returns file system location or a URL; same as
13896: filelocation except for hrefs
13897:
13898: =item *
13899:
13900: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
13901: also removes beginning /home/httpd/html unless /priv/ follows it.
13902:
13903: =back
13904:
13905: =head2 Usererfile file routines (/uploaded*)
13906:
13907: =over 4
13908:
13909: =item *
13910:
13911: userfileupload(): main rotine for putting a file in a user or course's
13912: filespace, arguments are,
13913:
13914: formname - required - this is the name of the element in $env where the
13915: filename, and the contents of the file to create/modifed exist
13916: the filename is in $env{'form.'.$formname.'.filename'} and the
13917: contents of the file is located in $env{'form.'.$formname}
13918: context - if coursedoc, store the file in the course of the active role
13919: of the current user;
13920: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
13921: if 'canceloverwrite': delete file in tmp/overwrites directory
13922: subdir - required - subdirectory to put the file in under ../userfiles/
13923: if undefined, it will be placed in "unknown"
13924:
13925: (This routine calls clean_filename() to remove any dangerous
13926: characters from the filename, and then calls finuserfileupload() to
13927: complete the transaction)
13928:
13929: returns either the url of the uploaded file (/uploaded/....) if successful
13930: and /adm/notfound.html if unsuccessful
13931:
13932: =item *
13933:
13934: clean_filename(): routine for cleaing a filename up for storage in
13935: userfile space, argument is:
13936:
13937: filename - proposed filename
13938:
13939: returns: the new clean filename
13940:
13941: =item *
13942:
13943: finishuserfileupload(): routine that creates and sends the file to
13944: userspace, probably shouldn't be called directly
13945:
13946: docuname: username or courseid of destination for the file
13947: docudom: domain of user/course of destination for the file
13948: formname: same as for userfileupload()
13949: fname: filename (including subdirectories) for the file
13950: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
13951: allfiles: reference to hash used to store objects found by parser
13952: codebase: reference to hash used for codebases of java objects found by parser
13953: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
13954: thumbheight: height (pixels) of thumbnail to be created for uploaded image
13955: resizewidth: width to be used to resize image using resizeImage from ImageMagick
13956: resizeheight: height to be used to resize image using resizeImage from ImageMagick
13957: context: if 'overwrite', will move the uploaded file from its temporary location to
13958: userfiles to facilitate overwriting a previously uploaded file with same name.
13959: mimetype: reference to scalar to accommodate mime type determined
13960: from File::MMagic if $parser = parse.
13961:
13962: returns either the url of the uploaded file (/uploaded/....) if successful
13963: and /adm/notfound.html if unsuccessful (or an error message if context
13964: was 'overwrite').
13965:
13966:
13967: =item *
13968:
13969: renameuserfile(): renames an existing userfile to a new name
13970:
13971: Args:
13972: docuname: username or courseid of destination for the file
13973: docudom: domain of user/course of destination for the file
13974: old: current file name (including any subdirs under userfiles)
13975: new: desired file name (including any subdirs under userfiles)
13976:
13977: =item *
13978:
13979: mkdiruserfile(): creates a directory is a userfiles dir
13980:
13981: Args:
13982: docuname: username or courseid of destination for the file
13983: docudom: domain of user/course of destination for the file
13984: dir: dir to create (including any subdirs under userfiles)
13985:
13986: =item *
13987:
13988: removeuserfile(): removes a file that exists in userfiles
13989:
13990: Args:
13991: docuname: username or courseid of destination for the file
13992: docudom: domain of user/course of destination for the file
13993: fname: filname to delete (including any subdirs under userfiles)
13994:
13995: =item *
13996:
13997: removeuploadedurl(): convience function for removeuserfile()
13998:
13999: Args:
14000: url: a full /uploaded/... url to delete
14001:
14002: =item *
14003:
14004: get_portfile_permissions():
14005: Args:
14006: domain: domain of user or course contain the portfolio files
14007: user: name of user or num of course contain the portfolio files
14008: Returns:
14009: hashref of a dump of the proper file_permissions.db
14010:
14011:
14012: =item *
14013:
14014: get_access_controls():
14015:
14016: Args:
14017: current_permissions: the hash ref returned from get_portfile_permissions()
14018: group: (optional) the group you want the files associated with
14019: file: (optional) the file you want access info on
14020:
14021: Returns:
14022: a hash (keys are file names) of hashes containing
14023: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
14024: values are XML containing access control settings (see below)
14025:
14026: Internal notes:
14027:
14028: access controls are stored in file_permissions.db as key=value pairs.
14029: key -> path to file/file_name\0uniqueID:scope_end_start
14030: where scope -> public,guest,course,group,domains or users.
14031: end -> UNIX time for end of access (0 -> no end date)
14032: start -> UNIX time for start of access
14033:
14034: value -> XML description of access control
14035: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
14036: <start></start>
14037: <end></end>
14038:
14039: <password></password> for scope type = guest
14040:
14041: <domain></domain> for scope type = course or group
14042: <number></number>
14043: <roles id="">
14044: <role></role>
14045: <access></access>
14046: <section></section>
14047: <group></group>
14048: </roles>
14049:
14050: <dom></dom> for scope type = domains
14051:
14052: <users> for scope type = users
14053: <user>
14054: <uname></uname>
14055: <udom></udom>
14056: </user>
14057: </users>
14058: </scope>
14059:
14060: Access data is also aggregated for each file in an additional key=value pair:
14061: key -> path to file/file_name\0accesscontrol
14062: value -> reference to hash
14063: hash contains key = value pairs
14064: where key = uniqueID:scope_end_start
14065: value = UNIX time record was last updated
14066:
14067: Used to improve speed of look-ups of access controls for each file.
14068:
14069: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
14070:
14071: =item *
14072:
14073: modify_access_controls():
14074:
14075: Modifies access controls for a portfolio file
14076: Args
14077: 1. file name
14078: 2. reference to hash of required changes,
14079: 3. domain
14080: 4. username
14081: where domain,username are the domain of the portfolio owner
14082: (either a user or a course)
14083:
14084: Returns:
14085: 1. result of additions or updates ('ok' or 'error', with error message).
14086: 2. result of deletions ('ok' or 'error', with error message).
14087: 3. reference to hash of any new or updated access controls.
14088: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
14089: key = integer (inbound ID)
14090: value = uniqueID
14091:
14092: =item *
14093:
14094: get_timebased_id():
14095:
14096: Attempts to get a unique timestamp-based suffix for use with items added to a
14097: course via the Course Editor (e.g., folders, composite pages,
14098: group bulletin boards).
14099:
14100: Args: (first three required; six others optional)
14101:
14102: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
14103: docssequence, or name of group
14104:
14105: 2. keyid (alphanumeric): name of temporary locking key in hash,
14106: e.g., num, boardids
14107:
14108: 3. namespace: name of gdbm file used to store suffixes already assigned;
14109: file will be named nohist_namespace.db
14110:
14111: 4. cdom: domain of course; default is current course domain from %env
14112:
14113: 5. cnum: course number; default is current course number from %env
14114:
14115: 6. idtype: set to concat if an additional digit is to be appended to the
14116: unix timestamp to form the suffix, if the plain timestamp is already
14117: in use. Default is to not do this, but simply increment the unix
14118: timestamp by 1 until a unique key is obtained.
14119:
14120: 7. who: holder of locking key; defaults to user:domain for user.
14121:
14122: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
14123: retrying); default is 3.
14124:
14125: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
14126:
14127: Returns:
14128:
14129: 1. suffix obtained (numeric)
14130:
14131: 2. result of deleting locking key (ok if deleted, or lock never obtained)
14132:
14133: 3. error: contains (localized) error message if an error occurred.
14134:
14135:
14136: =back
14137:
14138: =head2 HTTP Helper Routines
14139:
14140: =over 4
14141:
14142: =item *
14143:
14144: escape() : unpack non-word characters into CGI-compatible hex codes
14145:
14146: =item *
14147:
14148: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
14149:
14150: =back
14151:
14152: =head1 PRIVATE SUBROUTINES
14153:
14154: =head2 Underlying communication routines (Shouldn't call)
14155:
14156: =over 4
14157:
14158: =item *
14159:
14160: subreply() : tries to pass a message to lonc, returns con_lost if incapable
14161:
14162: =item *
14163:
14164: reply() : uses subreply to send a message to remote machine, logs all failures
14165:
14166: =item *
14167:
14168: critical() : passes a critical message to another server; if cannot
14169: get through then place message in connection buffer directory and
14170: returns con_delayed, if incapable of saving message, returns
14171: con_failed
14172:
14173: =item *
14174:
14175: reconlonc() : tries to reconnect lonc client processes.
14176:
14177: =back
14178:
14179: =head2 Resource Access Logging
14180:
14181: =over 4
14182:
14183: =item *
14184:
14185: flushcourselogs() : flush (save) buffer logs and access logs
14186:
14187: =item *
14188:
14189: courselog($what) : save message for course in hash
14190:
14191: =item *
14192:
14193: courseacclog($what) : save message for course using &courselog(). Perform
14194: special processing for specific resource types (problems, exams, quizzes, etc).
14195:
14196: =item *
14197:
14198: goodbye() : flush course logs and log shutting down; it is called in srm.conf
14199: as a PerlChildExitHandler
14200:
14201: =back
14202:
14203: =head2 Other
14204:
14205: =over 4
14206:
14207: =item *
14208:
14209: symblist($mapname,%newhash) : update symbolic storage links
14210:
14211: =back
14212:
14213: =cut
14214:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>