1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1167 2012/05/16 21:19:33 droeschl Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
80: %managerstab);
81:
82: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
83: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
84: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
85: %courseownerbuf, %coursetypebuf,$locknum);
86:
87: use IO::Socket;
88: use GDBM_File;
89: use HTML::LCParser;
90: use Fcntl qw(:flock);
91: use Storable qw(thaw nfreeze);
92: use Time::HiRes qw( gettimeofday tv_interval );
93: use Cache::Memcached;
94: use Digest::MD5;
95: use Math::Random;
96: use File::MMagic;
97: use LONCAPA qw(:DEFAULT :match);
98: use LONCAPA::Configuration;
99: use LONCAPA::lonmetadata;
100: use LONCAPA::Lond;
101:
102: use File::Copy;
103:
104: my $readit;
105: my $max_connection_retries = 10; # Or some such value.
106:
107: require Exporter;
108:
109: our @ISA = qw (Exporter);
110: our @EXPORT = qw(%env);
111:
112:
113: # --------------------------------------------------------------------- Logging
114: {
115: my $logid;
116: sub instructor_log {
117: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
118: if (($cnum eq '') || ($cdom eq '')) {
119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
120: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
121: }
122: $logid++;
123: my $now = time();
124: my $id=$now.'00000'.$$.'00000'.$logid;
125: return &Apache::lonnet::put('nohist_'.$hash_name,
126: { $id => {
127: 'exe_uname' => $env{'user.name'},
128: 'exe_udom' => $env{'user.domain'},
129: 'exe_time' => $now,
130: 'exe_ip' => $ENV{'REMOTE_ADDR'},
131: 'delflag' => $delflag,
132: 'logentry' => $storehash,
133: 'uname' => $uname,
134: 'udom' => $udom,
135: }
136: },$cdom,$cnum);
137: }
138: }
139:
140: sub logtouch {
141: my $execdir=$perlvar{'lonDaemons'};
142: unless (-e "$execdir/logs/lonnet.log") {
143: open(my $fh,">>$execdir/logs/lonnet.log");
144: close $fh;
145: }
146: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
147: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
148: }
149:
150: sub logthis {
151: my $message=shift;
152: my $execdir=$perlvar{'lonDaemons'};
153: my $now=time;
154: my $local=localtime($now);
155: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
156: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
157: print $fh $logstring;
158: close($fh);
159: }
160: return 1;
161: }
162:
163: sub logperm {
164: my $message=shift;
165: my $execdir=$perlvar{'lonDaemons'};
166: my $now=time;
167: my $local=localtime($now);
168: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
169: print $fh "$now:$message:$local\n";
170: close($fh);
171: }
172: return 1;
173: }
174:
175: sub create_connection {
176: my ($hostname,$lonid) = @_;
177: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
178: Type => SOCK_STREAM,
179: Timeout => 10);
180: return 0 if (!$client);
181: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
182: my $result = <$client>;
183: chomp($result);
184: return 1 if ($result eq 'done');
185: return 0;
186: }
187:
188: sub get_server_timezone {
189: my ($cnum,$cdom) = @_;
190: my $home=&homeserver($cnum,$cdom);
191: if ($home ne 'no_host') {
192: my $cachetime = 24*3600;
193: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
194: if (defined($cached)) {
195: return $timezone;
196: } else {
197: my $timezone = &reply('servertimezone',$home);
198: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
199: }
200: }
201: }
202:
203: sub get_server_distarch {
204: my ($lonhost,$ignore_cache) = @_;
205: if (defined($lonhost)) {
206: if (!defined(&hostname($lonhost))) {
207: return;
208: }
209: my $cachetime = 12*3600;
210: if (!$ignore_cache) {
211: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
212: if (defined($cached)) {
213: return $distarch;
214: }
215: }
216: my $rep = &reply('serverdistarch',$lonhost);
217: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
218: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
219: $rep eq '') {
220: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
221: }
222: }
223: return;
224: }
225:
226: sub get_server_loncaparev {
227: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
228: if (defined($lonhost)) {
229: if (!defined(&hostname($lonhost))) {
230: undef($lonhost);
231: }
232: }
233: if (!defined($lonhost)) {
234: if (defined(&domain($dom,'primary'))) {
235: $lonhost=&domain($dom,'primary');
236: if ($lonhost eq 'no_host') {
237: undef($lonhost);
238: }
239: }
240: }
241: if (defined($lonhost)) {
242: my $cachetime = 12*3600;
243: if (!$ignore_cache) {
244: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
245: if (defined($cached)) {
246: return $loncaparev;
247: }
248: }
249: my ($answer,$loncaparev);
250: my @ids=¤t_machine_ids();
251: if (grep(/^\Q$lonhost\E$/,@ids)) {
252: $answer = $perlvar{'lonVersion'};
253: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
254: $loncaparev = $1;
255: }
256: } else {
257: $answer = &reply('serverloncaparev',$lonhost);
258: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
259: if ($caller eq 'loncron') {
260: my $ua=new LWP::UserAgent;
261: $ua->timeout(4);
262: my $protocol = $protocol{$lonhost};
263: $protocol = 'http' if ($protocol ne 'https');
264: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
265: my $request=new HTTP::Request('GET',$url);
266: my $response=$ua->request($request);
267: unless ($response->is_error()) {
268: my $content = $response->content;
269: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
270: $loncaparev = $1;
271: }
272: }
273: } else {
274: $loncaparev = $loncaparevs{$lonhost};
275: }
276: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
277: $loncaparev = $1;
278: }
279: }
280: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
281: }
282: }
283:
284: sub get_server_homeID {
285: my ($hostname,$ignore_cache,$caller) = @_;
286: unless ($ignore_cache) {
287: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
288: if (defined($cached)) {
289: return $serverhomeID;
290: }
291: }
292: my $cachetime = 12*3600;
293: my $serverhomeID;
294: if ($caller eq 'loncron') {
295: my @machine_ids = &machine_ids($hostname);
296: foreach my $id (@machine_ids) {
297: my $response = &reply('serverhomeID',$id);
298: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
299: $serverhomeID = $response;
300: last;
301: }
302: }
303: if ($serverhomeID eq '') {
304: $serverhomeID = $machine_ids[-1];
305: }
306: } else {
307: $serverhomeID = $serverhomeIDs{$hostname};
308: }
309: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
310: }
311:
312: sub get_remote_globals {
313: my ($lonhost,$whathash,$ignore_cache) = @_;
314: my ($result,%returnhash,%whatneeded);
315: if (ref($whathash) eq 'HASH') {
316: foreach my $what (sort(keys(%{$whathash}))) {
317: my $hashid = $lonhost.'-'.$what;
318: my ($response,$cached);
319: unless ($ignore_cache) {
320: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
321: }
322: if (defined($cached)) {
323: $returnhash{$what} = $response;
324: } else {
325: $whatneeded{$what} = 1;
326: }
327: }
328: if (keys(%whatneeded) == 0) {
329: $result = 'ok';
330: } else {
331: my $requested = &freeze_escape(\%whatneeded);
332: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
333: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
334: ($rep eq 'unknown_cmd')) {
335: $result = $rep;
336: } else {
337: $result = 'ok';
338: my @pairs=split(/\&/,$rep);
339: foreach my $item (@pairs) {
340: my ($key,$value)=split(/=/,$item,2);
341: my $what = &unescape($key);
342: my $hashid = $lonhost.'-'.$what;
343: $returnhash{$what}=&thaw_unescape($value);
344: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
345: }
346: }
347: }
348: }
349: return ($result,\%returnhash);
350: }
351:
352: sub remote_devalidate_cache {
353: my ($lonhost,$name,$id) = @_;
354: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
355: return $response;
356: }
357:
358: # -------------------------------------------------- Non-critical communication
359: sub subreply {
360: my ($cmd,$server)=@_;
361: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
362: #
363: # With loncnew process trimming, there's a timing hole between lonc server
364: # process exit and the master server picking up the listen on the AF_UNIX
365: # socket. In that time interval, a lock file will exist:
366:
367: my $lockfile=$peerfile.".lock";
368: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
369: sleep(1);
370: }
371: # At this point, either a loncnew parent is listening or an old lonc
372: # or loncnew child is listening so we can connect or everything's dead.
373: #
374: # We'll give the connection a few tries before abandoning it. If
375: # connection is not possible, we'll con_lost back to the client.
376: #
377: my $client;
378: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
379: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
380: Type => SOCK_STREAM,
381: Timeout => 10);
382: if ($client) {
383: last; # Connected!
384: } else {
385: &create_connection(&hostname($server),$server);
386: }
387: sleep(1); # Try again later if failed connection.
388: }
389: my $answer;
390: if ($client) {
391: print $client "sethost:$server:$cmd\n";
392: $answer=<$client>;
393: if (!$answer) { $answer="con_lost"; }
394: chomp($answer);
395: } else {
396: $answer = 'con_lost'; # Failed connection.
397: }
398: return $answer;
399: }
400:
401: sub reply {
402: my ($cmd,$server)=@_;
403: unless (defined(&hostname($server))) { return 'no_such_host'; }
404: my $answer=subreply($cmd,$server);
405: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
406: &logthis("<font color=\"blue\">WARNING:".
407: " $cmd to $server returned $answer</font>");
408: }
409: return $answer;
410: }
411:
412: # ----------------------------------------------------------- Send USR1 to lonc
413:
414: sub reconlonc {
415: my ($lonid) = @_;
416: my $hostname = &hostname($lonid);
417: if ($lonid) {
418: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
419: if ($hostname && -e $peerfile) {
420: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
421: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
422: Type => SOCK_STREAM,
423: Timeout => 10);
424: if ($client) {
425: print $client ("reset_retries\n");
426: my $answer=<$client>;
427: #reset just this one.
428: }
429: }
430: return;
431: }
432:
433: &logthis("Trying to reconnect lonc");
434: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
435: if (open(my $fh,"<$loncfile")) {
436: my $loncpid=<$fh>;
437: chomp($loncpid);
438: if (kill 0 => $loncpid) {
439: &logthis("lonc at pid $loncpid responding, sending USR1");
440: kill USR1 => $loncpid;
441: sleep 1;
442: } else {
443: &logthis(
444: "<font color=\"blue\">WARNING:".
445: " lonc at pid $loncpid not responding, giving up</font>");
446: }
447: } else {
448: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
449: }
450: }
451:
452: # ------------------------------------------------------ Critical communication
453:
454: sub critical {
455: my ($cmd,$server)=@_;
456: unless (&hostname($server)) {
457: &logthis("<font color=\"blue\">WARNING:".
458: " Critical message to unknown server ($server)</font>");
459: return 'no_such_host';
460: }
461: my $answer=reply($cmd,$server);
462: if ($answer eq 'con_lost') {
463: &reconlonc("$perlvar{'lonSockDir'}/$server");
464: my $answer=reply($cmd,$server);
465: if ($answer eq 'con_lost') {
466: my $now=time;
467: my $middlename=$cmd;
468: $middlename=substr($middlename,0,16);
469: $middlename=~s/\W//g;
470: my $dfilename=
471: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
472: $dumpcount++;
473: {
474: my $dfh;
475: if (open($dfh,">$dfilename")) {
476: print $dfh "$cmd\n";
477: close($dfh);
478: }
479: }
480: sleep 2;
481: my $wcmd='';
482: {
483: my $dfh;
484: if (open($dfh,"<$dfilename")) {
485: $wcmd=<$dfh>;
486: close($dfh);
487: }
488: }
489: chomp($wcmd);
490: if ($wcmd eq $cmd) {
491: &logthis("<font color=\"blue\">WARNING: ".
492: "Connection buffer $dfilename: $cmd</font>");
493: &logperm("D:$server:$cmd");
494: return 'con_delayed';
495: } else {
496: &logthis("<font color=\"red\">CRITICAL:"
497: ." Critical connection failed: $server $cmd</font>");
498: &logperm("F:$server:$cmd");
499: return 'con_failed';
500: }
501: }
502: }
503: return $answer;
504: }
505:
506: # ------------------------------------------- check if return value is an error
507:
508: sub error {
509: my ($result) = @_;
510: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
511: if ($2 == 2) { return undef; }
512: return $1;
513: }
514: return undef;
515: }
516:
517: sub convert_and_load_session_env {
518: my ($lonidsdir,$handle)=@_;
519: my @profile;
520: {
521: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
522: if (!$opened) {
523: return 0;
524: }
525: flock($idf,LOCK_SH);
526: @profile=<$idf>;
527: close($idf);
528: }
529: my %temp_env;
530: foreach my $line (@profile) {
531: if ($line !~ m/=/) {
532: return 0;
533: }
534: chomp($line);
535: my ($envname,$envvalue)=split(/=/,$line,2);
536: $temp_env{&unescape($envname)} = &unescape($envvalue);
537: }
538: unlink("$lonidsdir/$handle.id");
539: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
540: 0640)) {
541: %disk_env = %temp_env;
542: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
543: untie(%disk_env);
544: }
545: return 1;
546: }
547:
548: # ------------------------------------------- Transfer profile into environment
549: my $env_loaded;
550: sub transfer_profile_to_env {
551: my ($lonidsdir,$handle,$force_transfer) = @_;
552: if (!$force_transfer && $env_loaded) { return; }
553:
554: if (!defined($lonidsdir)) {
555: $lonidsdir = $perlvar{'lonIDsDir'};
556: }
557: if (!defined($handle)) {
558: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
559: }
560:
561: my $convert;
562: {
563: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
564: if (!$opened) {
565: return;
566: }
567: flock($idf,LOCK_SH);
568: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
569: &GDBM_READER(),0640)) {
570: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
571: untie(%disk_env);
572: } else {
573: $convert = 1;
574: }
575: }
576: if ($convert) {
577: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
578: &logthis("Failed to load session, or convert session.");
579: }
580: }
581:
582: my %remove;
583: while ( my $envname = each(%env) ) {
584: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
585: if ($time < time-300) {
586: $remove{$key}++;
587: }
588: }
589: }
590:
591: $env{'user.environment'} = "$lonidsdir/$handle.id";
592: $env_loaded=1;
593: foreach my $expired_key (keys(%remove)) {
594: &delenv($expired_key);
595: }
596: }
597:
598: # ---------------------------------------------------- Check for valid session
599: sub check_for_valid_session {
600: my ($r,$name) = @_;
601: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
602: if ($name eq '') {
603: $name = 'lonID';
604: }
605: my $lonid=$cookies{$name};
606: return undef if (!$lonid);
607:
608: my $handle=&LONCAPA::clean_handle($lonid->value);
609: my $lonidsdir;
610: if ($name eq 'lonDAV') {
611: $lonidsdir=$r->dir_config('lonDAVsessDir');
612: } else {
613: $lonidsdir=$r->dir_config('lonIDsDir');
614: }
615: return undef if (!-e "$lonidsdir/$handle.id");
616:
617: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
618: return undef if (!$opened);
619:
620: flock($idf,LOCK_SH);
621: my %disk_env;
622: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
623: &GDBM_READER(),0640)) {
624: return undef;
625: }
626:
627: if (!defined($disk_env{'user.name'})
628: || !defined($disk_env{'user.domain'})) {
629: return undef;
630: }
631: return $handle;
632: }
633:
634: sub timed_flock {
635: my ($file,$lock_type) = @_;
636: my $failed=0;
637: eval {
638: local $SIG{__DIE__}='DEFAULT';
639: local $SIG{ALRM}=sub {
640: $failed=1;
641: die("failed lock");
642: };
643: alarm(13);
644: flock($file,$lock_type);
645: alarm(0);
646: };
647: if ($failed) {
648: return undef;
649: } else {
650: return 1;
651: }
652: }
653:
654: # ---------------------------------------------------------- Append Environment
655:
656: sub appenv {
657: my ($newenv,$roles) = @_;
658: if (ref($newenv) eq 'HASH') {
659: foreach my $key (keys(%{$newenv})) {
660: my $refused = 0;
661: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
662: $refused = 1;
663: if (ref($roles) eq 'ARRAY') {
664: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
665: if (grep(/^\Q$role\E$/,@{$roles})) {
666: $refused = 0;
667: }
668: }
669: }
670: if ($refused) {
671: &logthis("<font color=\"blue\">WARNING: ".
672: "Attempt to modify environment ".$key." to ".$newenv->{$key}
673: .'</font>');
674: delete($newenv->{$key});
675: } else {
676: $env{$key}=$newenv->{$key};
677: }
678: }
679: my $opened = open(my $env_file,'+<',$env{'user.environment'});
680: if ($opened
681: && &timed_flock($env_file,LOCK_EX)
682: &&
683: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
684: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
685: while (my ($key,$value) = each(%{$newenv})) {
686: $disk_env{$key} = $value;
687: }
688: untie(%disk_env);
689: }
690: }
691: return 'ok';
692: }
693: # ----------------------------------------------------- Delete from Environment
694:
695: sub delenv {
696: my ($delthis,$regexp,$roles) = @_;
697: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
698: my $refused = 1;
699: if (ref($roles) eq 'ARRAY') {
700: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
701: if (grep(/^\Q$role\E$/,@{$roles})) {
702: $refused = 0;
703: }
704: }
705: if ($refused) {
706: &logthis("<font color=\"blue\">WARNING: ".
707: "Attempt to delete from environment ".$delthis);
708: return 'error';
709: }
710: }
711: my $opened = open(my $env_file,'+<',$env{'user.environment'});
712: if ($opened
713: && &timed_flock($env_file,LOCK_EX)
714: &&
715: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
716: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
717: foreach my $key (keys(%disk_env)) {
718: if ($regexp) {
719: if ($key=~/^$delthis/) {
720: delete($env{$key});
721: delete($disk_env{$key});
722: }
723: } else {
724: if ($key=~/^\Q$delthis\E/) {
725: delete($env{$key});
726: delete($disk_env{$key});
727: }
728: }
729: }
730: untie(%disk_env);
731: }
732: return 'ok';
733: }
734:
735: sub get_env_multiple {
736: my ($name) = @_;
737: my @values;
738: if (defined($env{$name})) {
739: # exists is it an array
740: if (ref($env{$name})) {
741: @values=@{ $env{$name} };
742: } else {
743: $values[0]=$env{$name};
744: }
745: }
746: return(@values);
747: }
748:
749: # ------------------------------------------------------------------- Locking
750:
751: sub set_lock {
752: my ($text)=@_;
753: $locknum++;
754: my $id=$$.'-'.$locknum;
755: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
756: 'session.lock.'.$id => $text});
757: return $id;
758: }
759:
760: sub get_locks {
761: my $num=0;
762: my %texts=();
763: foreach my $lock (split(/\,/,$env{'session.locks'})) {
764: if ($lock=~/\w/) {
765: $num++;
766: $texts{$lock}=$env{'session.lock.'.$lock};
767: }
768: }
769: return ($num,%texts);
770: }
771:
772: sub remove_lock {
773: my ($id)=@_;
774: my $newlocks='';
775: foreach my $lock (split(/\,/,$env{'session.locks'})) {
776: if (($lock=~/\w/) && ($lock ne $id)) {
777: $newlocks.=','.$lock;
778: }
779: }
780: &appenv({'session.locks' => $newlocks});
781: &delenv('session.lock.'.$id);
782: }
783:
784: sub remove_all_locks {
785: my $activelocks=$env{'session.locks'};
786: foreach my $lock (split(/\,/,$env{'session.locks'})) {
787: if ($lock=~/\w/) {
788: &remove_lock($lock);
789: }
790: }
791: }
792:
793:
794: # ------------------------------------------ Find out current server userload
795: sub userload {
796: my $numusers=0;
797: {
798: opendir(LONIDS,$perlvar{'lonIDsDir'});
799: my $filename;
800: my $curtime=time;
801: while ($filename=readdir(LONIDS)) {
802: next if ($filename eq '.' || $filename eq '..');
803: next if ($filename =~ /publicuser_\d+\.id/);
804: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
805: if ($curtime-$mtime < 1800) { $numusers++; }
806: }
807: closedir(LONIDS);
808: }
809: my $userloadpercent=0;
810: my $maxuserload=$perlvar{'lonUserLoadLim'};
811: if ($maxuserload) {
812: $userloadpercent=100*$numusers/$maxuserload;
813: }
814: $userloadpercent=sprintf("%.2f",$userloadpercent);
815: return $userloadpercent;
816: }
817:
818: # ------------------------------ Find server with least workload from spare.tab
819:
820: sub spareserver {
821: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
822: my $spare_server;
823: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
824: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
825: : $userloadpercent;
826: my ($uint_dom,$remotesessions);
827: if (($udom ne '') && (&domain($udom) ne '')) {
828: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
829: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
830: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
831: $remotesessions = $udomdefaults{'remotesessions'};
832: }
833: my $spareshash = &this_host_spares($udom);
834: if (ref($spareshash) eq 'HASH') {
835: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
836: foreach my $try_server (@{ $spareshash->{'primary'} }) {
837: if ($uint_dom) {
838: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
839: $try_server));
840: }
841: ($spare_server, $lowest_load) =
842: &compare_server_load($try_server, $spare_server, $lowest_load);
843: }
844: }
845:
846: my $found_server = ($spare_server ne '' && $lowest_load < 100);
847:
848: if (!$found_server) {
849: if (ref($spareshash->{'default'}) eq 'ARRAY') {
850: foreach my $try_server (@{ $spareshash->{'default'} }) {
851: if ($uint_dom) {
852: next unless (&spare_can_host($udom,$uint_dom,
853: $remotesessions,$try_server));
854: }
855: ($spare_server, $lowest_load) =
856: &compare_server_load($try_server, $spare_server, $lowest_load);
857: }
858: }
859: }
860: }
861:
862: if (!$want_server_name) {
863: my $protocol = 'http';
864: if ($protocol{$spare_server} eq 'https') {
865: $protocol = $protocol{$spare_server};
866: }
867: if (defined($spare_server)) {
868: my $hostname = &hostname($spare_server);
869: if (defined($hostname)) {
870: $spare_server = $protocol.'://'.$hostname;
871: }
872: }
873: }
874: return $spare_server;
875: }
876:
877: sub compare_server_load {
878: my ($try_server, $spare_server, $lowest_load) = @_;
879:
880: my $loadans = &reply('load', $try_server);
881: my $userloadans = &reply('userload',$try_server);
882:
883: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
884: return ($spare_server, $lowest_load); #didn't get a number from the server
885: }
886:
887: my $load;
888: if ($loadans =~ /\d/) {
889: if ($userloadans =~ /\d/) {
890: #both are numbers, pick the bigger one
891: $load = ($loadans > $userloadans) ? $loadans
892: : $userloadans;
893: } else {
894: $load = $loadans;
895: }
896: } else {
897: $load = $userloadans;
898: }
899:
900: if (($load =~ /\d/) && ($load < $lowest_load)) {
901: $spare_server = $try_server;
902: $lowest_load = $load;
903: }
904: return ($spare_server,$lowest_load);
905: }
906:
907: # --------------------------- ask offload servers if user already has a session
908: sub find_existing_session {
909: my ($udom,$uname) = @_;
910: my $spareshash = &this_host_spares($udom);
911: if (ref($spareshash) eq 'HASH') {
912: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
913: foreach my $try_server (@{ $spareshash->{'primary'} }) {
914: return $try_server if (&has_user_session($try_server, $udom, $uname));
915: }
916: }
917: if (ref($spareshash->{'default'}) eq 'ARRAY') {
918: foreach my $try_server (@{ $spareshash->{'default'} }) {
919: return $try_server if (&has_user_session($try_server, $udom, $uname));
920: }
921: }
922: }
923: return;
924: }
925:
926: # -------------------------------- ask if server already has a session for user
927: sub has_user_session {
928: my ($lonid,$udom,$uname) = @_;
929: my $result = &reply(join(':','userhassession',
930: map {&escape($_)} ($udom,$uname)),$lonid);
931: return 1 if ($result eq 'ok');
932:
933: return 0;
934: }
935:
936: # --------- determine least loaded server in a user's domain which allows login
937:
938: sub choose_server {
939: my ($udom,$checkloginvia) = @_;
940: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
941: my %servers = &get_servers($udom);
942: my $lowest_load = 30000;
943: my ($login_host,$hostname,$portal_path,$isredirect);
944: foreach my $lonhost (keys(%servers)) {
945: my $loginvia;
946: if ($checkloginvia) {
947: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
948: if ($loginvia) {
949: my ($server,$path) = split(/:/,$loginvia);
950: ($login_host, $lowest_load) =
951: &compare_server_load($server, $login_host, $lowest_load);
952: if ($login_host eq $server) {
953: $portal_path = $path;
954: $isredirect = 1;
955: }
956: } else {
957: ($login_host, $lowest_load) =
958: &compare_server_load($lonhost, $login_host, $lowest_load);
959: if ($login_host eq $lonhost) {
960: $portal_path = '';
961: $isredirect = '';
962: }
963: }
964: } else {
965: ($login_host, $lowest_load) =
966: &compare_server_load($lonhost, $login_host, $lowest_load);
967: }
968: }
969: if ($login_host ne '') {
970: $hostname = &hostname($login_host);
971: }
972: return ($login_host,$hostname,$portal_path,$isredirect);
973: }
974:
975: # --------------------------------------------- Try to change a user's password
976:
977: sub changepass {
978: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
979: $currentpass = &escape($currentpass);
980: $newpass = &escape($newpass);
981: my $lonhost = $perlvar{'lonHostID'};
982: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
983: $server);
984: if (! $answer) {
985: &logthis("No reply on password change request to $server ".
986: "by $uname in domain $udom.");
987: } elsif ($answer =~ "^ok") {
988: &logthis("$uname in $udom successfully changed their password ".
989: "on $server.");
990: } elsif ($answer =~ "^pwchange_failure") {
991: &logthis("$uname in $udom was unable to change their password ".
992: "on $server. The action was blocked by either lcpasswd ".
993: "or pwchange");
994: } elsif ($answer =~ "^non_authorized") {
995: &logthis("$uname in $udom did not get their password correct when ".
996: "attempting to change it on $server.");
997: } elsif ($answer =~ "^auth_mode_error") {
998: &logthis("$uname in $udom attempted to change their password despite ".
999: "not being locally or internally authenticated on $server.");
1000: } elsif ($answer =~ "^unknown_user") {
1001: &logthis("$uname in $udom attempted to change their password ".
1002: "on $server but were unable to because $server is not ".
1003: "their home server.");
1004: } elsif ($answer =~ "^refused") {
1005: &logthis("$server refused to change $uname in $udom password because ".
1006: "it was sent an unencrypted request to change the password.");
1007: } elsif ($answer =~ "invalid_client") {
1008: &logthis("$server refused to change $uname in $udom password because ".
1009: "it was a reset by e-mail originating from an invalid server.");
1010: }
1011: return $answer;
1012: }
1013:
1014: # ----------------------- Try to determine user's current authentication scheme
1015:
1016: sub queryauthenticate {
1017: my ($uname,$udom)=@_;
1018: my $uhome=&homeserver($uname,$udom);
1019: if (!$uhome) {
1020: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1021: return 'no_host';
1022: }
1023: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1024: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1025: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1026: }
1027: return $answer;
1028: }
1029:
1030: # --------- Try to authenticate user from domain's lib servers (first this one)
1031:
1032: sub authenticate {
1033: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1034: $upass=&escape($upass);
1035: $uname= &LONCAPA::clean_username($uname);
1036: my $uhome=&homeserver($uname,$udom,1);
1037: my $newhome;
1038: if ((!$uhome) || ($uhome eq 'no_host')) {
1039: # Maybe the machine was offline and only re-appeared again recently?
1040: &reconlonc();
1041: # One more
1042: $uhome=&homeserver($uname,$udom,1);
1043: if (($uhome eq 'no_host') && $checkdefauth) {
1044: if (defined(&domain($udom,'primary'))) {
1045: $newhome=&domain($udom,'primary');
1046: }
1047: if ($newhome ne '') {
1048: $uhome = $newhome;
1049: }
1050: }
1051: if ((!$uhome) || ($uhome eq 'no_host')) {
1052: &logthis("User $uname at $udom is unknown in authenticate");
1053: return 'no_host';
1054: }
1055: }
1056: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1057: if ($answer eq 'authorized') {
1058: if ($newhome) {
1059: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1060: return 'no_account_on_host';
1061: } else {
1062: &logthis("User $uname at $udom authorized by $uhome");
1063: return $uhome;
1064: }
1065: }
1066: if ($answer eq 'non_authorized') {
1067: &logthis("User $uname at $udom rejected by $uhome");
1068: return 'no_host';
1069: }
1070: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1071: return 'no_host';
1072: }
1073:
1074: sub can_host_session {
1075: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1076: my $canhost = 1;
1077: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1078: if (ref($remotesessions) eq 'HASH') {
1079: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1080: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1081: $canhost = 0;
1082: } else {
1083: $canhost = 1;
1084: }
1085: }
1086: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1087: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1088: $canhost = 1;
1089: } else {
1090: $canhost = 0;
1091: }
1092: }
1093: if ($canhost) {
1094: if ($remotesessions->{'version'} ne '') {
1095: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1096: if ($reqmajor ne '' && $reqminor ne '') {
1097: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1098: my $major = $1;
1099: my $minor = $2;
1100: if (($major < $reqmajor ) ||
1101: (($major == $reqmajor) && ($minor < $reqminor))) {
1102: $canhost = 0;
1103: }
1104: } else {
1105: $canhost = 0;
1106: }
1107: }
1108: }
1109: }
1110: }
1111: if ($canhost) {
1112: if (ref($hostedsessions) eq 'HASH') {
1113: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1114: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1115: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1116: if (($uint_dom ne '') &&
1117: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1118: $canhost = 0;
1119: } else {
1120: $canhost = 1;
1121: }
1122: }
1123: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1124: if (($uint_dom ne '') &&
1125: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1126: $canhost = 1;
1127: } else {
1128: $canhost = 0;
1129: }
1130: }
1131: }
1132: }
1133: return $canhost;
1134: }
1135:
1136: sub spare_can_host {
1137: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1138: my $canhost=1;
1139: my @intdoms;
1140: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1141: if (ref($internet_names) eq 'ARRAY') {
1142: @intdoms = @{$internet_names};
1143: }
1144: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1145: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1146: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1147: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1148: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1149: $canhost = &can_host_session($udom,$try_server,$remoterev,
1150: $remotesessions,
1151: $defdomdefaults{'hostedsessions'});
1152: }
1153: return $canhost;
1154: }
1155:
1156: sub this_host_spares {
1157: my ($dom) = @_;
1158: my ($dom_in_use,$lonhost_in_use,$result);
1159: my @hosts = ¤t_machine_ids();
1160: foreach my $lonhost (@hosts) {
1161: if (&host_domain($lonhost) eq $dom) {
1162: $dom_in_use = $dom;
1163: $lonhost_in_use = $lonhost;
1164: last;
1165: }
1166: }
1167: if ($dom_in_use ne '') {
1168: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1169: }
1170: if (ref($result) ne 'HASH') {
1171: $lonhost_in_use = $perlvar{'lonHostID'};
1172: $dom_in_use = &host_domain($lonhost_in_use);
1173: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1174: if (ref($result) ne 'HASH') {
1175: $result = \%spareid;
1176: }
1177: }
1178: return $result;
1179: }
1180:
1181: sub spares_for_offload {
1182: my ($dom_in_use,$lonhost_in_use) = @_;
1183: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1184: if (defined($cached)) {
1185: return $result;
1186: } else {
1187: my $cachetime = 60*60*24;
1188: my %domconfig =
1189: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1190: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1191: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1192: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1193: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1194: }
1195: }
1196: }
1197: }
1198: return;
1199: }
1200:
1201: sub get_lonbalancer_config {
1202: my ($servers) = @_;
1203: my ($currbalancer,$currtargets);
1204: if (ref($servers) eq 'HASH') {
1205: foreach my $server (keys(%{$servers})) {
1206: my %what = (
1207: spareid => 1,
1208: perlvar => 1,
1209: );
1210: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1211: if ($result eq 'ok') {
1212: if (ref($returnhash) eq 'HASH') {
1213: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1214: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1215: $currbalancer = $server;
1216: $currtargets = {};
1217: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1218: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1219: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1220: }
1221: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1222: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1223: }
1224: }
1225: last;
1226: }
1227: }
1228: }
1229: }
1230: }
1231: }
1232: return ($currbalancer,$currtargets);
1233: }
1234:
1235: sub check_loadbalancing {
1236: my ($uname,$udom) = @_;
1237: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1238: $offloadto,$otherserver);
1239: my $lonhost = $perlvar{'lonHostID'};
1240: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1241: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1242: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1243: my $serverhomedom = &host_domain($lonhost);
1244:
1245: my $cachetime = 60*60*24;
1246:
1247: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1248: $dom_in_use = $udom;
1249: $homeintdom = 1;
1250: } else {
1251: $dom_in_use = $serverhomedom;
1252: }
1253: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1254: unless (defined($cached)) {
1255: my %domconfig =
1256: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1257: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1258: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1259: }
1260: }
1261: if (ref($result) eq 'HASH') {
1262: my $currbalancer = $result->{'lonhost'};
1263: my $currtargets = $result->{'targets'};
1264: my $currrules = $result->{'rules'};
1265: if ($currbalancer ne '') {
1266: my @hosts = ¤t_machine_ids();
1267: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1268: $is_balancer = 1;
1269: }
1270: }
1271: if ($is_balancer) {
1272: if (ref($currrules) eq 'HASH') {
1273: if ($homeintdom) {
1274: if ($uname ne '') {
1275: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1276: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1277: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1278: $rule_in_effect = $currrules->{'_LC_author'};
1279: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1280: $rule_in_effect = $currrules->{'_LC_adv'}
1281: }
1282: }
1283: if ($rule_in_effect eq '') {
1284: my %userenv = &userenvironment($udom,$uname,'inststatus');
1285: if ($userenv{'inststatus'} ne '') {
1286: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1287: my ($othertitle,$usertypes,$types) =
1288: &Apache::loncommon::sorted_inst_types($udom);
1289: if (ref($types) eq 'ARRAY') {
1290: foreach my $type (@{$types}) {
1291: if (grep(/^\Q$type\E$/,@statuses)) {
1292: if (exists($currrules->{$type})) {
1293: $rule_in_effect = $currrules->{$type};
1294: }
1295: }
1296: }
1297: }
1298: } else {
1299: if (exists($currrules->{'default'})) {
1300: $rule_in_effect = $currrules->{'default'};
1301: }
1302: }
1303: }
1304: } else {
1305: if (exists($currrules->{'default'})) {
1306: $rule_in_effect = $currrules->{'default'};
1307: }
1308: }
1309: } else {
1310: if ($currrules->{'_LC_external'} ne '') {
1311: $rule_in_effect = $currrules->{'_LC_external'};
1312: }
1313: }
1314: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1315: $uname,$udom);
1316: }
1317: }
1318: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1319: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1320: unless (defined($cached)) {
1321: my %domconfig =
1322: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1323: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1324: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1325: }
1326: }
1327: if (ref($result) eq 'HASH') {
1328: my $currbalancer = $result->{'lonhost'};
1329: my $currtargets = $result->{'targets'};
1330: my $currrules = $result->{'rules'};
1331:
1332: if ($currbalancer eq $lonhost) {
1333: $is_balancer = 1;
1334: if (ref($currrules) eq 'HASH') {
1335: if ($currrules->{'_LC_internetdom'} ne '') {
1336: $rule_in_effect = $currrules->{'_LC_internetdom'};
1337: }
1338: }
1339: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1340: $uname,$udom);
1341: }
1342: } else {
1343: if ($perlvar{'lonBalancer'} eq 'yes') {
1344: $is_balancer = 1;
1345: $offloadto = &this_host_spares($dom_in_use);
1346: }
1347: }
1348: } else {
1349: if ($perlvar{'lonBalancer'} eq 'yes') {
1350: $is_balancer = 1;
1351: $offloadto = &this_host_spares($dom_in_use);
1352: }
1353: }
1354: my $lowest_load = 30000;
1355: if (ref($offloadto) eq 'HASH') {
1356: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1357: foreach my $try_server (@{$offloadto->{'primary'}}) {
1358: ($otherserver,$lowest_load) =
1359: &compare_server_load($try_server,$otherserver,$lowest_load);
1360: }
1361: }
1362: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1363:
1364: if (!$found_server) {
1365: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1366: foreach my $try_server (@{$offloadto->{'default'}}) {
1367: ($otherserver,$lowest_load) =
1368: &compare_server_load($try_server,$otherserver,$lowest_load);
1369: }
1370: }
1371: }
1372: } elsif (ref($offloadto) eq 'ARRAY') {
1373: if (@{$offloadto} == 1) {
1374: $otherserver = $offloadto->[0];
1375: } elsif (@{$offloadto} > 1) {
1376: foreach my $try_server (@{$offloadto}) {
1377: ($otherserver,$lowest_load) =
1378: &compare_server_load($try_server,$otherserver,$lowest_load);
1379: }
1380: }
1381: }
1382: return ($is_balancer,$otherserver);
1383: }
1384:
1385: sub get_loadbalancer_targets {
1386: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1387: my $offloadto;
1388: if ($rule_in_effect eq '') {
1389: $offloadto = $currtargets;
1390: } else {
1391: if ($rule_in_effect eq 'homeserver') {
1392: my $homeserver = &homeserver($uname,$udom);
1393: if ($homeserver ne 'no_host') {
1394: $offloadto = [$homeserver];
1395: }
1396: } elsif ($rule_in_effect eq 'externalbalancer') {
1397: my %domconfig =
1398: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1399: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1400: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1401: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1402: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1403: }
1404: }
1405: } else {
1406: my %servers = &dom_servers($udom);
1407: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1408: if (&hostname($remotebalancer) ne '') {
1409: $offloadto = [$remotebalancer];
1410: }
1411: }
1412: } elsif (&hostname($rule_in_effect) ne '') {
1413: $offloadto = [$rule_in_effect];
1414: }
1415: }
1416: return $offloadto;
1417: }
1418:
1419: sub internet_dom_servers {
1420: my ($dom) = @_;
1421: my (%uniqservers,%servers);
1422: my $primaryserver = &hostname(&domain($dom,'primary'));
1423: my @machinedoms = &machine_domains($primaryserver);
1424: foreach my $mdom (@machinedoms) {
1425: my %currservers = %servers;
1426: my %server = &get_servers($mdom);
1427: %servers = (%currservers,%server);
1428: }
1429: my %by_hostname;
1430: foreach my $id (keys(%servers)) {
1431: push(@{$by_hostname{$servers{$id}}},$id);
1432: }
1433: foreach my $hostname (sort(keys(%by_hostname))) {
1434: if (@{$by_hostname{$hostname}} > 1) {
1435: my $match = 0;
1436: foreach my $id (@{$by_hostname{$hostname}}) {
1437: if (&host_domain($id) eq $dom) {
1438: $uniqservers{$id} = $hostname;
1439: $match = 1;
1440: }
1441: }
1442: unless ($match) {
1443: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1444: }
1445: } else {
1446: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1447: }
1448: }
1449: return %uniqservers;
1450: }
1451:
1452: # ---------------------- Find the homebase for a user from domain's lib servers
1453:
1454: my %homecache;
1455: sub homeserver {
1456: my ($uname,$udom,$ignoreBadCache)=@_;
1457: my $index="$uname:$udom";
1458:
1459: if (exists($homecache{$index})) { return $homecache{$index}; }
1460:
1461: my %servers = &get_servers($udom,'library');
1462: foreach my $tryserver (keys(%servers)) {
1463: next if ($ignoreBadCache ne 'true' &&
1464: exists($badServerCache{$tryserver}));
1465:
1466: my $answer=reply("home:$udom:$uname",$tryserver);
1467: if ($answer eq 'found') {
1468: delete($badServerCache{$tryserver});
1469: return $homecache{$index}=$tryserver;
1470: } elsif ($answer eq 'no_host') {
1471: $badServerCache{$tryserver}=1;
1472: }
1473: }
1474: return 'no_host';
1475: }
1476:
1477: # ------------------------------------- Find the usernames behind a list of IDs
1478:
1479: sub idget {
1480: my ($udom,@ids)=@_;
1481: my %returnhash=();
1482:
1483: my %servers = &get_servers($udom,'library');
1484: foreach my $tryserver (keys(%servers)) {
1485: my $idlist=join('&',@ids);
1486: $idlist=~tr/A-Z/a-z/;
1487: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1488: my @answer=();
1489: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1490: @answer=split(/\&/,$reply);
1491: } ;
1492: my $i;
1493: for ($i=0;$i<=$#ids;$i++) {
1494: if ($answer[$i]) {
1495: $returnhash{$ids[$i]}=$answer[$i];
1496: }
1497: }
1498: }
1499: return %returnhash;
1500: }
1501:
1502: # ------------------------------------- Find the IDs behind a list of usernames
1503:
1504: sub idrget {
1505: my ($udom,@unames)=@_;
1506: my %returnhash=();
1507: foreach my $uname (@unames) {
1508: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1509: }
1510: return %returnhash;
1511: }
1512:
1513: # ------------------------------- Store away a list of names and associated IDs
1514:
1515: sub idput {
1516: my ($udom,%ids)=@_;
1517: my %servers=();
1518: foreach my $uname (keys(%ids)) {
1519: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1520: my $uhom=&homeserver($uname,$udom);
1521: if ($uhom ne 'no_host') {
1522: my $id=&escape($ids{$uname});
1523: $id=~tr/A-Z/a-z/;
1524: my $esc_unam=&escape($uname);
1525: if ($servers{$uhom}) {
1526: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1527: } else {
1528: $servers{$uhom}=$id.'='.$esc_unam;
1529: }
1530: }
1531: }
1532: foreach my $server (keys(%servers)) {
1533: &critical('idput:'.$udom.':'.$servers{$server},$server);
1534: }
1535: }
1536:
1537: # ------------------------------dump from db file owned by domainconfig user
1538: sub dump_dom {
1539: my ($namespace, $udom, $regexp) = @_;
1540:
1541: $udom ||= $env{'user.domain'};
1542:
1543: return () unless $udom;
1544:
1545: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1546: }
1547:
1548: # ------------------------------------------ get items from domain db files
1549:
1550: sub get_dom {
1551: my ($namespace,$storearr,$udom,$uhome)=@_;
1552: my $items='';
1553: foreach my $item (@$storearr) {
1554: $items.=&escape($item).'&';
1555: }
1556: $items=~s/\&$//;
1557: if (!$udom) {
1558: $udom=$env{'user.domain'};
1559: if (defined(&domain($udom,'primary'))) {
1560: $uhome=&domain($udom,'primary');
1561: } else {
1562: undef($uhome);
1563: }
1564: } else {
1565: if (!$uhome) {
1566: if (defined(&domain($udom,'primary'))) {
1567: $uhome=&domain($udom,'primary');
1568: }
1569: }
1570: }
1571: if ($udom && $uhome && ($uhome ne 'no_host')) {
1572: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1573: my %returnhash;
1574: if ($rep eq '' || $rep =~ /^error: 2 /) {
1575: return %returnhash;
1576: }
1577: my @pairs=split(/\&/,$rep);
1578: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1579: return @pairs;
1580: }
1581: my $i=0;
1582: foreach my $item (@$storearr) {
1583: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1584: $i++;
1585: }
1586: return %returnhash;
1587: } else {
1588: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1589: }
1590: }
1591:
1592: # -------------------------------------------- put items in domain db files
1593:
1594: sub put_dom {
1595: my ($namespace,$storehash,$udom,$uhome)=@_;
1596: if (!$udom) {
1597: $udom=$env{'user.domain'};
1598: if (defined(&domain($udom,'primary'))) {
1599: $uhome=&domain($udom,'primary');
1600: } else {
1601: undef($uhome);
1602: }
1603: } else {
1604: if (!$uhome) {
1605: if (defined(&domain($udom,'primary'))) {
1606: $uhome=&domain($udom,'primary');
1607: }
1608: }
1609: }
1610: if ($udom && $uhome && ($uhome ne 'no_host')) {
1611: my $items='';
1612: foreach my $item (keys(%$storehash)) {
1613: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1614: }
1615: $items=~s/\&$//;
1616: return &reply("putdom:$udom:$namespace:$items",$uhome);
1617: } else {
1618: &logthis("put_dom failed - no homeserver and/or domain");
1619: }
1620: }
1621:
1622: # --------------------- newput for items in db file owned by domainconfig user
1623: sub newput_dom {
1624: my ($namespace,$storehash,$udom) = @_;
1625: my $result;
1626: if (!$udom) {
1627: $udom=$env{'user.domain'};
1628: }
1629: if ($udom) {
1630: my $uname = &get_domainconfiguser($udom);
1631: $result = &newput($namespace,$storehash,$udom,$uname);
1632: }
1633: return $result;
1634: }
1635:
1636: # --------------------- delete for items in db file owned by domainconfig user
1637: sub del_dom {
1638: my ($namespace,$storearr,$udom)=@_;
1639: if (ref($storearr) eq 'ARRAY') {
1640: if (!$udom) {
1641: $udom=$env{'user.domain'};
1642: }
1643: if ($udom) {
1644: my $uname = &get_domainconfiguser($udom);
1645: return &del($namespace,$storearr,$udom,$uname);
1646: }
1647: }
1648: }
1649:
1650: # ----------------------------------construct domainconfig user for a domain
1651: sub get_domainconfiguser {
1652: my ($udom) = @_;
1653: return $udom.'-domainconfig';
1654: }
1655:
1656: sub retrieve_inst_usertypes {
1657: my ($udom) = @_;
1658: my (%returnhash,@order);
1659: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1660: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1661: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1662: %returnhash = %{$domdefs{'inststatustypes'}};
1663: @order = @{$domdefs{'inststatusorder'}};
1664: } else {
1665: if (defined(&domain($udom,'primary'))) {
1666: my $uhome=&domain($udom,'primary');
1667: my $rep=&reply("inst_usertypes:$udom",$uhome);
1668: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1669: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1670: return (\%returnhash,\@order);
1671: }
1672: my ($hashitems,$orderitems) = split(/:/,$rep);
1673: my @pairs=split(/\&/,$hashitems);
1674: foreach my $item (@pairs) {
1675: my ($key,$value)=split(/=/,$item,2);
1676: $key = &unescape($key);
1677: next if ($key =~ /^error: 2 /);
1678: $returnhash{$key}=&thaw_unescape($value);
1679: }
1680: my @esc_order = split(/\&/,$orderitems);
1681: foreach my $item (@esc_order) {
1682: push(@order,&unescape($item));
1683: }
1684: } else {
1685: &logthis("get_dom failed - no primary domain server for $udom");
1686: }
1687: }
1688: return (\%returnhash,\@order);
1689: }
1690:
1691: sub is_domainimage {
1692: my ($url) = @_;
1693: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1694: if (&domain($1) ne '') {
1695: return '1';
1696: }
1697: }
1698: return;
1699: }
1700:
1701: sub inst_directory_query {
1702: my ($srch) = @_;
1703: my $udom = $srch->{'srchdomain'};
1704: my %results;
1705: my $homeserver = &domain($udom,'primary');
1706: my $outcome;
1707: if ($homeserver ne '') {
1708: my $queryid=&reply("querysend:instdirsearch:".
1709: &escape($srch->{'srchby'}).':'.
1710: &escape($srch->{'srchterm'}).':'.
1711: &escape($srch->{'srchtype'}),$homeserver);
1712: my $host=&hostname($homeserver);
1713: if ($queryid !~/^\Q$host\E\_/) {
1714: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1715: return;
1716: }
1717: my $response = &get_query_reply($queryid);
1718: my $maxtries = 5;
1719: my $tries = 1;
1720: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1721: $response = &get_query_reply($queryid);
1722: $tries ++;
1723: }
1724:
1725: if (!&error($response) && $response ne 'refused') {
1726: if ($response eq 'unavailable') {
1727: $outcome = $response;
1728: } else {
1729: $outcome = 'ok';
1730: my @matches = split(/\n/,$response);
1731: foreach my $match (@matches) {
1732: my ($key,$value) = split(/=/,$match);
1733: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1734: }
1735: }
1736: }
1737: }
1738: return ($outcome,%results);
1739: }
1740:
1741: sub usersearch {
1742: my ($srch) = @_;
1743: my $dom = $srch->{'srchdomain'};
1744: my %results;
1745: my %libserv = &all_library();
1746: my $query = 'usersearch';
1747: foreach my $tryserver (keys(%libserv)) {
1748: if (&host_domain($tryserver) eq $dom) {
1749: my $host=&hostname($tryserver);
1750: my $queryid=
1751: &reply("querysend:".&escape($query).':'.
1752: &escape($srch->{'srchby'}).':'.
1753: &escape($srch->{'srchtype'}).':'.
1754: &escape($srch->{'srchterm'}),$tryserver);
1755: if ($queryid !~/^\Q$host\E\_/) {
1756: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1757: next;
1758: }
1759: my $reply = &get_query_reply($queryid);
1760: my $maxtries = 1;
1761: my $tries = 1;
1762: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1763: $reply = &get_query_reply($queryid);
1764: $tries ++;
1765: }
1766: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1767: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1768: } else {
1769: my @matches;
1770: if ($reply =~ /\n/) {
1771: @matches = split(/\n/,$reply);
1772: } else {
1773: @matches = split(/\&/,$reply);
1774: }
1775: foreach my $match (@matches) {
1776: my ($uname,$udom,%userhash);
1777: foreach my $entry (split(/:/,$match)) {
1778: my ($key,$value) =
1779: map {&unescape($_);} split(/=/,$entry);
1780: $userhash{$key} = $value;
1781: if ($key eq 'username') {
1782: $uname = $value;
1783: } elsif ($key eq 'domain') {
1784: $udom = $value;
1785: }
1786: }
1787: $results{$uname.':'.$udom} = \%userhash;
1788: }
1789: }
1790: }
1791: }
1792: return %results;
1793: }
1794:
1795: sub get_instuser {
1796: my ($udom,$uname,$id) = @_;
1797: my $homeserver = &domain($udom,'primary');
1798: my ($outcome,%results);
1799: if ($homeserver ne '') {
1800: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1801: &escape($id).':'.&escape($udom),$homeserver);
1802: my $host=&hostname($homeserver);
1803: if ($queryid !~/^\Q$host\E\_/) {
1804: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1805: return;
1806: }
1807: my $response = &get_query_reply($queryid);
1808: my $maxtries = 5;
1809: my $tries = 1;
1810: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1811: $response = &get_query_reply($queryid);
1812: $tries ++;
1813: }
1814: if (!&error($response) && $response ne 'refused') {
1815: if ($response eq 'unavailable') {
1816: $outcome = $response;
1817: } else {
1818: $outcome = 'ok';
1819: my @matches = split(/\n/,$response);
1820: foreach my $match (@matches) {
1821: my ($key,$value) = split(/=/,$match);
1822: $results{&unescape($key)} = &thaw_unescape($value);
1823: }
1824: }
1825: }
1826: }
1827: my %userinfo;
1828: if (ref($results{$uname}) eq 'HASH') {
1829: %userinfo = %{$results{$uname}};
1830: }
1831: return ($outcome,%userinfo);
1832: }
1833:
1834: sub inst_rulecheck {
1835: my ($udom,$uname,$id,$item,$rules) = @_;
1836: my %returnhash;
1837: if ($udom ne '') {
1838: if (ref($rules) eq 'ARRAY') {
1839: @{$rules} = map {&escape($_);} (@{$rules});
1840: my $rulestr = join(':',@{$rules});
1841: my $homeserver=&domain($udom,'primary');
1842: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1843: my $response;
1844: if ($item eq 'username') {
1845: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1846: ':'.&escape($uname).':'.$rulestr,
1847: $homeserver));
1848: } elsif ($item eq 'id') {
1849: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1850: ':'.&escape($id).':'.$rulestr,
1851: $homeserver));
1852: } elsif ($item eq 'selfcreate') {
1853: $response=&unescape(&reply('instselfcreatecheck:'.
1854: &escape($udom).':'.&escape($uname).
1855: ':'.$rulestr,$homeserver));
1856: }
1857: if ($response ne 'refused') {
1858: my @pairs=split(/\&/,$response);
1859: foreach my $item (@pairs) {
1860: my ($key,$value)=split(/=/,$item,2);
1861: $key = &unescape($key);
1862: next if ($key =~ /^error: 2 /);
1863: $returnhash{$key}=&thaw_unescape($value);
1864: }
1865: }
1866: }
1867: }
1868: }
1869: return %returnhash;
1870: }
1871:
1872: sub inst_userrules {
1873: my ($udom,$check) = @_;
1874: my (%ruleshash,@ruleorder);
1875: if ($udom ne '') {
1876: my $homeserver=&domain($udom,'primary');
1877: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1878: my $response;
1879: if ($check eq 'id') {
1880: $response=&reply('instidrules:'.&escape($udom),
1881: $homeserver);
1882: } elsif ($check eq 'email') {
1883: $response=&reply('instemailrules:'.&escape($udom),
1884: $homeserver);
1885: } else {
1886: $response=&reply('instuserrules:'.&escape($udom),
1887: $homeserver);
1888: }
1889: if (($response ne 'refused') && ($response ne 'error') &&
1890: ($response ne 'unknown_cmd') &&
1891: ($response ne 'no_such_host')) {
1892: my ($hashitems,$orderitems) = split(/:/,$response);
1893: my @pairs=split(/\&/,$hashitems);
1894: foreach my $item (@pairs) {
1895: my ($key,$value)=split(/=/,$item,2);
1896: $key = &unescape($key);
1897: next if ($key =~ /^error: 2 /);
1898: $ruleshash{$key}=&thaw_unescape($value);
1899: }
1900: my @esc_order = split(/\&/,$orderitems);
1901: foreach my $item (@esc_order) {
1902: push(@ruleorder,&unescape($item));
1903: }
1904: }
1905: }
1906: }
1907: return (\%ruleshash,\@ruleorder);
1908: }
1909:
1910: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1911:
1912: sub get_domain_defaults {
1913: my ($domain) = @_;
1914: my $cachetime = 60*60*24;
1915: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1916: if (defined($cached)) {
1917: if (ref($result) eq 'HASH') {
1918: return %{$result};
1919: }
1920: }
1921: my %domdefaults;
1922: my %domconfig =
1923: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1924: 'requestcourses','inststatus',
1925: 'coursedefaults','usersessions'],$domain);
1926: if (ref($domconfig{'defaults'}) eq 'HASH') {
1927: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1928: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1929: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1930: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1931: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1932: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1933: } else {
1934: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1935: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1936: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1937: }
1938: if (ref($domconfig{'quotas'}) eq 'HASH') {
1939: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1940: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1941: } else {
1942: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1943: }
1944: my @usertools = ('aboutme','blog','portfolio');
1945: foreach my $item (@usertools) {
1946: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1947: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1948: }
1949: }
1950: }
1951: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1952: foreach my $item ('official','unofficial','community') {
1953: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1954: }
1955: }
1956: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1957: foreach my $item ('inststatustypes','inststatusorder') {
1958: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1959: }
1960: }
1961: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1962: foreach my $item ('canuse_pdfforms') {
1963: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1964: }
1965: }
1966: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1967: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1968: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1969: }
1970: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1971: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1972: }
1973: }
1974: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1975: $cachetime);
1976: return %domdefaults;
1977: }
1978:
1979: # --------------------------------------------------- Assign a key to a student
1980:
1981: sub assign_access_key {
1982: #
1983: # a valid key looks like uname:udom#comments
1984: # comments are being appended
1985: #
1986: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1987: $kdom=
1988: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1989: $knum=
1990: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1991: $cdom=
1992: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1993: $cnum=
1994: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1995: $udom=$env{'user.name'} unless (defined($udom));
1996: $uname=$env{'user.domain'} unless (defined($uname));
1997: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1998: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1999: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2000: # assigned to this person
2001: # - this should not happen,
2002: # unless something went wrong
2003: # the first time around
2004: # ready to assign
2005: $logentry=$1.'; '.$logentry;
2006: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2007: $kdom,$knum) eq 'ok') {
2008: # key now belongs to user
2009: my $envkey='key.'.$cdom.'_'.$cnum;
2010: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2011: &appenv({'environment.'.$envkey => $ckey});
2012: return 'ok';
2013: } else {
2014: return
2015: 'error: Count not permanently assign key, will need to be re-entered later.';
2016: }
2017: } else {
2018: return 'error: Could not assign key, try again later.';
2019: }
2020: } elsif (!$existing{$ckey}) {
2021: # the key does not exist
2022: return 'error: The key does not exist';
2023: } else {
2024: # the key is somebody else's
2025: return 'error: The key is already in use';
2026: }
2027: }
2028:
2029: # ------------------------------------------ put an additional comment on a key
2030:
2031: sub comment_access_key {
2032: #
2033: # a valid key looks like uname:udom#comments
2034: # comments are being appended
2035: #
2036: my ($ckey,$cdom,$cnum,$logentry)=@_;
2037: $cdom=
2038: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2039: $cnum=
2040: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2041: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2042: if ($existing{$ckey}) {
2043: $existing{$ckey}.='; '.$logentry;
2044: # ready to assign
2045: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2046: $cdom,$cnum) eq 'ok') {
2047: return 'ok';
2048: } else {
2049: return 'error: Count not store comment.';
2050: }
2051: } else {
2052: # the key does not exist
2053: return 'error: The key does not exist';
2054: }
2055: }
2056:
2057: # ------------------------------------------------------ Generate a set of keys
2058:
2059: sub generate_access_keys {
2060: my ($number,$cdom,$cnum,$logentry)=@_;
2061: $cdom=
2062: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2063: $cnum=
2064: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2065: unless (&allowed('mky',$cdom)) { return 0; }
2066: unless (($cdom) && ($cnum)) { return 0; }
2067: if ($number>10000) { return 0; }
2068: sleep(2); # make sure don't get same seed twice
2069: srand(time()^($$+($$<<15))); # from "Programming Perl"
2070: my $total=0;
2071: for (my $i=1;$i<=$number;$i++) {
2072: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2073: sprintf("%lx",int(100000*rand)).'-'.
2074: sprintf("%lx",int(100000*rand));
2075: $newkey=~s/1/g/g; # folks mix up 1 and l
2076: $newkey=~s/0/h/g; # and also 0 and O
2077: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2078: if ($existing{$newkey}) {
2079: $i--;
2080: } else {
2081: if (&put('accesskeys',
2082: { $newkey => '# generated '.localtime().
2083: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2084: '; '.$logentry },
2085: $cdom,$cnum) eq 'ok') {
2086: $total++;
2087: }
2088: }
2089: }
2090: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2091: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2092: return $total;
2093: }
2094:
2095: # ------------------------------------------------------- Validate an accesskey
2096:
2097: sub validate_access_key {
2098: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2099: $cdom=
2100: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2101: $cnum=
2102: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2103: $udom=$env{'user.domain'} unless (defined($udom));
2104: $uname=$env{'user.name'} unless (defined($uname));
2105: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2106: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2107: }
2108:
2109: # ------------------------------------- Find the section of student in a course
2110: sub devalidate_getsection_cache {
2111: my ($udom,$unam,$courseid)=@_;
2112: my $hashid="$udom:$unam:$courseid";
2113: &devalidate_cache_new('getsection',$hashid);
2114: }
2115:
2116: sub courseid_to_courseurl {
2117: my ($courseid) = @_;
2118: #already url style courseid
2119: return $courseid if ($courseid =~ m{^/});
2120:
2121: if (exists($env{'course.'.$courseid.'.num'})) {
2122: my $cnum = $env{'course.'.$courseid.'.num'};
2123: my $cdom = $env{'course.'.$courseid.'.domain'};
2124: return "/$cdom/$cnum";
2125: }
2126:
2127: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2128: if (exists($courseinfo{'num'})) {
2129: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2130: }
2131:
2132: return undef;
2133: }
2134:
2135: sub getsection {
2136: my ($udom,$unam,$courseid)=@_;
2137: my $cachetime=1800;
2138:
2139: my $hashid="$udom:$unam:$courseid";
2140: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2141: if (defined($cached)) { return $result; }
2142:
2143: my %Pending;
2144: my %Expired;
2145: #
2146: # Each role can either have not started yet (pending), be active,
2147: # or have expired.
2148: #
2149: # If there is an active role, we are done.
2150: #
2151: # If there is more than one role which has not started yet,
2152: # choose the one which will start sooner
2153: # If there is one role which has not started yet, return it.
2154: #
2155: # If there is more than one expired role, choose the one which ended last.
2156: # If there is a role which has expired, return it.
2157: #
2158: $courseid = &courseid_to_courseurl($courseid);
2159: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2160: foreach my $key (keys(%roleshash)) {
2161: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2162: my $section=$1;
2163: if ($key eq $courseid.'_st') { $section=''; }
2164: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2165: my $now=time;
2166: if (defined($end) && $end && ($now > $end)) {
2167: $Expired{$end}=$section;
2168: next;
2169: }
2170: if (defined($start) && $start && ($now < $start)) {
2171: $Pending{$start}=$section;
2172: next;
2173: }
2174: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2175: }
2176: #
2177: # Presumedly there will be few matching roles from the above
2178: # loop and the sorting time will be negligible.
2179: if (scalar(keys(%Pending))) {
2180: my ($time) = sort {$a <=> $b} keys(%Pending);
2181: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2182: }
2183: if (scalar(keys(%Expired))) {
2184: my @sorted = sort {$a <=> $b} keys(%Expired);
2185: my $time = pop(@sorted);
2186: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2187: }
2188: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2189: }
2190:
2191: sub save_cache {
2192: &purge_remembered();
2193: #&Apache::loncommon::validate_page();
2194: undef(%env);
2195: undef($env_loaded);
2196: }
2197:
2198: my $to_remember=-1;
2199: my %remembered;
2200: my %accessed;
2201: my $kicks=0;
2202: my $hits=0;
2203: sub make_key {
2204: my ($name,$id) = @_;
2205: if (length($id) > 65
2206: && length(&escape($id)) > 200) {
2207: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2208: }
2209: return &escape($name.':'.$id);
2210: }
2211:
2212: sub devalidate_cache_new {
2213: my ($name,$id,$debug) = @_;
2214: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2215: $id=&make_key($name,$id);
2216: $memcache->delete($id);
2217: delete($remembered{$id});
2218: delete($accessed{$id});
2219: }
2220:
2221: sub is_cached_new {
2222: my ($name,$id,$debug) = @_;
2223: $id=&make_key($name,$id);
2224: if (exists($remembered{$id})) {
2225: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
2226: $accessed{$id}=[&gettimeofday()];
2227: $hits++;
2228: return ($remembered{$id},1);
2229: }
2230: my $value = $memcache->get($id);
2231: if (!(defined($value))) {
2232: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2233: return (undef,undef);
2234: }
2235: if ($value eq '__undef__') {
2236: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2237: $value=undef;
2238: }
2239: &make_room($id,$value,$debug);
2240: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2241: return ($value,1);
2242: }
2243:
2244: sub do_cache_new {
2245: my ($name,$id,$value,$time,$debug) = @_;
2246: $id=&make_key($name,$id);
2247: my $setvalue=$value;
2248: if (!defined($setvalue)) {
2249: $setvalue='__undef__';
2250: }
2251: if (!defined($time) ) {
2252: $time=600;
2253: }
2254: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2255: my $result = $memcache->set($id,$setvalue,$time);
2256: if (! $result) {
2257: &logthis("caching of id -> $id failed");
2258: $memcache->disconnect_all();
2259: }
2260: # need to make a copy of $value
2261: &make_room($id,$value,$debug);
2262: return $value;
2263: }
2264:
2265: sub make_room {
2266: my ($id,$value,$debug)=@_;
2267:
2268: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2269: : $value;
2270: if ($to_remember<0) { return; }
2271: $accessed{$id}=[&gettimeofday()];
2272: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2273: my $to_kick;
2274: my $max_time=0;
2275: foreach my $other (keys(%accessed)) {
2276: if (&tv_interval($accessed{$other}) > $max_time) {
2277: $to_kick=$other;
2278: $max_time=&tv_interval($accessed{$other});
2279: }
2280: }
2281: delete($remembered{$to_kick});
2282: delete($accessed{$to_kick});
2283: $kicks++;
2284: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2285: return;
2286: }
2287:
2288: sub purge_remembered {
2289: #&logthis("Tossing ".scalar(keys(%remembered)));
2290: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2291: undef(%remembered);
2292: undef(%accessed);
2293: }
2294: # ------------------------------------- Read an entry from a user's environment
2295:
2296: sub userenvironment {
2297: my ($udom,$unam,@what)=@_;
2298: my $items;
2299: foreach my $item (@what) {
2300: $items.=&escape($item).'&';
2301: }
2302: $items=~s/\&$//;
2303: my %returnhash=();
2304: my $uhome = &homeserver($unam,$udom);
2305: unless ($uhome eq 'no_host') {
2306: my @answer=split(/\&/,
2307: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2308: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2309: return %returnhash;
2310: }
2311: my $i;
2312: for ($i=0;$i<=$#what;$i++) {
2313: $returnhash{$what[$i]}=&unescape($answer[$i]);
2314: }
2315: }
2316: return %returnhash;
2317: }
2318:
2319: # ---------------------------------------------------------- Get a studentphoto
2320: sub studentphoto {
2321: my ($udom,$unam,$ext) = @_;
2322: my $home=&Apache::lonnet::homeserver($unam,$udom);
2323: if (defined($env{'request.course.id'})) {
2324: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2325: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2326: return(&retrievestudentphoto($udom,$unam,$ext));
2327: } else {
2328: my ($result,$perm_reqd)=
2329: &Apache::lonnet::auto_photo_permission($unam,$udom);
2330: if ($result eq 'ok') {
2331: if (!($perm_reqd eq 'yes')) {
2332: return(&retrievestudentphoto($udom,$unam,$ext));
2333: }
2334: }
2335: }
2336: }
2337: } else {
2338: my ($result,$perm_reqd) =
2339: &Apache::lonnet::auto_photo_permission($unam,$udom);
2340: if ($result eq 'ok') {
2341: if (!($perm_reqd eq 'yes')) {
2342: return(&retrievestudentphoto($udom,$unam,$ext));
2343: }
2344: }
2345: }
2346: return '/adm/lonKaputt/lonlogo_broken.gif';
2347: }
2348:
2349: sub retrievestudentphoto {
2350: my ($udom,$unam,$ext,$type) = @_;
2351: my $home=&Apache::lonnet::homeserver($unam,$udom);
2352: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2353: if ($ret eq 'ok') {
2354: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2355: if ($type eq 'thumbnail') {
2356: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2357: }
2358: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2359: return $tokenurl;
2360: } else {
2361: if ($type eq 'thumbnail') {
2362: return '/adm/lonKaputt/genericstudent_tn.gif';
2363: } else {
2364: return '/adm/lonKaputt/lonlogo_broken.gif';
2365: }
2366: }
2367: }
2368:
2369: # -------------------------------------------------------------------- New chat
2370:
2371: sub chatsend {
2372: my ($newentry,$anon,$group)=@_;
2373: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2374: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2375: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2376: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2377: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2378: &escape($newentry)).':'.$group,$chome);
2379: }
2380:
2381: # ------------------------------------------ Find current version of a resource
2382:
2383: sub getversion {
2384: my $fname=&clutter(shift);
2385: unless ($fname=~/^\/res\//) { return -1; }
2386: return ¤tversion(&filelocation('',$fname));
2387: }
2388:
2389: sub currentversion {
2390: my $fname=shift;
2391: my $author=$fname;
2392: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2393: my ($udom,$uname)=split(/\//,$author);
2394: my $home=&homeserver($uname,$udom);
2395: if ($home eq 'no_host') {
2396: return -1;
2397: }
2398: my $answer=&reply("currentversion:$fname",$home);
2399: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2400: return -1;
2401: }
2402: return $answer;
2403: }
2404:
2405: #
2406: # Return special version number of resource if set by override, empty otherwise
2407: #
2408: sub usedversion {
2409: my $fname=shift;
2410: unless ($fname) { $fname=$env{'request.uri'}; }
2411: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2412: if ($urlversion) { return $urlversion; }
2413: return '';
2414: }
2415:
2416: # ----------------------------- Subscribe to a resource, return URL if possible
2417:
2418: sub subscribe {
2419: my $fname=shift;
2420: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2421: $fname=~s/[\n\r]//g;
2422: my $author=$fname;
2423: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2424: my ($udom,$uname)=split(/\//,$author);
2425: my $home=homeserver($uname,$udom);
2426: if ($home eq 'no_host') {
2427: return 'not_found';
2428: }
2429: my $answer=reply("sub:$fname",$home);
2430: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2431: $answer.=' by '.$home;
2432: }
2433: return $answer;
2434: }
2435:
2436: # -------------------------------------------------------------- Replicate file
2437:
2438: sub repcopy {
2439: my $filename=shift;
2440: $filename=~s/\/+/\//g;
2441: my $londocroot = $perlvar{'lonDocRoot'};
2442: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
2443: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
2444: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2445: $filename=~m{^/*(uploaded|editupload)/}) {
2446: return &repcopy_userfile($filename);
2447: }
2448: $filename=~s/[\n\r]//g;
2449: my $transname="$filename.in.transfer";
2450: # FIXME: this should flock
2451: if ((-e $filename) || (-e $transname)) { return 'ok'; }
2452: my $remoteurl=subscribe($filename);
2453: if ($remoteurl =~ /^con_lost by/) {
2454: &logthis("Subscribe returned $remoteurl: $filename");
2455: return 'unavailable';
2456: } elsif ($remoteurl eq 'not_found') {
2457: #&logthis("Subscribe returned not_found: $filename");
2458: return 'not_found';
2459: } elsif ($remoteurl =~ /^rejected by/) {
2460: &logthis("Subscribe returned $remoteurl: $filename");
2461: return 'forbidden';
2462: } elsif ($remoteurl eq 'directory') {
2463: return 'ok';
2464: } else {
2465: my $author=$filename;
2466: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2467: my ($udom,$uname)=split(/\//,$author);
2468: my $home=homeserver($uname,$udom);
2469: unless ($home eq $perlvar{'lonHostID'}) {
2470: my @parts=split(/\//,$filename);
2471: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2472: if ($path ne "$londocroot/res") {
2473: &logthis("Malconfiguration for replication: $filename");
2474: return 'bad_request';
2475: }
2476: my $count;
2477: for ($count=5;$count<$#parts;$count++) {
2478: $path.="/$parts[$count]";
2479: if ((-e $path)!=1) {
2480: mkdir($path,0777);
2481: }
2482: }
2483: my $ua=new LWP::UserAgent;
2484: my $request=new HTTP::Request('GET',"$remoteurl");
2485: my $response=$ua->request($request,$transname);
2486: if ($response->is_error()) {
2487: unlink($transname);
2488: my $message=$response->status_line;
2489: &logthis("<font color=\"blue\">WARNING:"
2490: ." LWP get: $message: $filename</font>");
2491: return 'unavailable';
2492: } else {
2493: if ($remoteurl!~/\.meta$/) {
2494: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2495: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2496: if ($mresponse->is_error()) {
2497: unlink($filename.'.meta');
2498: &logthis(
2499: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
2500: }
2501: }
2502: rename($transname,$filename);
2503: return 'ok';
2504: }
2505: }
2506: }
2507: }
2508:
2509: # ------------------------------------------------ Get server side include body
2510: sub ssi_body {
2511: my ($filelink,%form)=@_;
2512: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2513: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2514: }
2515: my $output='';
2516: my $response;
2517: if ($filelink=~/^https?\:/) {
2518: ($output,$response)=&externalssi($filelink);
2519: } else {
2520: $filelink .= $filelink=~/\?/ ? '&' : '?';
2521: $filelink .= 'inhibitmenu=yes';
2522: ($output,$response)=&ssi($filelink,%form);
2523: }
2524: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
2525: $output=~s/^.*?\<body[^\>]*\>//si;
2526: $output=~s/\<\/body\s*\>.*?$//si;
2527: if (wantarray) {
2528: return ($output, $response);
2529: } else {
2530: return $output;
2531: }
2532: }
2533:
2534: # --------------------------------------------------------- Server Side Include
2535:
2536: sub absolute_url {
2537: my ($host_name) = @_;
2538: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2539: if ($host_name eq '') {
2540: $host_name = $ENV{'SERVER_NAME'};
2541: }
2542: return $protocol.$host_name;
2543: }
2544:
2545: #
2546: # Server side include.
2547: # Parameters:
2548: # fn Possibly encrypted resource name/id.
2549: # form Hash that describes how the rendering should be done
2550: # and other things.
2551: # Returns:
2552: # Scalar context: The content of the response.
2553: # Array context: 2 element list of the content and the full response object.
2554: #
2555: sub ssi {
2556:
2557: my ($fn,%form)=@_;
2558: my $ua=new LWP::UserAgent;
2559: my $request;
2560:
2561: $form{'no_update_last_known'}=1;
2562: &Apache::lonenc::check_encrypt(\$fn);
2563: if (%form) {
2564: $request=new HTTP::Request('POST',&absolute_url().$fn);
2565: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2566: } else {
2567: $request=new HTTP::Request('GET',&absolute_url().$fn);
2568: }
2569:
2570: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2571: my $response=$ua->request($request);
2572:
2573: if (wantarray) {
2574: return ($response->content, $response);
2575: } else {
2576: return $response->content;
2577: }
2578: }
2579:
2580: sub externalssi {
2581: my ($url)=@_;
2582: my $ua=new LWP::UserAgent;
2583: my $request=new HTTP::Request('GET',$url);
2584: my $response=$ua->request($request);
2585: if (wantarray) {
2586: return ($response->content, $response);
2587: } else {
2588: return $response->content;
2589: }
2590: }
2591:
2592: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2593:
2594: sub allowuploaded {
2595: my ($srcurl,$url)=@_;
2596: $url=&clutter(&declutter($url));
2597: my $dir=$url;
2598: $dir=~s/\/[^\/]+$//;
2599: my %httpref=();
2600: my $httpurl=&hreflocation('',$url);
2601: $httpref{'httpref.'.$httpurl}=$srcurl;
2602: &Apache::lonnet::appenv(\%httpref);
2603: }
2604:
2605: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2606: # input: action, courseID, current domain, intended
2607: # path to file, source of file, instruction to parse file for objects,
2608: # ref to hash for embedded objects,
2609: # ref to hash for codebase of java objects.
2610: # reference to scalar to accommodate mime type determined
2611: # from File::MMagic if $parser = parse.
2612: #
2613: # output: url to file (if action was uploaddoc),
2614: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2615: #
2616: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2617: # course.
2618: #
2619: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2620: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2621: # course's home server.
2622: #
2623: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2624: # be copied from $source (current location) to
2625: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2626: # and will then be copied to
2627: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2628: # course's home server.
2629: #
2630: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2631: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2632: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2633: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2634: # in course's home server.
2635: #
2636:
2637: sub process_coursefile {
2638: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2639: $mimetype)=@_;
2640: my $fetchresult;
2641: my $home=&homeserver($docuname,$docudom);
2642: if ($action eq 'propagate') {
2643: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2644: $home);
2645: } else {
2646: my $fpath = '';
2647: my $fname = $file;
2648: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2649: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2650: my $filepath = &build_filepath($fpath);
2651: if ($action eq 'copy') {
2652: if ($source eq '') {
2653: $fetchresult = 'no source file';
2654: return $fetchresult;
2655: } else {
2656: my $destination = $filepath.'/'.$fname;
2657: rename($source,$destination);
2658: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2659: $home);
2660: }
2661: } elsif ($action eq 'uploaddoc') {
2662: open(my $fh,'>'.$filepath.'/'.$fname);
2663: print $fh $env{'form.'.$source};
2664: close($fh);
2665: if ($parser eq 'parse') {
2666: my $mm = new File::MMagic;
2667: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2668: if ($type eq 'text/html') {
2669: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2670: unless ($parse_result eq 'ok') {
2671: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2672: }
2673: }
2674: if (ref($mimetype)) {
2675: $$mimetype = $type;
2676: }
2677: }
2678: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2679: $home);
2680: if ($fetchresult eq 'ok') {
2681: return '/uploaded/'.$fpath.'/'.$fname;
2682: } else {
2683: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2684: ' to host '.$home.': '.$fetchresult);
2685: return '/adm/notfound.html';
2686: }
2687: }
2688: }
2689: unless ( $fetchresult eq 'ok') {
2690: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2691: ' to host '.$home.': '.$fetchresult);
2692: }
2693: return $fetchresult;
2694: }
2695:
2696: sub build_filepath {
2697: my ($fpath) = @_;
2698: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2699: unless ($fpath eq '') {
2700: my @parts=split('/',$fpath);
2701: foreach my $part (@parts) {
2702: $filepath.= '/'.$part;
2703: if ((-e $filepath)!=1) {
2704: mkdir($filepath,0777);
2705: }
2706: }
2707: }
2708: return $filepath;
2709: }
2710:
2711: sub store_edited_file {
2712: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2713: my $file = $primary_url;
2714: $file =~ s#^/uploaded/$docudom/$docuname/##;
2715: my $fpath = '';
2716: my $fname = $file;
2717: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2718: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2719: my $filepath = &build_filepath($fpath);
2720: open(my $fh,'>'.$filepath.'/'.$fname);
2721: print $fh $content;
2722: close($fh);
2723: my $home=&homeserver($docuname,$docudom);
2724: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2725: $home);
2726: if ($$fetchresult eq 'ok') {
2727: return '/uploaded/'.$fpath.'/'.$fname;
2728: } else {
2729: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2730: ' to host '.$home.': '.$$fetchresult);
2731: return '/adm/notfound.html';
2732: }
2733: }
2734:
2735: sub clean_filename {
2736: my ($fname,$args)=@_;
2737: # Replace Windows backslashes by forward slashes
2738: $fname=~s/\\/\//g;
2739: if (!$args->{'keep_path'}) {
2740: # Get rid of everything but the actual filename
2741: $fname=~s/^.*\/([^\/]+)$/$1/;
2742: }
2743: # Replace spaces by underscores
2744: $fname=~s/\s+/\_/g;
2745: # Replace all other weird characters by nothing
2746: $fname=~s{[^/\w\.\-]}{}g;
2747: # Replace all .\d. sequences with _\d. so they no longer look like version
2748: # numbers
2749: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2750: return $fname;
2751: }
2752: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2753: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2754: # image with the same aspect ratio as the original, but with dimensions which do
2755: # not exceed $resizewidth and $resizeheight.
2756:
2757: sub resizeImage {
2758: my ($img_path,$resizewidth,$resizeheight) = @_;
2759: my $ima = Image::Magick->new;
2760: my $resized;
2761: if (-e $img_path) {
2762: $ima->Read($img_path);
2763: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2764: my $width = $ima->Get('width');
2765: my $height = $ima->Get('height');
2766: if ($width > $resizewidth) {
2767: my $factor = $width/$resizewidth;
2768: my $newheight = $height/$factor;
2769: $ima->Scale(width=>$resizewidth,height=>$newheight);
2770: $resized = 1;
2771: }
2772: }
2773: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2774: my $width = $ima->Get('width');
2775: my $height = $ima->Get('height');
2776: if ($height > $resizeheight) {
2777: my $factor = $height/$resizeheight;
2778: my $newwidth = $width/$factor;
2779: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2780: $resized = 1;
2781: }
2782: }
2783: if ($resized) {
2784: $ima->Write($img_path);
2785: }
2786: }
2787: return;
2788: }
2789:
2790: # --------------- Take an uploaded file and put it into the userfiles directory
2791: # input: $formname - the contents of the file are in $env{"form.$formname"}
2792: # the desired filename is in $env{"form.$formname.filename"}
2793: # $context - possible values: coursedoc, existingfile, overwrite,
2794: # canceloverwrite, or ''.
2795: # if 'coursedoc': upload to the current course
2796: # if 'existingfile': write file to tmp/overwrites directory
2797: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2798: # $context is passed as argument to &finishuserfileupload
2799: # $subdir - directory in userfile to store the file into
2800: # $parser - instruction to parse file for objects ($parser = parse)
2801: # $allfiles - reference to hash for embedded objects
2802: # $codebase - reference to hash for codebase of java objects
2803: # $desuname - username for permanent storage of uploaded file
2804: # $dsetudom - domain for permanaent storage of uploaded file
2805: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2806: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2807: # $resizewidth - width (pixels) to which to resize uploaded image
2808: # $resizeheight - height (pixels) to which to resize uploaded image
2809: # $mimetype - reference to scalar to accommodate mime type determined
2810: # from File::MMagic.
2811: #
2812: # output: url of file in userspace, or error: <message>
2813: # or /adm/notfound.html if failure to upload occurse
2814:
2815: sub userfileupload {
2816: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
2817: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
2818: if (!defined($subdir)) { $subdir='unknown'; }
2819: my $fname=$env{'form.'.$formname.'.filename'};
2820: $fname=&clean_filename($fname);
2821: # See if there is anything left
2822: unless ($fname) { return 'error: no uploaded file'; }
2823: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2824: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2825: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2826: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2827: my $now = time;
2828: my $filepath;
2829: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
2830: $filepath = 'tmp/helprequests/'.$now;
2831: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2832: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2833: '_'.$env{'user.domain'}.'/pending';
2834: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2835: my ($docuname,$docudom);
2836: if ($destudom) {
2837: $docudom = $destudom;
2838: } else {
2839: $docudom = $env{'user.domain'};
2840: }
2841: if ($destuname) {
2842: $docuname = $destuname;
2843: } else {
2844: $docuname = $env{'user.name'};
2845: }
2846: if (exists($env{'form.group'})) {
2847: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2848: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2849: }
2850: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2851: if ($context eq 'canceloverwrite') {
2852: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2853: if (-e $tempfile) {
2854: my @info = stat($tempfile);
2855: if ($info[9] eq $env{'form.timestamp'}) {
2856: unlink($tempfile);
2857: }
2858: }
2859: return;
2860: }
2861: }
2862: # Create the directory if not present
2863: my @parts=split(/\//,$filepath);
2864: my $fullpath = $perlvar{'lonDaemons'};
2865: for (my $i=0;$i<@parts;$i++) {
2866: $fullpath .= '/'.$parts[$i];
2867: if ((-e $fullpath)!=1) {
2868: mkdir($fullpath,0777);
2869: }
2870: }
2871: open(my $fh,'>'.$fullpath.'/'.$fname);
2872: print $fh $env{'form.'.$formname};
2873: close($fh);
2874: if ($context eq 'existingfile') {
2875: my @info = stat($fullpath.'/'.$fname);
2876: return ($fullpath.'/'.$fname,$info[9]);
2877: } else {
2878: return $fullpath.'/'.$fname;
2879: }
2880: }
2881: if ($subdir eq 'scantron') {
2882: $fname = 'scantron_orig_'.$fname;
2883: } else {
2884: $fname="$subdir/$fname";
2885: }
2886: if ($context eq 'coursedoc') {
2887: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2888: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2889: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2890: return &finishuserfileupload($docuname,$docudom,
2891: $formname,$fname,$parser,$allfiles,
2892: $codebase,$thumbwidth,$thumbheight,
2893: $resizewidth,$resizeheight,$context,$mimetype);
2894: } else {
2895: $fname=$env{'form.folder'}.'/'.$fname;
2896: return &process_coursefile('uploaddoc',$docuname,$docudom,
2897: $fname,$formname,$parser,
2898: $allfiles,$codebase,$mimetype);
2899: }
2900: } elsif (defined($destuname)) {
2901: my $docuname=$destuname;
2902: my $docudom=$destudom;
2903: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2904: $parser,$allfiles,$codebase,
2905: $thumbwidth,$thumbheight,
2906: $resizewidth,$resizeheight,$context,$mimetype);
2907: } else {
2908: my $docuname=$env{'user.name'};
2909: my $docudom=$env{'user.domain'};
2910: if (exists($env{'form.group'})) {
2911: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2912: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2913: }
2914: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2915: $parser,$allfiles,$codebase,
2916: $thumbwidth,$thumbheight,
2917: $resizewidth,$resizeheight,$context,$mimetype);
2918: }
2919: }
2920:
2921: sub finishuserfileupload {
2922: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2923: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
2924: my $path=$docudom.'/'.$docuname.'/';
2925: my $filepath=$perlvar{'lonDocRoot'};
2926:
2927: my ($fnamepath,$file,$fetchthumb);
2928: $file=$fname;
2929: if ($fname=~m|/|) {
2930: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2931: $path.=$fnamepath.'/';
2932: }
2933: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2934: my $count;
2935: for ($count=4;$count<=$#parts;$count++) {
2936: $filepath.="/$parts[$count]";
2937: if ((-e $filepath)!=1) {
2938: mkdir($filepath,0777);
2939: }
2940: }
2941:
2942: # Save the file
2943: {
2944: if (!open(FH,'>'.$filepath.'/'.$file)) {
2945: &logthis('Failed to create '.$filepath.'/'.$file);
2946: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2947: return '/adm/notfound.html';
2948: }
2949: if ($context eq 'overwrite') {
2950: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
2951: my $target = $filepath.'/'.$file;
2952: if (-e $source) {
2953: my @info = stat($source);
2954: if ($info[9] eq $env{'form.timestamp'}) {
2955: unless (&File::Copy::move($source,$target)) {
2956: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2957: return "Moving from $source failed";
2958: }
2959: } else {
2960: return "Temporary file: $source had unexpected date/time for last modification";
2961: }
2962: } else {
2963: return "Temporary file: $source missing";
2964: }
2965: } elsif (!print FH ($env{'form.'.$formname})) {
2966: &logthis('Failed to write to '.$filepath.'/'.$file);
2967: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2968: return '/adm/notfound.html';
2969: }
2970: close(FH);
2971: if ($resizewidth && $resizeheight) {
2972: my $mm = new File::MMagic;
2973: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2974: if ($mime_type =~ m{^image/}) {
2975: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2976: }
2977: }
2978: }
2979: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
2980: if (ref($mimetype)) {
2981: if ($$mimetype eq '') {
2982: my $mm = new File::MMagic;
2983: my $type = $mm->checktype_filename($filepath.'/'.$file);
2984: $$mimetype = $type;
2985: }
2986: }
2987: }
2988: if ($parser eq 'parse') {
2989: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
2990: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2991: $allfiles,$codebase);
2992: unless ($parse_result eq 'ok') {
2993: &logthis('Failed to parse '.$filepath.$file.
2994: ' for embedded media: '.$parse_result);
2995: }
2996: }
2997: }
2998: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2999: my $input = $filepath.'/'.$file;
3000: my $output = $filepath.'/'.'tn-'.$file;
3001: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3002: system("convert -sample $thumbsize $input $output");
3003: if (-e $filepath.'/'.'tn-'.$file) {
3004: $fetchthumb = 1;
3005: }
3006: }
3007:
3008: # Notify homeserver to grep it
3009: #
3010: my $docuhome=&homeserver($docuname,$docudom);
3011: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3012: if ($fetchresult eq 'ok') {
3013: if ($fetchthumb) {
3014: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3015: if ($thumbresult ne 'ok') {
3016: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3017: $docuhome.': '.$thumbresult);
3018: }
3019: }
3020: #
3021: # Return the URL to it
3022: return '/uploaded/'.$path.$file;
3023: } else {
3024: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3025: ': '.$fetchresult);
3026: return '/adm/notfound.html';
3027: }
3028: }
3029:
3030: sub extract_embedded_items {
3031: my ($fullpath,$allfiles,$codebase,$content) = @_;
3032: my @state = ();
3033: my (%lastids,%related,%shockwave,%flashvars);
3034: my %javafiles = (
3035: codebase => '',
3036: code => '',
3037: archive => ''
3038: );
3039: my %mediafiles = (
3040: src => '',
3041: movie => '',
3042: );
3043: my $p;
3044: if ($content) {
3045: $p = HTML::LCParser->new($content);
3046: } else {
3047: $p = HTML::LCParser->new($fullpath);
3048: }
3049: while (my $t=$p->get_token()) {
3050: if ($t->[0] eq 'S') {
3051: my ($tagname, $attr) = ($t->[1],$t->[2]);
3052: push(@state, $tagname);
3053: if (lc($tagname) eq 'allow') {
3054: &add_filetype($allfiles,$attr->{'src'},'src');
3055: }
3056: if (lc($tagname) eq 'img') {
3057: &add_filetype($allfiles,$attr->{'src'},'src');
3058: }
3059: if (lc($tagname) eq 'a') {
3060: &add_filetype($allfiles,$attr->{'href'},'href');
3061: }
3062: if (lc($tagname) eq 'script') {
3063: my $src;
3064: if ($attr->{'archive'} =~ /\.jar$/i) {
3065: &add_filetype($allfiles,$attr->{'archive'},'archive');
3066: } else {
3067: if ($attr->{'src'} ne '') {
3068: $src = $attr->{'src'};
3069: &add_filetype($allfiles,$src,'src');
3070: }
3071: }
3072: my $text = $p->get_trimmed_text();
3073: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3074: my @swfargs = split(/,/,$1);
3075: foreach my $item (@swfargs) {
3076: $item =~ s/["']//g;
3077: $item =~ s/^\s+//;
3078: $item =~ s/\s+$//;
3079: }
3080: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3081: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3082: push(@{$related{$swfargs[0]}},$swfargs[2]);
3083: } else {
3084: $related{$swfargs[0]} = [$swfargs[2]];
3085: }
3086: }
3087: }
3088: }
3089: if (lc($tagname) eq 'link') {
3090: if (lc($attr->{'rel'}) eq 'stylesheet') {
3091: &add_filetype($allfiles,$attr->{'href'},'href');
3092: }
3093: }
3094: if (lc($tagname) eq 'object' ||
3095: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3096: foreach my $item (keys(%javafiles)) {
3097: $javafiles{$item} = '';
3098: }
3099: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3100: $lastids{lc($tagname)} = $attr->{'id'};
3101: }
3102: }
3103: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3104: my $name = lc($attr->{'name'});
3105: foreach my $item (keys(%javafiles)) {
3106: if ($name eq $item) {
3107: $javafiles{$item} = $attr->{'value'};
3108: last;
3109: }
3110: }
3111: my $pathfrom;
3112: foreach my $item (keys(%mediafiles)) {
3113: if ($name eq $item) {
3114: $pathfrom = $attr->{'value'};
3115: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3116: &add_filetype($allfiles,$pathfrom,$name);
3117: last;
3118: }
3119: }
3120: if ($name eq 'flashvars') {
3121: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3122: }
3123: if ($pathfrom ne '') {
3124: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3125: $pathfrom);
3126: }
3127: }
3128: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3129: foreach my $item (keys(%javafiles)) {
3130: if ($attr->{$item}) {
3131: $javafiles{$item} = $attr->{$item};
3132: last;
3133: }
3134: }
3135: foreach my $item (keys(%mediafiles)) {
3136: if ($attr->{$item}) {
3137: &add_filetype($allfiles,$attr->{$item},$item);
3138: last;
3139: }
3140: }
3141: if (lc($tagname) eq 'embed') {
3142: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3143: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3144: $attr->{'src'});
3145: }
3146: }
3147: }
3148: if ($t->[4] =~ m{/>$}) {
3149: pop(@state);
3150: }
3151: } elsif ($t->[0] eq 'E') {
3152: my ($tagname) = ($t->[1]);
3153: if ($javafiles{'codebase'} ne '') {
3154: $javafiles{'codebase'} .= '/';
3155: }
3156: if (lc($tagname) eq 'applet' ||
3157: lc($tagname) eq 'object' ||
3158: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3159: ) {
3160: foreach my $item (keys(%javafiles)) {
3161: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3162: my $file=$javafiles{'codebase'}.$javafiles{$item};
3163: &add_filetype($allfiles,$file,$item);
3164: }
3165: }
3166: }
3167: pop @state;
3168: }
3169: }
3170: foreach my $id (sort(keys(%flashvars))) {
3171: if ($shockwave{$id} ne '') {
3172: my @pairs = split(/\&/,$flashvars{$id});
3173: foreach my $pair (@pairs) {
3174: my ($key,$value) = split(/\=/,$pair);
3175: if ($key eq 'thumb') {
3176: &add_filetype($allfiles,$value,$key);
3177: } elsif ($key eq 'content') {
3178: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3179: my ($ext) = ($value =~ /\.([^.]+)$/);
3180: if ($ext ne '') {
3181: &add_filetype($allfiles,$path.$value,$ext);
3182: }
3183: }
3184: }
3185: }
3186: }
3187: return 'ok';
3188: }
3189:
3190: sub add_filetype {
3191: my ($allfiles,$file,$type)=@_;
3192: if (exists($allfiles->{$file})) {
3193: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3194: push(@{$allfiles->{$file}}, &escape($type));
3195: }
3196: } else {
3197: @{$allfiles->{$file}} = (&escape($type));
3198: }
3199: }
3200:
3201: sub embedded_dependency {
3202: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3203: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3204: if (($identifier ne '') &&
3205: (ref($related->{$identifier}) eq 'ARRAY') &&
3206: ($pathfrom ne '')) {
3207: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3208: foreach my $dep (@{$related->{$identifier}}) {
3209: &add_filetype($allfiles,$path.$dep,'object');
3210: }
3211: }
3212: }
3213: return;
3214: }
3215:
3216: sub removeuploadedurl {
3217: my ($url)=@_;
3218: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
3219: return &removeuserfile($uname,$udom,$fname);
3220: }
3221:
3222: sub removeuserfile {
3223: my ($docuname,$docudom,$fname)=@_;
3224: my $home=&homeserver($docuname,$docudom);
3225: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
3226: if ($result eq 'ok') {
3227: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3228: my $metafile = $fname.'.meta';
3229: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
3230: my $url = "/uploaded/$docudom/$docuname/$fname";
3231: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3232: my $sqlresult =
3233: &update_portfolio_table($docuname,$docudom,$file,
3234: 'portfolio_metadata',$group,
3235: 'delete');
3236: }
3237: }
3238: return $result;
3239: }
3240:
3241: sub mkdiruserfile {
3242: my ($docuname,$docudom,$dir)=@_;
3243: my $home=&homeserver($docuname,$docudom);
3244: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3245: }
3246:
3247: sub renameuserfile {
3248: my ($docuname,$docudom,$old,$new)=@_;
3249: my $home=&homeserver($docuname,$docudom);
3250: my $result = &reply("renameuserfile:$docudom:$docuname:".
3251: &escape("$old").':'.&escape("$new"),$home);
3252: if ($result eq 'ok') {
3253: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3254: my $oldmeta = $old.'.meta';
3255: my $newmeta = $new.'.meta';
3256: my $metaresult =
3257: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
3258: my $url = "/uploaded/$docudom/$docuname/$old";
3259: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
3260: my $sqlresult =
3261: &update_portfolio_table($docuname,$docudom,$file,
3262: 'portfolio_metadata',$group,
3263: 'delete');
3264: }
3265: }
3266: return $result;
3267: }
3268:
3269: # ------------------------------------------------------------------------- Log
3270:
3271: sub log {
3272: my ($dom,$nam,$hom,$what)=@_;
3273: return critical("log:$dom:$nam:$what",$hom);
3274: }
3275:
3276: # ------------------------------------------------------------------ Course Log
3277: #
3278: # This routine flushes several buffers of non-mission-critical nature
3279: #
3280:
3281: sub flushcourselogs {
3282: &logthis('Flushing log buffers');
3283: #
3284: # course logs
3285: # This is a log of all transactions in a course, which can be used
3286: # for data mining purposes
3287: #
3288: # It also collects the courseid database, which lists last transaction
3289: # times and course titles for all courseids
3290: #
3291: my %courseidbuffer=();
3292: foreach my $crsid (keys(%courselogs)) {
3293: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
3294: &escape($courselogs{$crsid}),
3295: $coursehombuf{$crsid}) eq 'ok') {
3296: delete $courselogs{$crsid};
3297: } else {
3298: &logthis('Failed to flush log buffer for '.$crsid);
3299: if (length($courselogs{$crsid})>40000) {
3300: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
3301: " exceeded maximum size, deleting.</font>");
3302: delete $courselogs{$crsid};
3303: }
3304: }
3305: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
3306: 'description' => $coursedescrbuf{$crsid},
3307: 'inst_code' => $courseinstcodebuf{$crsid},
3308: 'type' => $coursetypebuf{$crsid},
3309: 'owner' => $courseownerbuf{$crsid},
3310: };
3311: }
3312: #
3313: # Write course id database (reverse lookup) to homeserver of courses
3314: # Is used in pickcourse
3315: #
3316: foreach my $crs_home (keys(%courseidbuffer)) {
3317: my $response = &courseidput(&host_domain($crs_home),
3318: $courseidbuffer{$crs_home},
3319: $crs_home,'timeonly');
3320: }
3321: #
3322: # File accesses
3323: # Writes to the dynamic metadata of resources to get hit counts, etc.
3324: #
3325: foreach my $entry (keys(%accesshash)) {
3326: if ($entry =~ /___count$/) {
3327: my ($dom,$name);
3328: ($dom,$name,undef)=
3329: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
3330: if (! defined($dom) || $dom eq '' ||
3331: ! defined($name) || $name eq '') {
3332: my $cid = $env{'request.course.id'};
3333: $dom = $env{'request.'.$cid.'.domain'};
3334: $name = $env{'request.'.$cid.'.num'};
3335: }
3336: my $value = $accesshash{$entry};
3337: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3338: my %temphash=($url => $value);
3339: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3340: if ($result eq 'ok') {
3341: delete $accesshash{$entry};
3342: }
3343: } else {
3344: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
3345: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
3346: my %temphash=($entry => $accesshash{$entry});
3347: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3348: delete $accesshash{$entry};
3349: }
3350: }
3351: }
3352: #
3353: # Roles
3354: # Reverse lookup of user roles for course faculty/staff and co-authorship
3355: #
3356: foreach my $entry (keys(%userrolehash)) {
3357: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
3358: split(/\:/,$entry);
3359: if (&Apache::lonnet::put('nohist_userroles',
3360: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
3361: $rudom,$runame) eq 'ok') {
3362: delete $userrolehash{$entry};
3363: }
3364: }
3365: #
3366: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3367: #
3368: my %domrolebuffer = ();
3369: foreach my $entry (keys(%domainrolehash)) {
3370: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
3371: if ($domrolebuffer{$rudom}) {
3372: $domrolebuffer{$rudom}.='&'.&escape($entry).
3373: '='.&escape($domainrolehash{$entry});
3374: } else {
3375: $domrolebuffer{$rudom}.=&escape($entry).
3376: '='.&escape($domainrolehash{$entry});
3377: }
3378: delete $domainrolehash{$entry};
3379: }
3380: foreach my $dom (keys(%domrolebuffer)) {
3381: my %servers = &get_servers($dom,'library');
3382: foreach my $tryserver (keys(%servers)) {
3383: unless (&reply('domroleput:'.$dom.':'.
3384: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3385: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3386: }
3387: }
3388: }
3389: $dumpcount++;
3390: }
3391:
3392: sub courselog {
3393: my $what=shift;
3394: $what=time.':'.$what;
3395: unless ($env{'request.course.id'}) { return ''; }
3396: $coursedombuf{$env{'request.course.id'}}=
3397: $env{'course.'.$env{'request.course.id'}.'.domain'};
3398: $coursenumbuf{$env{'request.course.id'}}=
3399: $env{'course.'.$env{'request.course.id'}.'.num'};
3400: $coursehombuf{$env{'request.course.id'}}=
3401: $env{'course.'.$env{'request.course.id'}.'.home'};
3402: $coursedescrbuf{$env{'request.course.id'}}=
3403: $env{'course.'.$env{'request.course.id'}.'.description'};
3404: $courseinstcodebuf{$env{'request.course.id'}}=
3405: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3406: $courseownerbuf{$env{'request.course.id'}}=
3407: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
3408: $coursetypebuf{$env{'request.course.id'}}=
3409: $env{'course.'.$env{'request.course.id'}.'.type'};
3410: if (defined $courselogs{$env{'request.course.id'}}) {
3411: $courselogs{$env{'request.course.id'}}.='&'.$what;
3412: } else {
3413: $courselogs{$env{'request.course.id'}}.=$what;
3414: }
3415: if (length($courselogs{$env{'request.course.id'}})>4048) {
3416: &flushcourselogs();
3417: }
3418: }
3419:
3420: sub courseacclog {
3421: my $fnsymb=shift;
3422: unless ($env{'request.course.id'}) { return ''; }
3423: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
3424: if ($fnsymb=~/$LONCAPA::assess_re/) {
3425: $what.=':POST';
3426: # FIXME: Probably ought to escape things....
3427: foreach my $key (keys(%env)) {
3428: if ($key=~/^form\.(.*)/) {
3429: my $formitem = $1;
3430: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3431: $what.=':'.$formitem.'='.$env{$key};
3432: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3433: $what.=':'.$formitem.'='.$env{$key};
3434: }
3435: }
3436: }
3437: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3438: # FIXME: We should not be depending on a form parameter that someone
3439: # editing lonsearchcat.pm might change in the future.
3440: if ($env{'form.phase'} eq 'course_search') {
3441: $what.= ':POST';
3442: # FIXME: Probably ought to escape things....
3443: foreach my $element ('courseexp','crsfulltext','crsrelated',
3444: 'crsdiscuss') {
3445: $what.=':'.$element.'='.$env{'form.'.$element};
3446: }
3447: }
3448: }
3449: &courselog($what);
3450: }
3451:
3452: sub countacc {
3453: my $url=&declutter(shift);
3454: return if (! defined($url) || $url eq '');
3455: unless ($env{'request.course.id'}) { return ''; }
3456: #
3457: # Mark that this url was used in this course
3458: #
3459: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
3460: #
3461: # Increase the access count for this resource in this child process
3462: #
3463: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
3464: $accesshash{$key}++;
3465: }
3466:
3467: sub linklog {
3468: my ($from,$to)=@_;
3469: $from=&declutter($from);
3470: $to=&declutter($to);
3471: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3472: $accesshash{$to.'___'.$from.'___goto'}=1;
3473: }
3474:
3475: sub statslog {
3476: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3477: if ($users<2) { return; }
3478: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3479: 'course' => $env{'request.course.id'},
3480: 'sections' => '"all"',
3481: 'num_students' => $users,
3482: 'part' => $part,
3483: 'symb' => $symb,
3484: 'mean_tries' => $av_attempts,
3485: 'deg_of_diff' => $degdiff});
3486: foreach my $key (keys(%dynstore)) {
3487: $accesshash{$key}=$dynstore{$key};
3488: }
3489: }
3490:
3491: sub userrolelog {
3492: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
3493: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
3494: ($trole=~/^in/) || ($trole=~/^cc/) ||
3495: ($trole=~/^ep/) || ($trole=~/^cr/) ||
3496: ($trole=~/^ta/) || ($trole=~/^co/)) {
3497: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3498: $userrolehash
3499: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3500: =$tend.':'.$tstart;
3501: }
3502: if (($env{'request.role'} =~ /dc\./) &&
3503: (($trole=~/^au/) || ($trole=~/^in/) ||
3504: ($trole=~/^cc/) || ($trole=~/^ep/) ||
3505: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3506: ($trole=~/^co/))) {
3507: $userrolehash
3508: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3509: =$tend.':'.$tstart;
3510: }
3511: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3512: ($trole=~/^li/) || ($trole=~/^li/) ||
3513: ($trole=~/^au/) || ($trole=~/^dg/) ||
3514: ($trole=~/^sc/)) {
3515: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3516: $domainrolehash
3517: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3518: = $tend.':'.$tstart;
3519: }
3520: }
3521:
3522: sub courserolelog {
3523: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3524: if (($trole eq 'cc') || ($trole eq 'in') ||
3525: ($trole eq 'ep') || ($trole eq 'ad') ||
3526: ($trole eq 'ta') || ($trole eq 'st') ||
3527: ($trole=~/^cr/) || ($trole eq 'gr') ||
3528: ($trole eq 'co')) {
3529: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3530: my $cdom = $1;
3531: my $cnum = $2;
3532: my $sec = $3;
3533: my $namespace = 'rolelog';
3534: my %storehash = (
3535: role => $trole,
3536: start => $tstart,
3537: end => $tend,
3538: selfenroll => $selfenroll,
3539: context => $context,
3540: );
3541: if ($trole eq 'gr') {
3542: $namespace = 'groupslog';
3543: $storehash{'group'} = $sec;
3544: } else {
3545: $storehash{'section'} = $sec;
3546: }
3547: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
3548: if (($trole ne 'st') || ($sec ne '')) {
3549: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3550: }
3551: }
3552: }
3553: return;
3554: }
3555:
3556: sub get_course_adv_roles {
3557: my ($cid,$codes) = @_;
3558: $cid=$env{'request.course.id'} unless (defined($cid));
3559: my %coursehash=&coursedescription($cid);
3560: my $crstype = &Apache::loncommon::course_type($cid);
3561: my %nothide=();
3562: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3563: if ($user !~ /:/) {
3564: $nothide{join(':',split(/[\@]/,$user))}=1;
3565: } else {
3566: $nothide{$user}=1;
3567: }
3568: }
3569: my %returnhash=();
3570: my %dumphash=
3571: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3572: my $now=time;
3573: my %privileged;
3574: foreach my $entry (keys(%dumphash)) {
3575: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3576: if (($tstart) && ($tstart<0)) { next; }
3577: if (($tend) && ($tend<$now)) { next; }
3578: if (($tstart) && ($now<$tstart)) { next; }
3579: my ($role,$username,$domain,$section)=split(/\:/,$entry);
3580: if ($username eq '' || $domain eq '') { next; }
3581: unless (ref($privileged{$domain}) eq 'HASH') {
3582: my %dompersonnel =
3583: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3584: $privileged{$domain} = {};
3585: foreach my $server (keys(%dompersonnel)) {
3586: if (ref($dompersonnel{$server}) eq 'HASH') {
3587: foreach my $user (keys(%{$dompersonnel{$server}})) {
3588: my ($trole,$uname,$udom) = split(/:/,$user);
3589: $privileged{$udom}{$uname} = 1;
3590: }
3591: }
3592: }
3593: }
3594: if ((exists($privileged{$domain}{$username})) &&
3595: (!$nothide{$username.':'.$domain})) { next; }
3596: if ($role eq 'cr') { next; }
3597: if ($codes) {
3598: if ($section) { $role .= ':'.$section; }
3599: if ($returnhash{$role}) {
3600: $returnhash{$role}.=','.$username.':'.$domain;
3601: } else {
3602: $returnhash{$role}=$username.':'.$domain;
3603: }
3604: } else {
3605: my $key=&plaintext($role,$crstype);
3606: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
3607: if ($returnhash{$key}) {
3608: $returnhash{$key}.=','.$username.':'.$domain;
3609: } else {
3610: $returnhash{$key}=$username.':'.$domain;
3611: }
3612: }
3613: }
3614: return %returnhash;
3615: }
3616:
3617: sub get_my_roles {
3618: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
3619: unless (defined($uname)) { $uname=$env{'user.name'}; }
3620: unless (defined($udom)) { $udom=$env{'user.domain'}; }
3621: my (%dumphash,%nothide);
3622: if ($context eq 'userroles') {
3623: %dumphash = &dump('roles',$udom,$uname);
3624: } else {
3625: %dumphash=
3626: &dump('nohist_userroles',$udom,$uname);
3627: if ($hidepriv) {
3628: my %coursehash=&coursedescription($udom.'_'.$uname);
3629: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3630: if ($user !~ /:/) {
3631: $nothide{join(':',split(/[\@]/,$user))} = 1;
3632: } else {
3633: $nothide{$user} = 1;
3634: }
3635: }
3636: }
3637: }
3638: my %returnhash=();
3639: my $now=time;
3640: my %privileged;
3641: foreach my $entry (keys(%dumphash)) {
3642: my ($role,$tend,$tstart);
3643: if ($context eq 'userroles') {
3644: next if ($entry =~ /^rolesdef/);
3645: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3646: } else {
3647: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3648: }
3649: if (($tstart) && ($tstart<0)) { next; }
3650: my $status = 'active';
3651: if (($tend) && ($tend<=$now)) {
3652: $status = 'previous';
3653: }
3654: if (($tstart) && ($now<$tstart)) {
3655: $status = 'future';
3656: }
3657: if (ref($types) eq 'ARRAY') {
3658: if (!grep(/^\Q$status\E$/,@{$types})) {
3659: next;
3660: }
3661: } else {
3662: if ($status ne 'active') {
3663: next;
3664: }
3665: }
3666: my ($rolecode,$username,$domain,$section,$area);
3667: if ($context eq 'userroles') {
3668: ($area,$rolecode) = split(/_/,$entry);
3669: (undef,$domain,$username,$section) = split(/\//,$area);
3670: } else {
3671: ($role,$username,$domain,$section) = split(/\:/,$entry);
3672: }
3673: if (ref($roledoms) eq 'ARRAY') {
3674: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3675: next;
3676: }
3677: }
3678: if (ref($roles) eq 'ARRAY') {
3679: if (!grep(/^\Q$role\E$/,@{$roles})) {
3680: if ($role =~ /^cr\//) {
3681: if (!grep(/^cr$/,@{$roles})) {
3682: next;
3683: }
3684: } elsif ($role =~ /^gr\//) {
3685: if (!grep(/^gr$/,@{$roles})) {
3686: next;
3687: }
3688: } else {
3689: next;
3690: }
3691: }
3692: }
3693: if ($hidepriv) {
3694: if ($context eq 'userroles') {
3695: if ((&privileged($username,$domain)) &&
3696: (!$nothide{$username.':'.$domain})) {
3697: next;
3698: }
3699: } else {
3700: unless (ref($privileged{$domain}) eq 'HASH') {
3701: my %dompersonnel =
3702: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3703: $privileged{$domain} = {};
3704: if (keys(%dompersonnel)) {
3705: foreach my $server (keys(%dompersonnel)) {
3706: if (ref($dompersonnel{$server}) eq 'HASH') {
3707: foreach my $user (keys(%{$dompersonnel{$server}})) {
3708: my ($trole,$uname,$udom) = split(/:/,$user);
3709: $privileged{$udom}{$uname} = $trole;
3710: }
3711: }
3712: }
3713: }
3714: }
3715: if (exists($privileged{$domain}{$username})) {
3716: if (!$nothide{$username.':'.$domain}) {
3717: next;
3718: }
3719: }
3720: }
3721: }
3722: if ($withsec) {
3723: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3724: $tstart.':'.$tend;
3725: } else {
3726: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3727: }
3728: }
3729: return %returnhash;
3730: }
3731:
3732: # ----------------------------------------------------- Frontpage Announcements
3733: #
3734: #
3735:
3736: sub postannounce {
3737: my ($server,$text)=@_;
3738: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3739: unless ($text=~/\w/) { $text=''; }
3740: return &reply('setannounce:'.&escape($text),$server);
3741: }
3742:
3743: sub getannounce {
3744:
3745: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3746: my $announcement='';
3747: while (my $line = <$fh>) { $announcement .= $line; }
3748: close($fh);
3749: if ($announcement=~/\w/) {
3750: return
3751: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3752: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3753: } else {
3754: return '';
3755: }
3756: } else {
3757: return '';
3758: }
3759: }
3760:
3761: # ---------------------------------------------------------- Course ID routines
3762: # Deal with domain's nohist_courseid.db files
3763: #
3764:
3765: sub courseidput {
3766: my ($domain,$storehash,$coursehome,$caller) = @_;
3767: return unless (ref($storehash) eq 'HASH');
3768: my $outcome;
3769: if ($caller eq 'timeonly') {
3770: my $cids = '';
3771: foreach my $item (keys(%$storehash)) {
3772: $cids.=&escape($item).'&';
3773: }
3774: $cids=~s/\&$//;
3775: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3776: $coursehome);
3777: } else {
3778: my $items = '';
3779: foreach my $item (keys(%$storehash)) {
3780: $items.= &escape($item).'='.
3781: &freeze_escape($$storehash{$item}).'&';
3782: }
3783: $items=~s/\&$//;
3784: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3785: $coursehome);
3786: }
3787: if ($outcome eq 'unknown_cmd') {
3788: my $what;
3789: foreach my $cid (keys(%$storehash)) {
3790: $what .= &escape($cid).'=';
3791: foreach my $item ('description','inst_code','owner','type') {
3792: $what .= &escape($storehash->{$cid}{$item}).':';
3793: }
3794: $what =~ s/\:$/&/;
3795: }
3796: $what =~ s/\&$//;
3797: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3798: } else {
3799: return $outcome;
3800: }
3801: }
3802:
3803: sub courseiddump {
3804: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3805: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3806: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3807: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
3808: my $as_hash = 1;
3809: my %returnhash;
3810: if (!$domfilter) { $domfilter=''; }
3811: my %libserv = &all_library();
3812: foreach my $tryserver (keys(%libserv)) {
3813: if ( ( $hostidflag == 1
3814: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3815: || (!defined($hostidflag)) ) {
3816:
3817: if (($domfilter eq '') ||
3818: (&host_domain($tryserver) eq $domfilter)) {
3819: my $rep =
3820: &reply('courseiddump:'.&host_domain($tryserver).':'.
3821: $sincefilter.':'.&escape($descfilter).':'.
3822: &escape($instcodefilter).':'.&escape($ownerfilter).
3823: ':'.&escape($coursefilter).':'.&escape($typefilter).
3824: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3825: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3826: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3827: &escape($cc_clone).':'.$cloneonly.':'.
3828: &escape($createdbefore).':'.&escape($createdafter).':'.
3829: &escape($creationcontext).':'.$domcloner,
3830: $tryserver);
3831: my @pairs=split(/\&/,$rep);
3832: foreach my $item (@pairs) {
3833: my ($key,$value)=split(/\=/,$item,2);
3834: $key = &unescape($key);
3835: next if ($key =~ /^error: 2 /);
3836: my $result = &thaw_unescape($value);
3837: if (ref($result) eq 'HASH') {
3838: $returnhash{$key}=$result;
3839: } else {
3840: my @responses = split(/:/,$value);
3841: my @items = ('description','inst_code','owner','type');
3842: for (my $i=0; $i<@responses; $i++) {
3843: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3844: }
3845: }
3846: }
3847: }
3848: }
3849: }
3850: return %returnhash;
3851: }
3852:
3853: sub courselastaccess {
3854: my ($cdom,$cnum,$hostidref) = @_;
3855: my %returnhash;
3856: if ($cdom && $cnum) {
3857: my $chome = &homeserver($cnum,$cdom);
3858: if ($chome ne 'no_host') {
3859: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3860: &extract_lastaccess(\%returnhash,$rep);
3861: }
3862: } else {
3863: if (!$cdom) { $cdom=''; }
3864: my %libserv = &all_library();
3865: foreach my $tryserver (keys(%libserv)) {
3866: if (ref($hostidref) eq 'ARRAY') {
3867: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3868: }
3869: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3870: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3871: &extract_lastaccess(\%returnhash,$rep);
3872: }
3873: }
3874: }
3875: return %returnhash;
3876: }
3877:
3878: sub extract_lastaccess {
3879: my ($returnhash,$rep) = @_;
3880: if (ref($returnhash) eq 'HASH') {
3881: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3882: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3883: $rep eq '') {
3884: my @pairs=split(/\&/,$rep);
3885: foreach my $item (@pairs) {
3886: my ($key,$value)=split(/\=/,$item,2);
3887: $key = &unescape($key);
3888: next if ($key =~ /^error: 2 /);
3889: $returnhash->{$key} = &thaw_unescape($value);
3890: }
3891: }
3892: }
3893: return;
3894: }
3895:
3896: # ---------------------------------------------------------- DC e-mail
3897:
3898: sub dcmailput {
3899: my ($domain,$msgid,$message,$server)=@_;
3900: my $status = &Apache::lonnet::critical(
3901: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3902: &escape($message),$server);
3903: return $status;
3904: }
3905:
3906: sub dcmaildump {
3907: my ($dom,$startdate,$enddate,$senders) = @_;
3908: my %returnhash=();
3909:
3910: if (defined(&domain($dom,'primary'))) {
3911: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3912: &escape($enddate).':';
3913: my @esc_senders=map { &escape($_)} @$senders;
3914: $cmd.=&escape(join('&',@esc_senders));
3915: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3916: my ($key,$value) = split(/\=/,$line,2);
3917: if (($key) && ($value)) {
3918: $returnhash{&unescape($key)} = &unescape($value);
3919: }
3920: }
3921: }
3922: return %returnhash;
3923: }
3924: # ---------------------------------------------------------- Domain roles
3925:
3926: sub get_domain_roles {
3927: my ($dom,$roles,$startdate,$enddate)=@_;
3928: if ((!defined($startdate)) || ($startdate eq '')) {
3929: $startdate = '.';
3930: }
3931: if ((!defined($enddate)) || ($enddate eq '')) {
3932: $enddate = '.';
3933: }
3934: my $rolelist;
3935: if (ref($roles) eq 'ARRAY') {
3936: $rolelist = join(':',@{$roles});
3937: }
3938: my %personnel = ();
3939:
3940: my %servers = &get_servers($dom,'library');
3941: foreach my $tryserver (keys(%servers)) {
3942: %{$personnel{$tryserver}}=();
3943: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3944: &escape($startdate).':'.
3945: &escape($enddate).':'.
3946: &escape($rolelist), $tryserver))) {
3947: my ($key,$value) = split(/\=/,$line,2);
3948: if (($key) && ($value)) {
3949: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3950: }
3951: }
3952: }
3953: return %personnel;
3954: }
3955:
3956: # ----------------------------------------------------------- Interval timing
3957:
3958: {
3959: # Caches needed for speedup of navmaps
3960: # We don't want to cache this for very long at all (5 seconds at most)
3961: #
3962: # The user for whom we cache
3963: my $cachedkey='';
3964: # The cached times for this user
3965: my %cachedtimes=();
3966: # When this was last done
3967: my $cachedtime=();
3968:
3969: sub load_all_first_access {
3970: my ($uname,$udom)=@_;
3971: if (($cachedkey eq $uname.':'.$udom) &&
3972: (abs($cachedtime-time)<5)) {
3973: return;
3974: }
3975: $cachedtime=time;
3976: $cachedkey=$uname.':'.$udom;
3977: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
3978: }
3979:
3980: sub get_first_access {
3981: my ($type,$argsymb,$argmap)=@_;
3982: my ($symb,$courseid,$udom,$uname)=&whichuser();
3983: if ($argsymb) { $symb=$argsymb; }
3984: my ($map,$id,$res)=&decode_symb($symb);
3985: if ($argmap) { $map = $argmap; }
3986: if ($type eq 'course') {
3987: $res='course';
3988: } elsif ($type eq 'map') {
3989: $res=&symbread($map);
3990: } else {
3991: $res=$symb;
3992: }
3993: &load_all_first_access($uname,$udom);
3994: return $cachedtimes{"$courseid\0$res"};
3995: }
3996:
3997: sub set_first_access {
3998: my ($type,$interval)=@_;
3999: my ($symb,$courseid,$udom,$uname)=&whichuser();
4000: my ($map,$id,$res)=&decode_symb($symb);
4001: if ($type eq 'course') {
4002: $res='course';
4003: } elsif ($type eq 'map') {
4004: $res=&symbread($map);
4005: } else {
4006: $res=$symb;
4007: }
4008: $cachedkey='';
4009: my $firstaccess=&get_first_access($type,$symb,$map);
4010: if (!$firstaccess) {
4011: my $start = time;
4012: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4013: $udom,$uname);
4014: if ($putres eq 'ok') {
4015: &put('timerinterval',{"$courseid\0$res"=>$interval},
4016: $udom,$uname);
4017: &appenv(
4018: {
4019: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4020: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4021: }
4022: );
4023: }
4024: return $putres;
4025: }
4026: return 'already_set';
4027: }
4028: }
4029: # --------------------------------------------- Set Expire Date for Spreadsheet
4030:
4031: sub expirespread {
4032: my ($uname,$udom,$stype,$usymb)=@_;
4033: my $cid=$env{'request.course.id'};
4034: if ($cid) {
4035: my $now=time;
4036: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
4037: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4038: $env{'course.'.$cid.'.num'}.
4039: ':nohist_expirationdates:'.
4040: &escape($key).'='.$now,
4041: $env{'course.'.$cid.'.home'})
4042: }
4043: return 'ok';
4044: }
4045:
4046: # ----------------------------------------------------- Devalidate Spreadsheets
4047:
4048: sub devalidate {
4049: my ($symb,$uname,$udom)=@_;
4050: my $cid=$env{'request.course.id'};
4051: if ($cid) {
4052: # delete the stored spreadsheets for
4053: # - the student level sheet of this user in course's homespace
4054: # - the assessment level sheet for this resource
4055: # for this user in user's homespace
4056: # - current conditional state info
4057: my $key=$uname.':'.$udom.':';
4058: my $status=
4059: &del('nohist_calculatedsheets',
4060: [$key.'studentcalc:'],
4061: $env{'course.'.$cid.'.domain'},
4062: $env{'course.'.$cid.'.num'})
4063: .' '.
4064: &del('nohist_calculatedsheets_'.$cid,
4065: [$key.'assesscalc:'.$symb],$udom,$uname);
4066: unless ($status eq 'ok ok') {
4067: &logthis('Could not devalidate spreadsheet '.
4068: $uname.' at '.$udom.' for '.
4069: $symb.': '.$status);
4070: }
4071: &delenv('user.state.'.$cid);
4072: }
4073: }
4074:
4075: sub get_scalar {
4076: my ($string,$end) = @_;
4077: my $value;
4078: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4079: $value = $1;
4080: } elsif ($$string =~ s/^([^&]*?)&//) {
4081: $value = $1;
4082: }
4083: return &unescape($value);
4084: }
4085:
4086: sub array2str {
4087: my (@array) = @_;
4088: my $result=&arrayref2str(\@array);
4089: $result=~s/^__ARRAY_REF__//;
4090: $result=~s/__END_ARRAY_REF__$//;
4091: return $result;
4092: }
4093:
4094: sub arrayref2str {
4095: my ($arrayref) = @_;
4096: my $result='__ARRAY_REF__';
4097: foreach my $elem (@$arrayref) {
4098: if(ref($elem) eq 'ARRAY') {
4099: $result.=&arrayref2str($elem).'&';
4100: } elsif(ref($elem) eq 'HASH') {
4101: $result.=&hashref2str($elem).'&';
4102: } elsif(ref($elem)) {
4103: #print("Got a ref of ".(ref($elem))." skipping.");
4104: } else {
4105: $result.=&escape($elem).'&';
4106: }
4107: }
4108: $result=~s/\&$//;
4109: $result .= '__END_ARRAY_REF__';
4110: return $result;
4111: }
4112:
4113: sub hash2str {
4114: my (%hash) = @_;
4115: my $result=&hashref2str(\%hash);
4116: $result=~s/^__HASH_REF__//;
4117: $result=~s/__END_HASH_REF__$//;
4118: return $result;
4119: }
4120:
4121: sub hashref2str {
4122: my ($hashref)=@_;
4123: my $result='__HASH_REF__';
4124: foreach my $key (sort(keys(%$hashref))) {
4125: if (ref($key) eq 'ARRAY') {
4126: $result.=&arrayref2str($key).'=';
4127: } elsif (ref($key) eq 'HASH') {
4128: $result.=&hashref2str($key).'=';
4129: } elsif (ref($key)) {
4130: $result.='=';
4131: #print("Got a ref of ".(ref($key))." skipping.");
4132: } else {
4133: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
4134: }
4135:
4136: if(ref($hashref->{$key}) eq 'ARRAY') {
4137: $result.=&arrayref2str($hashref->{$key}).'&';
4138: } elsif(ref($hashref->{$key}) eq 'HASH') {
4139: $result.=&hashref2str($hashref->{$key}).'&';
4140: } elsif(ref($hashref->{$key})) {
4141: $result.='&';
4142: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
4143: } else {
4144: $result.=&escape($hashref->{$key}).'&';
4145: }
4146: }
4147: $result=~s/\&$//;
4148: $result .= '__END_HASH_REF__';
4149: return $result;
4150: }
4151:
4152: sub str2hash {
4153: my ($string)=@_;
4154: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4155: return %$hash;
4156: }
4157:
4158: sub str2hashref {
4159: my ($string) = @_;
4160:
4161: my %hash;
4162:
4163: if($string !~ /^__HASH_REF__/) {
4164: if (! ($string eq '' || !defined($string))) {
4165: $hash{'error'}='Not hash reference';
4166: }
4167: return (\%hash, $string);
4168: }
4169:
4170: $string =~ s/^__HASH_REF__//;
4171:
4172: while($string !~ /^__END_HASH_REF__/) {
4173: #key
4174: my $key='';
4175: if($string =~ /^__HASH_REF__/) {
4176: ($key, $string)=&str2hashref($string);
4177: if(defined($key->{'error'})) {
4178: $hash{'error'}='Bad data';
4179: return (\%hash, $string);
4180: }
4181: } elsif($string =~ /^__ARRAY_REF__/) {
4182: ($key, $string)=&str2arrayref($string);
4183: if($key->[0] eq 'Array reference error') {
4184: $hash{'error'}='Bad data';
4185: return (\%hash, $string);
4186: }
4187: } else {
4188: $string =~ s/^(.*?)=//;
4189: $key=&unescape($1);
4190: }
4191: $string =~ s/^=//;
4192:
4193: #value
4194: my $value='';
4195: if($string =~ /^__HASH_REF__/) {
4196: ($value, $string)=&str2hashref($string);
4197: if(defined($value->{'error'})) {
4198: $hash{'error'}='Bad data';
4199: return (\%hash, $string);
4200: }
4201: } elsif($string =~ /^__ARRAY_REF__/) {
4202: ($value, $string)=&str2arrayref($string);
4203: if($value->[0] eq 'Array reference error') {
4204: $hash{'error'}='Bad data';
4205: return (\%hash, $string);
4206: }
4207: } else {
4208: $value=&get_scalar(\$string,'__END_HASH_REF__');
4209: }
4210: $string =~ s/^&//;
4211:
4212: $hash{$key}=$value;
4213: }
4214:
4215: $string =~ s/^__END_HASH_REF__//;
4216:
4217: return (\%hash, $string);
4218: }
4219:
4220: sub str2array {
4221: my ($string)=@_;
4222: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4223: return @$array;
4224: }
4225:
4226: sub str2arrayref {
4227: my ($string) = @_;
4228: my @array;
4229:
4230: if($string !~ /^__ARRAY_REF__/) {
4231: if (! ($string eq '' || !defined($string))) {
4232: $array[0]='Array reference error';
4233: }
4234: return (\@array, $string);
4235: }
4236:
4237: $string =~ s/^__ARRAY_REF__//;
4238:
4239: while($string !~ /^__END_ARRAY_REF__/) {
4240: my $value='';
4241: if($string =~ /^__HASH_REF__/) {
4242: ($value, $string)=&str2hashref($string);
4243: if(defined($value->{'error'})) {
4244: $array[0] ='Array reference error';
4245: return (\@array, $string);
4246: }
4247: } elsif($string =~ /^__ARRAY_REF__/) {
4248: ($value, $string)=&str2arrayref($string);
4249: if($value->[0] eq 'Array reference error') {
4250: $array[0] ='Array reference error';
4251: return (\@array, $string);
4252: }
4253: } else {
4254: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4255: }
4256: $string =~ s/^&//;
4257:
4258: push(@array, $value);
4259: }
4260:
4261: $string =~ s/^__END_ARRAY_REF__//;
4262:
4263: return (\@array, $string);
4264: }
4265:
4266: # -------------------------------------------------------------------Temp Store
4267:
4268: sub tmpreset {
4269: my ($symb,$namespace,$domain,$stuname) = @_;
4270: if (!$symb) {
4271: $symb=&symbread();
4272: if (!$symb) { $symb= $env{'request.url'}; }
4273: }
4274: $symb=escape($symb);
4275:
4276: if (!$namespace) { $namespace=$env{'request.state'}; }
4277: $namespace=~s/\//\_/g;
4278: $namespace=~s/\W//g;
4279:
4280: if (!$domain) { $domain=$env{'user.domain'}; }
4281: if (!$stuname) { $stuname=$env{'user.name'}; }
4282: if ($domain eq 'public' && $stuname eq 'public') {
4283: $stuname=$ENV{'REMOTE_ADDR'};
4284: }
4285: my $path=LONCAPA::tempdir();
4286: my %hash;
4287: if (tie(%hash,'GDBM_File',
4288: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4289: &GDBM_WRCREAT(),0640)) {
4290: foreach my $key (keys(%hash)) {
4291: if ($key=~ /:$symb/) {
4292: delete($hash{$key});
4293: }
4294: }
4295: }
4296: }
4297:
4298: sub tmpstore {
4299: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4300:
4301: if (!$symb) {
4302: $symb=&symbread();
4303: if (!$symb) { $symb= $env{'request.url'}; }
4304: }
4305: $symb=escape($symb);
4306:
4307: if (!$namespace) {
4308: # I don't think we would ever want to store this for a course.
4309: # it seems this will only be used if we don't have a course.
4310: #$namespace=$env{'request.course.id'};
4311: #if (!$namespace) {
4312: $namespace=$env{'request.state'};
4313: #}
4314: }
4315: $namespace=~s/\//\_/g;
4316: $namespace=~s/\W//g;
4317: if (!$domain) { $domain=$env{'user.domain'}; }
4318: if (!$stuname) { $stuname=$env{'user.name'}; }
4319: if ($domain eq 'public' && $stuname eq 'public') {
4320: $stuname=$ENV{'REMOTE_ADDR'};
4321: }
4322: my $now=time;
4323: my %hash;
4324: my $path=LONCAPA::tempdir();
4325: if (tie(%hash,'GDBM_File',
4326: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4327: &GDBM_WRCREAT(),0640)) {
4328: $hash{"version:$symb"}++;
4329: my $version=$hash{"version:$symb"};
4330: my $allkeys='';
4331: foreach my $key (keys(%$storehash)) {
4332: $allkeys.=$key.':';
4333: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
4334: }
4335: $hash{"$version:$symb:timestamp"}=$now;
4336: $allkeys.='timestamp';
4337: $hash{"$version:keys:$symb"}=$allkeys;
4338: if (untie(%hash)) {
4339: return 'ok';
4340: } else {
4341: return "error:$!";
4342: }
4343: } else {
4344: return "error:$!";
4345: }
4346: }
4347:
4348: # -----------------------------------------------------------------Temp Restore
4349:
4350: sub tmprestore {
4351: my ($symb,$namespace,$domain,$stuname) = @_;
4352:
4353: if (!$symb) {
4354: $symb=&symbread();
4355: if (!$symb) { $symb= $env{'request.url'}; }
4356: }
4357: $symb=escape($symb);
4358:
4359: if (!$namespace) { $namespace=$env{'request.state'}; }
4360:
4361: if (!$domain) { $domain=$env{'user.domain'}; }
4362: if (!$stuname) { $stuname=$env{'user.name'}; }
4363: if ($domain eq 'public' && $stuname eq 'public') {
4364: $stuname=$ENV{'REMOTE_ADDR'};
4365: }
4366: my %returnhash;
4367: $namespace=~s/\//\_/g;
4368: $namespace=~s/\W//g;
4369: my %hash;
4370: my $path=LONCAPA::tempdir();
4371: if (tie(%hash,'GDBM_File',
4372: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
4373: &GDBM_READER(),0640)) {
4374: my $version=$hash{"version:$symb"};
4375: $returnhash{'version'}=$version;
4376: my $scope;
4377: for ($scope=1;$scope<=$version;$scope++) {
4378: my $vkeys=$hash{"$scope:keys:$symb"};
4379: my @keys=split(/:/,$vkeys);
4380: my $key;
4381: $returnhash{"$scope:keys"}=$vkeys;
4382: foreach $key (@keys) {
4383: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4384: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4385: }
4386: }
4387: if (!(untie(%hash))) {
4388: return "error:$!";
4389: }
4390: } else {
4391: return "error:$!";
4392: }
4393: return %returnhash;
4394: }
4395:
4396: # ----------------------------------------------------------------------- Store
4397:
4398: sub store {
4399: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4400: my $home='';
4401:
4402: if ($stuname) { $home=&homeserver($stuname,$domain); }
4403:
4404: $symb=&symbclean($symb);
4405: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4406:
4407: if (!$domain) { $domain=$env{'user.domain'}; }
4408: if (!$stuname) { $stuname=$env{'user.name'}; }
4409:
4410: &devalidate($symb,$stuname,$domain);
4411:
4412: $symb=escape($symb);
4413: if (!$namespace) {
4414: unless ($namespace=$env{'request.course.id'}) {
4415: return '';
4416: }
4417: }
4418: if (!$home) { $home=$env{'user.home'}; }
4419:
4420: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4421: $$storehash{'host'}=$perlvar{'lonHostID'};
4422:
4423: my $namevalue='';
4424: foreach my $key (keys(%$storehash)) {
4425: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4426: }
4427: $namevalue=~s/\&$//;
4428: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
4429: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4430: }
4431:
4432: # -------------------------------------------------------------- Critical Store
4433:
4434: sub cstore {
4435: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4436: my $home='';
4437:
4438: if ($stuname) { $home=&homeserver($stuname,$domain); }
4439:
4440: $symb=&symbclean($symb);
4441: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
4442:
4443: if (!$domain) { $domain=$env{'user.domain'}; }
4444: if (!$stuname) { $stuname=$env{'user.name'}; }
4445:
4446: &devalidate($symb,$stuname,$domain);
4447:
4448: $symb=escape($symb);
4449: if (!$namespace) {
4450: unless ($namespace=$env{'request.course.id'}) {
4451: return '';
4452: }
4453: }
4454: if (!$home) { $home=$env{'user.home'}; }
4455:
4456: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4457: $$storehash{'host'}=$perlvar{'lonHostID'};
4458:
4459: my $namevalue='';
4460: foreach my $key (keys(%$storehash)) {
4461: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4462: }
4463: $namevalue=~s/\&$//;
4464: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
4465: return critical
4466: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
4467: }
4468:
4469: # --------------------------------------------------------------------- Restore
4470:
4471: sub restore {
4472: my ($symb,$namespace,$domain,$stuname) = @_;
4473: my $home='';
4474:
4475: if ($stuname) { $home=&homeserver($stuname,$domain); }
4476:
4477: if (!$symb) {
4478: unless ($symb=escape(&symbread())) { return ''; }
4479: } else {
4480: $symb=&escape(&symbclean($symb));
4481: }
4482: if (!$namespace) {
4483: unless ($namespace=$env{'request.course.id'}) {
4484: return '';
4485: }
4486: }
4487: if (!$domain) { $domain=$env{'user.domain'}; }
4488: if (!$stuname) { $stuname=$env{'user.name'}; }
4489: if (!$home) { $home=$env{'user.home'}; }
4490: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4491:
4492: my %returnhash=();
4493: foreach my $line (split(/\&/,$answer)) {
4494: my ($name,$value)=split(/\=/,$line);
4495: $returnhash{&unescape($name)}=&thaw_unescape($value);
4496: }
4497: my $version;
4498: for ($version=1;$version<=$returnhash{'version'};$version++) {
4499: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4500: $returnhash{$item}=$returnhash{$version.':'.$item};
4501: }
4502: }
4503: return %returnhash;
4504: }
4505:
4506: # ---------------------------------------------------------- Course Description
4507: #
4508: #
4509:
4510: sub coursedescription {
4511: my ($courseid,$args)=@_;
4512: $courseid=~s/^\///;
4513: $courseid=~s/\_/\//g;
4514: my ($cdomain,$cnum)=split(/\//,$courseid);
4515: my $chome=&homeserver($cnum,$cdomain);
4516: my $normalid=$cdomain.'_'.$cnum;
4517: # need to always cache even if we get errors otherwise we keep
4518: # trying and trying and trying to get the course description.
4519: my %envhash=();
4520: my %returnhash=();
4521:
4522: my $expiretime=600;
4523: if ($env{'request.course.id'} eq $normalid) {
4524: $expiretime=120;
4525: }
4526:
4527: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4528: if (!$args->{'freshen_cache'}
4529: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4530: foreach my $key (keys(%env)) {
4531: next if ($key !~ /^\Q$prefix\E(.*)/);
4532: my ($setting) = $1;
4533: $returnhash{$setting} = $env{$key};
4534: }
4535: return %returnhash;
4536: }
4537:
4538: # get the data again
4539:
4540: if (!$args->{'one_time'}) {
4541: $envhash{'course.'.$normalid.'.last_cache'}=time;
4542: }
4543:
4544: if ($chome ne 'no_host') {
4545: %returnhash=&dump('environment',$cdomain,$cnum);
4546: if (!exists($returnhash{'con_lost'})) {
4547: my $username = $env{'user.name'}; # Defult username
4548: if(defined $args->{'user'}) {
4549: $username = $args->{'user'};
4550: }
4551: $returnhash{'home'}= $chome;
4552: $returnhash{'domain'} = $cdomain;
4553: $returnhash{'num'} = $cnum;
4554: if (!defined($returnhash{'type'})) {
4555: $returnhash{'type'} = 'Course';
4556: }
4557: while (my ($name,$value) = each %returnhash) {
4558: $envhash{'course.'.$normalid.'.'.$name}=$value;
4559: }
4560: $returnhash{'url'}=&clutter($returnhash{'url'});
4561: $returnhash{'fn'}=LONCAPA::tempdir() .
4562: $username.'_'.$cdomain.'_'.$cnum;
4563: $envhash{'course.'.$normalid.'.home'}=$chome;
4564: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4565: $envhash{'course.'.$normalid.'.num'}=$cnum;
4566: }
4567: }
4568: if (!$args->{'one_time'}) {
4569: &appenv(\%envhash);
4570: }
4571: return %returnhash;
4572: }
4573:
4574: sub update_released_required {
4575: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4576: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4577: $cid = $env{'request.course.id'};
4578: $cdom = $env{'course.'.$cid.'.domain'};
4579: $cnum = $env{'course.'.$cid.'.num'};
4580: $chome = $env{'course.'.$cid.'.home'};
4581: }
4582: if ($needsrelease) {
4583: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4584: my $needsupdate;
4585: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4586: $needsupdate = 1;
4587: } else {
4588: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4589: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4590: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4591: $needsupdate = 1;
4592: }
4593: }
4594: if ($needsupdate) {
4595: my %needshash = (
4596: 'internal.releaserequired' => $needsrelease,
4597: );
4598: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4599: if ($putresult eq 'ok') {
4600: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4601: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4602: if (ref($crsinfo{$cid}) eq 'HASH') {
4603: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4604: &courseidput($cdom,\%crsinfo,$chome,'notime');
4605: }
4606: }
4607: }
4608: }
4609: return;
4610: }
4611:
4612: # -------------------------------------------------See if a user is privileged
4613:
4614: sub privileged {
4615: my ($username,$domain)=@_;
4616: my $rolesdump=&reply("dump:$domain:$username:roles",
4617: &homeserver($username,$domain));
4618: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4619: ($rolesdump =~ /^error:/)) {
4620: return 0;
4621: }
4622: my $now=time;
4623: if ($rolesdump ne '') {
4624: foreach my $entry (split(/&/,$rolesdump)) {
4625: if ($entry!~/^rolesdef_/) {
4626: my ($area,$role)=split(/=/,$entry);
4627: $area=~s/\_\w\w$//;
4628: my ($trole,$tend,$tstart)=split(/_/,$role);
4629: if (($trole eq 'dc') || ($trole eq 'su')) {
4630: my $active=1;
4631: if ($tend) {
4632: if ($tend<$now) { $active=0; }
4633: }
4634: if ($tstart) {
4635: if ($tstart>$now) { $active=0; }
4636: }
4637: if ($active) { return 1; }
4638: }
4639: }
4640: }
4641: }
4642: return 0;
4643: }
4644:
4645: # -------------------------------------------------------- Get user privileges
4646:
4647: sub rolesinit {
4648: my ($domain,$username,$authhost)=@_;
4649: my $now=time;
4650: my %userroles = ('user.login.time' => $now);
4651: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
4652: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4653: ($rolesdump =~ /^error:/)) {
4654: return \%userroles;
4655: }
4656: my %firstaccess = &dump('firstaccesstimes',$domain,$username);
4657: my %timerinterval = &dump('timerinterval',$domain,$username);
4658: my (%coursetimerstarts,%firstaccchk,%firstaccenv,
4659: %coursetimerintervals,%timerintchk,%timerintenv);
4660: foreach my $key (keys(%firstaccess)) {
4661: my ($cid,$rest) = split(/\0/,$key);
4662: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4663: }
4664: foreach my $key (keys(%timerinterval)) {
4665: my ($cid,$rest) = split(/\0/,$key);
4666: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4667: }
4668: my %allroles=();
4669: my %allgroups=();
4670:
4671: if ($rolesdump ne '') {
4672: foreach my $entry (split(/&/,$rolesdump)) {
4673: if ($entry!~/^rolesdef_/) {
4674: my ($area,$role)=split(/=/,$entry);
4675: $area=~s/\_\w\w$//;
4676: my ($trole,$tend,$tstart,$group_privs);
4677: if ($role=~/^cr/) {
4678: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4679: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
4680: ($tend,$tstart)=split('_',$trest);
4681: } else {
4682: $trole=$role;
4683: }
4684: } elsif ($role =~ m|^gr/|) {
4685: ($trole,$tend,$tstart) = split(/_/,$role);
4686: next if ($tstart eq '-1');
4687: ($trole,$group_privs) = split(/\//,$trole);
4688: $group_privs = &unescape($group_privs);
4689: } else {
4690: ($trole,$tend,$tstart)=split(/_/,$role);
4691: }
4692: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4693: $username);
4694: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4695: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4696: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
4697: if (($area ne '') && ($trole ne '')) {
4698: my $spec=$trole.'.'.$area;
4699: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4700: if ($trole =~ /^cr\//) {
4701: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4702: } elsif ($trole eq 'gr') {
4703: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4704: } else {
4705: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4706: }
4707: if ($trole ne 'gr') {
4708: my $cid = $tdomain.'_'.$trest;
4709: unless ($firstaccchk{$cid}) {
4710: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4711: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4712: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4713: $coursetimerstarts{$cid}{$item};
4714: }
4715: }
4716: $firstaccchk{$cid} = 1;
4717: }
4718: unless ($timerintchk{$cid}) {
4719: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4720: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4721: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4722: $coursetimerintervals{$cid}{$item};
4723: }
4724: }
4725: $timerintchk{$cid} = 1;
4726: }
4727: }
4728: }
4729: }
4730: }
4731: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4732: $userroles{'user.adv'} = $adv;
4733: $userroles{'user.author'} = $author;
4734: $env{'user.adv'}=$adv;
4735: }
4736: return (\%userroles,\%firstaccenv,\%timerintenv);
4737: }
4738:
4739: sub set_arearole {
4740: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4741: # log the associated role with the area
4742: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
4743: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
4744: }
4745:
4746: sub custom_roleprivs {
4747: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4748: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4749: my $homsvr=homeserver($rauthor,$rdomain);
4750: if (&hostname($homsvr) ne '') {
4751: my ($rdummy,$roledef)=
4752: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4753: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4754: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4755: if (defined($syspriv)) {
4756: if ($trest =~ /^$match_community$/) {
4757: $syspriv =~ s/bre\&S//;
4758: }
4759: $$allroles{'cm./'}.=':'.$syspriv;
4760: $$allroles{$spec.'./'}.=':'.$syspriv;
4761: }
4762: if ($tdomain ne '') {
4763: if (defined($dompriv)) {
4764: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4765: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4766: }
4767: if (($trest ne '') && (defined($coursepriv))) {
4768: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4769: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4770: }
4771: }
4772: }
4773: }
4774: }
4775:
4776: sub group_roleprivs {
4777: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4778: my $access = 1;
4779: my $now = time;
4780: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4781: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4782: if ($access) {
4783: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
4784: $$allgroups{$course}{$group} .=':'.$group_privs;
4785: }
4786: }
4787:
4788: sub standard_roleprivs {
4789: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4790: if (defined($pr{$trole.':s'})) {
4791: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4792: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4793: }
4794: if ($tdomain ne '') {
4795: if (defined($pr{$trole.':d'})) {
4796: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4797: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4798: }
4799: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4800: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4801: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4802: }
4803: }
4804: }
4805:
4806: sub set_userprivs {
4807: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
4808: my $author=0;
4809: my $adv=0;
4810: my %grouproles = ();
4811: if (keys(%{$allgroups}) > 0) {
4812: my @groupkeys;
4813: foreach my $role (keys(%{$allroles})) {
4814: push(@groupkeys,$role);
4815: }
4816: if (ref($groups_roles) eq 'HASH') {
4817: foreach my $key (keys(%{$groups_roles})) {
4818: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4819: push(@groupkeys,$key);
4820: }
4821: }
4822: }
4823: if (@groupkeys > 0) {
4824: foreach my $role (@groupkeys) {
4825: my ($trole,$area,$sec,$extendedarea);
4826: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4827: $trole = $1;
4828: $area = $2;
4829: $sec = $3;
4830: $extendedarea = $area.$sec;
4831: if (exists($$allgroups{$area})) {
4832: foreach my $group (keys(%{$$allgroups{$area}})) {
4833: my $spec = $trole.'.'.$extendedarea;
4834: $grouproles{$spec.'.'.$area.'/'.$group} =
4835: $$allgroups{$area}{$group};
4836: }
4837: }
4838: }
4839: }
4840: }
4841: }
4842: foreach my $group (keys(%grouproles)) {
4843: $$allroles{$group} = $grouproles{$group};
4844: }
4845: foreach my $role (keys(%{$allroles})) {
4846: my %thesepriv;
4847: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4848: foreach my $item (split(/:/,$$allroles{$role})) {
4849: if ($item ne '') {
4850: my ($privilege,$restrictions)=split(/&/,$item);
4851: if ($restrictions eq '') {
4852: $thesepriv{$privilege}='F';
4853: } elsif ($thesepriv{$privilege} ne 'F') {
4854: $thesepriv{$privilege}.=$restrictions;
4855: }
4856: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4857: }
4858: }
4859: my $thesestr='';
4860: foreach my $priv (sort(keys(%thesepriv))) {
4861: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4862: }
4863: $userroles->{'user.priv.'.$role} = $thesestr;
4864: }
4865: return ($author,$adv);
4866: }
4867:
4868: sub role_status {
4869: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4870: my @pwhere = ();
4871: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4872: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4873: unless (!defined($$role) || $$role eq '') {
4874: $$where=join('.',@pwhere);
4875: $$trolecode=$$role.'.'.$$where;
4876: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4877: $$tstatus='is';
4878: if ($$tstart && $$tstart>$update) {
4879: $$tstatus='future';
4880: if ($$tstart<$now) {
4881: if ($$tstart && $$tstart>$refresh) {
4882: if (($$where ne '') && ($$role ne '')) {
4883: my (%allroles,%allgroups,$group_privs,
4884: %groups_roles,@rolecodes);
4885: my %userroles = (
4886: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4887: );
4888: @rolecodes = ('cm');
4889: my $spec=$$role.'.'.$$where;
4890: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4891: if ($$role =~ /^cr\//) {
4892: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4893: push(@rolecodes,'cr');
4894: } elsif ($$role eq 'gr') {
4895: push(@rolecodes,$$role);
4896: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4897: $env{'user.name'});
4898: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
4899: (undef,my $group_privs) = split(/\//,$trole);
4900: $group_privs = &unescape($group_privs);
4901: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4902: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
4903: &get_groups_roles($tdomain,$trest,
4904: \%course_roles,\@rolecodes,
4905: \%groups_roles);
4906: } else {
4907: push(@rolecodes,$$role);
4908: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4909: }
4910: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4911: &appenv(\%userroles,\@rolecodes);
4912: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4913: }
4914: }
4915: $$tstatus = 'is';
4916: }
4917: }
4918: if ($$tend) {
4919: if ($$tend<$update) {
4920: $$tstatus='expired';
4921: } elsif ($$tend<$now) {
4922: $$tstatus='will_not';
4923: }
4924: }
4925: }
4926: }
4927: }
4928:
4929: sub get_groups_roles {
4930: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4931: return unless((ref($cdom_courseroles) eq 'HASH') &&
4932: (ref($rolecodes) eq 'ARRAY') &&
4933: (ref($groups_roles) eq 'HASH'));
4934: if (keys(%{$cdom_courseroles}) > 0) {
4935: my ($cnum) = ($rest =~ /^($match_courseid)/);
4936: if ($cdom ne '' && $cnum ne '') {
4937: foreach my $key (keys(%{$cdom_courseroles})) {
4938: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4939: my $crsrole = $1;
4940: my $crssec = $2;
4941: if ($crsrole =~ /^cr/) {
4942: unless (grep(/^cr$/,@{$rolecodes})) {
4943: push(@{$rolecodes},'cr');
4944: }
4945: } else {
4946: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4947: push(@{$rolecodes},$crsrole);
4948: }
4949: }
4950: my $rolekey = "$crsrole./$cdom/$cnum";
4951: if ($crssec ne '') {
4952: $rolekey .= "/$crssec";
4953: }
4954: $rolekey .= './';
4955: $groups_roles->{$rolekey} = $rolecodes;
4956: }
4957: }
4958: }
4959: }
4960: return;
4961: }
4962:
4963: sub delete_env_groupprivs {
4964: my ($where,$courseroles,$possroles) = @_;
4965: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4966: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4967: unless (ref($courseroles->{$udom}) eq 'HASH') {
4968: %{$courseroles->{$udom}} =
4969: &get_my_roles('','','userroles',['active'],
4970: $possroles,[$udom],1);
4971: }
4972: if (ref($courseroles->{$udom}) eq 'HASH') {
4973: foreach my $item (keys(%{$courseroles->{$udom}})) {
4974: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4975: my $area = '/'.$cdom.'/'.$cnum;
4976: my $privkey = "user.priv.$crsrole.$area";
4977: if ($crssec ne '') {
4978: $privkey .= '/'.$crssec;
4979: }
4980: $privkey .= ".$area/$group";
4981: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4982: }
4983: }
4984: return;
4985: }
4986:
4987: sub check_adhoc_privs {
4988: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
4989: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4990: if ($env{$cckey}) {
4991: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4992: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4993: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4994: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4995: }
4996: } else {
4997: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
4998: }
4999: }
5000:
5001: sub set_adhoc_privileges {
5002: # role can be cc or ca
5003: my ($dcdom,$pickedcourse,$role,$caller) = @_;
5004: my $area = '/'.$dcdom.'/'.$pickedcourse;
5005: my $spec = $role.'.'.$area;
5006: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5007: $env{'user.name'});
5008: my %ccrole = ();
5009: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5010: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5011: &appenv(\%userroles,[$role,'cm']);
5012: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
5013: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5014: &appenv( {'request.role' => $spec,
5015: 'request.role.domain' => $dcdom,
5016: 'request.course.sec' => ''
5017: }
5018: );
5019: my $tadv=0;
5020: if (&allowed('adv') eq 'F') { $tadv=1; }
5021: &appenv({'request.role.adv' => $tadv});
5022: }
5023: }
5024:
5025: # --------------------------------------------------------------- get interface
5026:
5027: sub get {
5028: my ($namespace,$storearr,$udomain,$uname)=@_;
5029: my $items='';
5030: foreach my $item (@$storearr) {
5031: $items.=&escape($item).'&';
5032: }
5033: $items=~s/\&$//;
5034: if (!$udomain) { $udomain=$env{'user.domain'}; }
5035: if (!$uname) { $uname=$env{'user.name'}; }
5036: my $uhome=&homeserver($uname,$udomain);
5037:
5038: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
5039: my @pairs=split(/\&/,$rep);
5040: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5041: return @pairs;
5042: }
5043: my %returnhash=();
5044: my $i=0;
5045: foreach my $item (@$storearr) {
5046: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5047: $i++;
5048: }
5049: return %returnhash;
5050: }
5051:
5052: # --------------------------------------------------------------- del interface
5053:
5054: sub del {
5055: my ($namespace,$storearr,$udomain,$uname)=@_;
5056: my $items='';
5057: foreach my $item (@$storearr) {
5058: $items.=&escape($item).'&';
5059: }
5060:
5061: $items=~s/\&$//;
5062: if (!$udomain) { $udomain=$env{'user.domain'}; }
5063: if (!$uname) { $uname=$env{'user.name'}; }
5064: my $uhome=&homeserver($uname,$udomain);
5065: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
5066: }
5067:
5068: # -------------------------------------------------------------- dump interface
5069:
5070: sub dump {
5071: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5072: if (!$udomain) { $udomain=$env{'user.domain'}; }
5073: if (!$uname) { $uname=$env{'user.name'}; }
5074: my $uhome=&homeserver($uname,$udomain);
5075:
5076: if ($regexp) {
5077: $regexp=&escape($regexp);
5078: } else {
5079: $regexp='.';
5080: }
5081: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5082: my @pairs=split(/\&/,$rep);
5083: my %returnhash=();
5084: if (!($rep =~ /^error/ )) {
5085: foreach my $item (@pairs) {
5086: my ($key,$value)=split(/=/,$item,2);
5087: $key = &unescape($key);
5088: next if ($key =~ /^error: 2 /);
5089: $returnhash{$key}=&thaw_unescape($value);
5090: }
5091: }
5092: return %returnhash;
5093: }
5094:
5095:
5096: # --------------------------------------------------------- dumpstore interface
5097:
5098: sub dumpstore {
5099: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
5100: if (!$udomain) { $udomain=$env{'user.domain'}; }
5101: if (!$uname) { $uname=$env{'user.name'}; }
5102: my $uhome=&homeserver($uname,$udomain);
5103: if ($regexp) {
5104: $regexp=&escape($regexp);
5105: } else {
5106: $regexp='.';
5107: }
5108: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
5109: my @pairs=split(/\&/,$rep);
5110: my %returnhash=();
5111: foreach my $item (@pairs) {
5112: my ($key,$value)=split(/=/,$item,2);
5113: next if ($key =~ /^error: 2 /);
5114: $returnhash{$key}=&thaw_unescape($value);
5115: }
5116: return %returnhash;
5117: }
5118:
5119: # -------------------------------------------------------------- keys interface
5120:
5121: sub getkeys {
5122: my ($namespace,$udomain,$uname)=@_;
5123: if (!$udomain) { $udomain=$env{'user.domain'}; }
5124: if (!$uname) { $uname=$env{'user.name'}; }
5125: my $uhome=&homeserver($uname,$udomain);
5126: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5127: my @keyarray=();
5128: foreach my $key (split(/\&/,$rep)) {
5129: next if ($key =~ /^error: 2 /);
5130: push(@keyarray,&unescape($key));
5131: }
5132: return @keyarray;
5133: }
5134:
5135: # --------------------------------------------------------------- currentdump
5136: sub currentdump {
5137: my ($courseid,$sdom,$sname)=@_;
5138: $courseid = $env{'request.course.id'} if (! defined($courseid));
5139: $sdom = $env{'user.domain'} if (! defined($sdom));
5140: $sname = $env{'user.name'} if (! defined($sname));
5141: my $uhome = &homeserver($sname,$sdom);
5142: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5143: return if ($rep =~ /^(error:|no_such_host)/);
5144: #
5145: my %returnhash=();
5146: #
5147: if ($rep eq "unknown_cmd") {
5148: # an old lond will not know currentdump
5149: # Do a dump and make it look like a currentdump
5150: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
5151: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5152: my %hash = @tmp;
5153: @tmp=();
5154: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
5155: } else {
5156: my @pairs=split(/\&/,$rep);
5157: foreach my $pair (@pairs) {
5158: my ($key,$value)=split(/=/,$pair,2);
5159: my ($symb,$param) = split(/:/,$key);
5160: $returnhash{&unescape($symb)}->{&unescape($param)} =
5161: &thaw_unescape($value);
5162: }
5163: }
5164: return %returnhash;
5165: }
5166:
5167: sub convert_dump_to_currentdump{
5168: my %hash = %{shift()};
5169: my %returnhash;
5170: # Code ripped from lond, essentially. The only difference
5171: # here is the unescaping done by lonnet::dump(). Conceivably
5172: # we might run in to problems with parameter names =~ /^v\./
5173: while (my ($key,$value) = each(%hash)) {
5174: my ($v,$symb,$param) = split(/:/,$key);
5175: $symb = &unescape($symb);
5176: $param = &unescape($param);
5177: next if ($v eq 'version' || $symb eq 'keys');
5178: next if (exists($returnhash{$symb}) &&
5179: exists($returnhash{$symb}->{$param}) &&
5180: $returnhash{$symb}->{'v.'.$param} > $v);
5181: $returnhash{$symb}->{$param}=$value;
5182: $returnhash{$symb}->{'v.'.$param}=$v;
5183: }
5184: #
5185: # Remove all of the keys in the hashes which keep track of
5186: # the version of the parameter.
5187: while (my ($symb,$param_hash) = each(%returnhash)) {
5188: # use a foreach because we are going to delete from the hash.
5189: foreach my $key (keys(%$param_hash)) {
5190: delete($param_hash->{$key}) if ($key =~ /^v\./);
5191: }
5192: }
5193: return \%returnhash;
5194: }
5195:
5196: # ------------------------------------------------------ critical inc interface
5197:
5198: sub cinc {
5199: return &inc(@_,'critical');
5200: }
5201:
5202: # --------------------------------------------------------------- inc interface
5203:
5204: sub inc {
5205: my ($namespace,$store,$udomain,$uname,$critical) = @_;
5206: if (!$udomain) { $udomain=$env{'user.domain'}; }
5207: if (!$uname) { $uname=$env{'user.name'}; }
5208: my $uhome=&homeserver($uname,$udomain);
5209: my $items='';
5210: if (! ref($store)) {
5211: # got a single value, so use that instead
5212: $items = &escape($store).'=&';
5213: } elsif (ref($store) eq 'SCALAR') {
5214: $items = &escape($$store).'=&';
5215: } elsif (ref($store) eq 'ARRAY') {
5216: $items = join('=&',map {&escape($_);} @{$store});
5217: } elsif (ref($store) eq 'HASH') {
5218: while (my($key,$value) = each(%{$store})) {
5219: $items.= &escape($key).'='.&escape($value).'&';
5220: }
5221: }
5222: $items=~s/\&$//;
5223: if ($critical) {
5224: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5225: } else {
5226: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5227: }
5228: }
5229:
5230: # --------------------------------------------------------------- put interface
5231:
5232: sub put {
5233: my ($namespace,$storehash,$udomain,$uname)=@_;
5234: if (!$udomain) { $udomain=$env{'user.domain'}; }
5235: if (!$uname) { $uname=$env{'user.name'}; }
5236: my $uhome=&homeserver($uname,$udomain);
5237: my $items='';
5238: foreach my $item (keys(%$storehash)) {
5239: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5240: }
5241: $items=~s/\&$//;
5242: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5243: }
5244:
5245: # ------------------------------------------------------------ newput interface
5246:
5247: sub newput {
5248: my ($namespace,$storehash,$udomain,$uname)=@_;
5249: if (!$udomain) { $udomain=$env{'user.domain'}; }
5250: if (!$uname) { $uname=$env{'user.name'}; }
5251: my $uhome=&homeserver($uname,$udomain);
5252: my $items='';
5253: foreach my $key (keys(%$storehash)) {
5254: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5255: }
5256: $items=~s/\&$//;
5257: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5258: }
5259:
5260: # --------------------------------------------------------- putstore interface
5261:
5262: sub putstore {
5263: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5264: if (!$udomain) { $udomain=$env{'user.domain'}; }
5265: if (!$uname) { $uname=$env{'user.name'}; }
5266: my $uhome=&homeserver($uname,$udomain);
5267: my $items='';
5268: foreach my $key (keys(%$storehash)) {
5269: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
5270: }
5271: $items=~s/\&$//;
5272: my $esc_symb=&escape($symb);
5273: my $esc_v=&escape($version);
5274: my $reply =
5275: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
5276: $uhome);
5277: if ($reply eq 'unknown_cmd') {
5278: # gfall back to way things use to be done
5279: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5280: $uname);
5281: }
5282: return $reply;
5283: }
5284:
5285: sub old_putstore {
5286: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5287: if (!$udomain) { $udomain=$env{'user.domain'}; }
5288: if (!$uname) { $uname=$env{'user.name'}; }
5289: my $uhome=&homeserver($uname,$udomain);
5290: my %newstorehash;
5291: foreach my $item (keys(%$storehash)) {
5292: my $key = $version.':'.&escape($symb).':'.$item;
5293: $newstorehash{$key} = $storehash->{$item};
5294: }
5295: my $items='';
5296: my %allitems = ();
5297: foreach my $item (keys(%newstorehash)) {
5298: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
5299: my $key = $1.':keys:'.$2;
5300: $allitems{$key} .= $3.':';
5301: }
5302: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
5303: }
5304: foreach my $item (keys(%allitems)) {
5305: $allitems{$item} =~ s/\:$//;
5306: $items.= $item.'='.$allitems{$item}.'&';
5307: }
5308: $items=~s/\&$//;
5309: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
5310: }
5311:
5312: # ------------------------------------------------------ critical put interface
5313:
5314: sub cput {
5315: my ($namespace,$storehash,$udomain,$uname)=@_;
5316: if (!$udomain) { $udomain=$env{'user.domain'}; }
5317: if (!$uname) { $uname=$env{'user.name'}; }
5318: my $uhome=&homeserver($uname,$udomain);
5319: my $items='';
5320: foreach my $item (keys(%$storehash)) {
5321: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5322: }
5323: $items=~s/\&$//;
5324: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
5325: }
5326:
5327: # -------------------------------------------------------------- eget interface
5328:
5329: sub eget {
5330: my ($namespace,$storearr,$udomain,$uname)=@_;
5331: my $items='';
5332: foreach my $item (@$storearr) {
5333: $items.=&escape($item).'&';
5334: }
5335: $items=~s/\&$//;
5336: if (!$udomain) { $udomain=$env{'user.domain'}; }
5337: if (!$uname) { $uname=$env{'user.name'}; }
5338: my $uhome=&homeserver($uname,$udomain);
5339: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
5340: my @pairs=split(/\&/,$rep);
5341: my %returnhash=();
5342: my $i=0;
5343: foreach my $item (@$storearr) {
5344: $returnhash{$item}=&thaw_unescape($pairs[$i]);
5345: $i++;
5346: }
5347: return %returnhash;
5348: }
5349:
5350: # ------------------------------------------------------------ tmpput interface
5351: sub tmpput {
5352: my ($storehash,$server,$context)=@_;
5353: my $items='';
5354: foreach my $item (keys(%$storehash)) {
5355: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
5356: }
5357: $items=~s/\&$//;
5358: if (defined($context)) {
5359: $items .= ':'.&escape($context);
5360: }
5361: return &reply("tmpput:$items",$server);
5362: }
5363:
5364: # ------------------------------------------------------------ tmpget interface
5365: sub tmpget {
5366: my ($token,$server)=@_;
5367: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5368: my $rep=&reply("tmpget:$token",$server);
5369: my %returnhash;
5370: foreach my $item (split(/\&/,$rep)) {
5371: my ($key,$value)=split(/=/,$item);
5372: next if ($key =~ /^error: 2 /);
5373: $returnhash{&unescape($key)}=&thaw_unescape($value);
5374: }
5375: return %returnhash;
5376: }
5377:
5378: # ------------------------------------------------------------ tmpdel interface
5379: sub tmpdel {
5380: my ($token,$server)=@_;
5381: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5382: return &reply("tmpdel:$token",$server);
5383: }
5384:
5385: # -------------------------------------------------- portfolio access checking
5386:
5387: sub portfolio_access {
5388: my ($requrl) = @_;
5389: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5390: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
5391: if ($result) {
5392: my %setters;
5393: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5394: my ($startblock,$endblock) =
5395: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5396: if ($startblock && $endblock) {
5397: return 'B';
5398: }
5399: } else {
5400: my ($startblock,$endblock) =
5401: &Apache::loncommon::blockcheck(\%setters,'port');
5402: if ($startblock && $endblock) {
5403: return 'B';
5404: }
5405: }
5406: }
5407: if ($result eq 'ok') {
5408: return 'F';
5409: } elsif ($result =~ /^[^:]+:guest_/) {
5410: return 'A';
5411: }
5412: return '';
5413: }
5414:
5415: sub get_portfolio_access {
5416: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5417:
5418: if (!ref($access_hash)) {
5419: my $current_perms = &get_portfile_permissions($udom,$unum);
5420: my %access_controls = &get_access_controls($current_perms,$group,
5421: $file_name);
5422: $access_hash = $access_controls{$file_name};
5423: }
5424:
5425: my ($public,$guest,@domains,@users,@courses,@groups);
5426: my $now = time;
5427: if (ref($access_hash) eq 'HASH') {
5428: foreach my $key (keys(%{$access_hash})) {
5429: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5430: if ($start > $now) {
5431: next;
5432: }
5433: if ($end && $end<$now) {
5434: next;
5435: }
5436: if ($scope eq 'public') {
5437: $public = $key;
5438: last;
5439: } elsif ($scope eq 'guest') {
5440: $guest = $key;
5441: } elsif ($scope eq 'domains') {
5442: push(@domains,$key);
5443: } elsif ($scope eq 'users') {
5444: push(@users,$key);
5445: } elsif ($scope eq 'course') {
5446: push(@courses,$key);
5447: } elsif ($scope eq 'group') {
5448: push(@groups,$key);
5449: }
5450: }
5451: if ($public) {
5452: return 'ok';
5453: }
5454: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5455: if ($guest) {
5456: return $guest;
5457: }
5458: } else {
5459: if (@domains > 0) {
5460: foreach my $domkey (@domains) {
5461: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5462: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5463: return 'ok';
5464: }
5465: }
5466: }
5467: }
5468: if (@users > 0) {
5469: foreach my $userkey (@users) {
5470: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5471: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5472: if (ref($item) eq 'HASH') {
5473: if (($item->{'uname'} eq $env{'user.name'}) &&
5474: ($item->{'udom'} eq $env{'user.domain'})) {
5475: return 'ok';
5476: }
5477: }
5478: }
5479: }
5480: }
5481: }
5482: my %roleshash;
5483: my @courses_and_groups = @courses;
5484: push(@courses_and_groups,@groups);
5485: if (@courses_and_groups > 0) {
5486: my (%allgroups,%allroles);
5487: my ($start,$end,$role,$sec,$group);
5488: foreach my $envkey (%env) {
5489: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
5490: my $cid = $2.'_'.$3;
5491: if ($1 eq 'gr') {
5492: $group = $4;
5493: $allgroups{$cid}{$group} = $env{$envkey};
5494: } else {
5495: if ($4 eq '') {
5496: $sec = 'none';
5497: } else {
5498: $sec = $4;
5499: }
5500: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5501: }
5502: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
5503: my $cid = $2.'_'.$3;
5504: if ($4 eq '') {
5505: $sec = 'none';
5506: } else {
5507: $sec = $4;
5508: }
5509: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5510: }
5511: }
5512: if (keys(%allroles) == 0) {
5513: return;
5514: }
5515: foreach my $key (@courses_and_groups) {
5516: my %content = %{$$access_hash{$key}};
5517: my $cnum = $content{'number'};
5518: my $cdom = $content{'domain'};
5519: my $cid = $cdom.'_'.$cnum;
5520: if (!exists($allroles{$cid})) {
5521: next;
5522: }
5523: foreach my $role_id (keys(%{$content{'roles'}})) {
5524: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5525: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5526: my @status = @{$content{'roles'}{$role_id}{'access'}};
5527: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5528: foreach my $role (keys(%{$allroles{$cid}})) {
5529: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5530: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5531: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5532: if (grep/^all$/,@sections) {
5533: return 'ok';
5534: } else {
5535: if (grep/^$sec$/,@sections) {
5536: return 'ok';
5537: }
5538: }
5539: }
5540: }
5541: if (keys(%{$allgroups{$cid}}) == 0) {
5542: if (grep/^none$/,@groups) {
5543: return 'ok';
5544: }
5545: } else {
5546: if (grep/^all$/,@groups) {
5547: return 'ok';
5548: }
5549: foreach my $group (keys(%{$allgroups{$cid}})) {
5550: if (grep/^$group$/,@groups) {
5551: return 'ok';
5552: }
5553: }
5554: }
5555: }
5556: }
5557: }
5558: }
5559: }
5560: if ($guest) {
5561: return $guest;
5562: }
5563: }
5564: }
5565: return;
5566: }
5567:
5568: sub course_group_datechecker {
5569: my ($dates,$now,$status) = @_;
5570: my ($start,$end) = split(/\./,$dates);
5571: if (!$start && !$end) {
5572: return 'ok';
5573: }
5574: if (grep/^active$/,@{$status}) {
5575: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5576: return 'ok';
5577: }
5578: }
5579: if (grep/^previous$/,@{$status}) {
5580: if ($end > $now ) {
5581: return 'ok';
5582: }
5583: }
5584: if (grep/^future$/,@{$status}) {
5585: if ($start > $now) {
5586: return 'ok';
5587: }
5588: }
5589: return;
5590: }
5591:
5592: sub parse_portfolio_url {
5593: my ($url) = @_;
5594:
5595: my ($type,$udom,$unum,$group,$file_name);
5596:
5597: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
5598: $type = 1;
5599: $udom = $1;
5600: $unum = $2;
5601: $file_name = $3;
5602: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
5603: $type = 2;
5604: $udom = $1;
5605: $unum = $2;
5606: $group = $3;
5607: $file_name = $3.'/'.$4;
5608: }
5609: if (wantarray) {
5610: return ($type,$udom,$unum,$file_name,$group);
5611: }
5612: return $type;
5613: }
5614:
5615: sub is_portfolio_url {
5616: my ($url) = @_;
5617: return scalar(&parse_portfolio_url($url));
5618: }
5619:
5620: sub is_portfolio_file {
5621: my ($file) = @_;
5622: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
5623: return 1;
5624: }
5625: return;
5626: }
5627:
5628: sub usertools_access {
5629: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
5630: my ($access,%tools);
5631: if ($context eq '') {
5632: $context = 'tools';
5633: }
5634: if ($context eq 'requestcourses') {
5635: %tools = (
5636: official => 1,
5637: unofficial => 1,
5638: community => 1,
5639: );
5640: } else {
5641: %tools = (
5642: aboutme => 1,
5643: blog => 1,
5644: portfolio => 1,
5645: );
5646: }
5647: return if (!defined($tools{$tool}));
5648:
5649: if ((!defined($udom)) || (!defined($uname))) {
5650: $udom = $env{'user.domain'};
5651: $uname = $env{'user.name'};
5652: }
5653:
5654: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5655: if ($action ne 'reload') {
5656: if ($context eq 'requestcourses') {
5657: return $env{'environment.canrequest.'.$tool};
5658: } else {
5659: return $env{'environment.availabletools.'.$tool};
5660: }
5661: }
5662: }
5663:
5664: my ($toolstatus,$inststatus);
5665:
5666: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5667: ($action ne 'reload')) {
5668: $toolstatus = $env{'environment.'.$context.'.'.$tool};
5669: $inststatus = $env{'environment.inststatus'};
5670: } else {
5671: if (ref($userenvref) eq 'HASH') {
5672: $toolstatus = $userenvref->{$context.'.'.$tool};
5673: $inststatus = $userenvref->{'inststatus'};
5674: } else {
5675: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5676: $toolstatus = $userenv{$context.'.'.$tool};
5677: $inststatus = $userenv{'inststatus'};
5678: }
5679: }
5680:
5681: if ($toolstatus ne '') {
5682: if ($toolstatus) {
5683: $access = 1;
5684: } else {
5685: $access = 0;
5686: }
5687: return $access;
5688: }
5689:
5690: my ($is_adv,%domdef);
5691: if (ref($is_advref) eq 'HASH') {
5692: $is_adv = $is_advref->{'is_adv'};
5693: } else {
5694: $is_adv = &is_advanced_user($udom,$uname);
5695: }
5696: if (ref($domdefref) eq 'HASH') {
5697: %domdef = %{$domdefref};
5698: } else {
5699: %domdef = &get_domain_defaults($udom);
5700: }
5701: if (ref($domdef{$tool}) eq 'HASH') {
5702: if ($is_adv) {
5703: if ($domdef{$tool}{'_LC_adv'} ne '') {
5704: if ($domdef{$tool}{'_LC_adv'}) {
5705: $access = 1;
5706: } else {
5707: $access = 0;
5708: }
5709: return $access;
5710: }
5711: }
5712: if ($inststatus ne '') {
5713: my ($hasaccess,$hasnoaccess);
5714: foreach my $affiliation (split(/:/,$inststatus)) {
5715: if ($domdef{$tool}{$affiliation} ne '') {
5716: if ($domdef{$tool}{$affiliation}) {
5717: $hasaccess = 1;
5718: } else {
5719: $hasnoaccess = 1;
5720: }
5721: }
5722: }
5723: if ($hasaccess || $hasnoaccess) {
5724: if ($hasaccess) {
5725: $access = 1;
5726: } elsif ($hasnoaccess) {
5727: $access = 0;
5728: }
5729: return $access;
5730: }
5731: } else {
5732: if ($domdef{$tool}{'default'} ne '') {
5733: if ($domdef{$tool}{'default'}) {
5734: $access = 1;
5735: } elsif ($domdef{$tool}{'default'} == 0) {
5736: $access = 0;
5737: }
5738: return $access;
5739: }
5740: }
5741: } else {
5742: if ($context eq 'tools') {
5743: $access = 1;
5744: } else {
5745: $access = 0;
5746: }
5747: return $access;
5748: }
5749: }
5750:
5751: sub is_course_owner {
5752: my ($cdom,$cnum,$udom,$uname) = @_;
5753: if (($udom eq '') || ($uname eq '')) {
5754: $udom = $env{'user.domain'};
5755: $uname = $env{'user.name'};
5756: }
5757: unless (($udom eq '') || ($uname eq '')) {
5758: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5759: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5760: return 1;
5761: } else {
5762: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5763: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5764: return 1;
5765: }
5766: }
5767: }
5768: }
5769: return;
5770: }
5771:
5772: sub is_advanced_user {
5773: my ($udom,$uname) = @_;
5774: if ($udom ne '' && $uname ne '') {
5775: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5776: if (wantarray) {
5777: return ($env{'user.adv'},$env{'user.author'});
5778: } else {
5779: return $env{'user.adv'};
5780: }
5781: }
5782: }
5783: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5784: my %allroles;
5785: my ($is_adv,$is_author);
5786: foreach my $role (keys(%roleshash)) {
5787: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5788: my $area = '/'.$tdomain.'/'.$trest;
5789: if ($sec ne '') {
5790: $area .= '/'.$sec;
5791: }
5792: if (($area ne '') && ($trole ne '')) {
5793: my $spec=$trole.'.'.$area;
5794: if ($trole =~ /^cr\//) {
5795: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5796: } elsif ($trole ne 'gr') {
5797: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5798: }
5799: if ($trole eq 'au') {
5800: $is_author = 1;
5801: }
5802: }
5803: }
5804: foreach my $role (keys(%allroles)) {
5805: last if ($is_adv);
5806: foreach my $item (split(/:/,$allroles{$role})) {
5807: if ($item ne '') {
5808: my ($privilege,$restrictions)=split(/&/,$item);
5809: if ($privilege eq 'adv') {
5810: $is_adv = 1;
5811: last;
5812: }
5813: }
5814: }
5815: }
5816: if (wantarray) {
5817: return ($is_adv,$is_author);
5818: }
5819: return $is_adv;
5820: }
5821:
5822: sub check_can_request {
5823: my ($dom,$can_request,$request_domains) = @_;
5824: my $canreq = 0;
5825: my ($types,$typename) = &Apache::loncommon::course_types();
5826: my @options = ('approval','validate','autolimit');
5827: my $optregex = join('|',@options);
5828: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5829: foreach my $type (@{$types}) {
5830: if (&usertools_access($env{'user.name'},
5831: $env{'user.domain'},
5832: $type,undef,'requestcourses')) {
5833: $canreq ++;
5834: if (ref($request_domains) eq 'HASH') {
5835: push(@{$request_domains->{$type}},$env{'user.domain'});
5836: }
5837: if ($dom eq $env{'user.domain'}) {
5838: $can_request->{$type} = 1;
5839: }
5840: }
5841: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5842: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5843: if (@curr > 0) {
5844: foreach my $item (@curr) {
5845: if (ref($request_domains) eq 'HASH') {
5846: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5847: if ($otherdom ne '') {
5848: if (ref($request_domains->{$type}) eq 'ARRAY') {
5849: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5850: push(@{$request_domains->{$type}},$otherdom);
5851: }
5852: } else {
5853: push(@{$request_domains->{$type}},$otherdom);
5854: }
5855: }
5856: }
5857: }
5858: unless($dom eq $env{'user.domain'}) {
5859: $canreq ++;
5860: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5861: $can_request->{$type} = 1;
5862: }
5863: }
5864: }
5865: }
5866: }
5867: }
5868: return $canreq;
5869: }
5870:
5871: # ---------------------------------------------- Custom access rule evaluation
5872:
5873: sub customaccess {
5874: my ($priv,$uri)=@_;
5875: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
5876: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
5877: $udom = &LONCAPA::clean_domain($udom);
5878: $ucrs = &LONCAPA::clean_username($ucrs);
5879: my $access=0;
5880: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
5881: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5882: if ($type eq 'user') {
5883: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5884: my ($tdom,$tuname)=split(m{/},$scope);
5885: if ($tdom) {
5886: if ($tdom ne $env{'user.domain'}) { next; }
5887: }
5888: if ($tuname) {
5889: if ($tuname ne $env{'user.name'}) { next; }
5890: }
5891: $access=($effect eq 'allow');
5892: last;
5893: }
5894: } else {
5895: if ($role) {
5896: if ($role ne $urole) { next; }
5897: }
5898: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5899: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5900: if ($tdom) {
5901: if ($tdom ne $udom) { next; }
5902: }
5903: if ($tcrs) {
5904: if ($tcrs ne $ucrs) { next; }
5905: }
5906: if ($tsec) {
5907: if ($tsec ne $usec) { next; }
5908: }
5909: $access=($effect eq 'allow');
5910: last;
5911: }
5912: if ($realm eq '' && $role eq '') {
5913: $access=($effect eq 'allow');
5914: }
5915: }
5916: }
5917: return $access;
5918: }
5919:
5920: # ------------------------------------------------- Check for a user privilege
5921:
5922: sub allowed {
5923: my ($priv,$uri,$symb,$role)=@_;
5924: my $ver_orguri=$uri;
5925: $uri=&deversion($uri);
5926: my $orguri=$uri;
5927: $uri=&declutter($uri);
5928:
5929: if ($priv eq 'evb') {
5930: # Evade communication block restrictions for specified role in a course
5931: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5932: return $1;
5933: } else {
5934: return;
5935: }
5936: }
5937:
5938: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
5939: # Free bre access to adm and meta resources
5940: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
5941: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5942: && ($priv eq 'bre')) {
5943: return 'F';
5944: }
5945:
5946: # Free bre access to user's own portfolio contents
5947: my ($space,$domain,$name,@dir)=split('/',$uri);
5948: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
5949: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
5950: my %setters;
5951: my ($startblock,$endblock) =
5952: &Apache::loncommon::blockcheck(\%setters,'port');
5953: if ($startblock && $endblock) {
5954: return 'B';
5955: } else {
5956: return 'F';
5957: }
5958: }
5959:
5960: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
5961: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5962: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5963: if (exists($env{'request.course.id'})) {
5964: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5965: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5966: if (($domain eq $cdom) && ($name eq $cnum)) {
5967: my $courseprivid=$env{'request.course.id'};
5968: $courseprivid=~s/\_/\//;
5969: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5970: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5971: return $1;
5972: } else {
5973: if ($env{'request.course.sec'}) {
5974: $courseprivid.='/'.$env{'request.course.sec'};
5975: }
5976: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5977: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5978: return $2;
5979: }
5980: }
5981: }
5982: }
5983: }
5984:
5985: # Free bre to public access
5986:
5987: if ($priv eq 'bre') {
5988: my $copyright=&metadata($uri,'copyright');
5989: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
5990: return 'F';
5991: }
5992: if ($copyright eq 'priv') {
5993: $uri=~/([^\/]+)\/([^\/]+)\//;
5994: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5995: return '';
5996: }
5997: }
5998: if ($copyright eq 'domain') {
5999: $uri=~/([^\/]+)\/([^\/]+)\//;
6000: unless (($env{'user.domain'} eq $1) ||
6001: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
6002: return '';
6003: }
6004: }
6005: if ($env{'request.role'}=~ /li\.\//) {
6006: # Library role, so allow browsing of resources in this domain.
6007: return 'F';
6008: }
6009: if ($copyright eq 'custom') {
6010: unless (&customaccess($priv,$uri)) { return ''; }
6011: }
6012: }
6013: # Domain coordinator is trying to create a course
6014: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
6015: # uri is the requested domain in this case.
6016: # comparison to 'request.role.domain' shows if the user has selected
6017: # a role of dc for the domain in question.
6018: return 'F' if ($uri eq $env{'request.role.domain'});
6019: }
6020:
6021: my $thisallowed='';
6022: my $statecond=0;
6023: my $courseprivid='';
6024:
6025: my $ownaccess;
6026: # Community Coordinator or Assistant Co-author browsing resource space.
6027: if (($priv eq 'bro') && ($env{'user.author'})) {
6028: if ($uri eq '') {
6029: $ownaccess = 1;
6030: } else {
6031: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6032: my $udom = $env{'user.domain'};
6033: my $uname = $env{'user.name'};
6034: if ($uri =~ m{^\Q$udom\E/?$}) {
6035: $ownaccess = 1;
6036: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
6037: unless ($uri =~ m{\.\./}) {
6038: $ownaccess = 1;
6039: }
6040: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6041: my $now = time;
6042: if ($uri =~ m{^([^/]+)/?$}) {
6043: my $adom = $1;
6044: foreach my $key (keys(%env)) {
6045: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
6046: my ($start,$end) = split('.',$env{$key});
6047: if (($now >= $start) && (!$end || $end < $now)) {
6048: $ownaccess = 1;
6049: last;
6050: }
6051: }
6052: }
6053: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6054: my $adom = $1;
6055: my $aname = $2;
6056: foreach my $role ('ca','aa') {
6057: if ($env{"user.role.$role./$adom/$aname"}) {
6058: my ($start,$end) =
6059: split('.',$env{"user.role.$role./$adom/$aname"});
6060: if (($now >= $start) && (!$end || $end < $now)) {
6061: $ownaccess = 1;
6062: last;
6063: }
6064: }
6065: }
6066: }
6067: }
6068: }
6069: }
6070: }
6071:
6072: # Course
6073:
6074: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
6075: unless (($priv eq 'bro') && (!$ownaccess)) {
6076: $thisallowed.=$1;
6077: }
6078: }
6079:
6080: # Domain
6081:
6082: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
6083: =~/\Q$priv\E\&([^\:]*)/) {
6084: unless (($priv eq 'bro') && (!$ownaccess)) {
6085: $thisallowed.=$1;
6086: }
6087: }
6088:
6089: # User who is not author or co-author might still be able to edit
6090: # resource of an author in the domain (e.g., if Domain Coordinator).
6091: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6092: (&allowed('mdc',$env{'request.course.id'}))) {
6093: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6094: $thisallowed.=$1;
6095: }
6096: }
6097:
6098: # Course: uri itself is a course
6099: my $courseuri=$uri;
6100: $courseuri=~s/\_(\d)/\/$1/;
6101: $courseuri=~s/^([^\/])/\/$1/;
6102:
6103: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
6104: =~/\Q$priv\E\&([^\:]*)/) {
6105: unless (($priv eq 'bro') && (!$ownaccess)) {
6106: $thisallowed.=$1;
6107: }
6108: }
6109:
6110: # URI is an uploaded document for this course, default permissions don't matter
6111: # not allowing 'edit' access (editupload) to uploaded course docs
6112: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
6113: $thisallowed='';
6114: my ($match)=&is_on_map($uri);
6115: if ($match) {
6116: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6117: =~/\Q$priv\E\&([^\:]*)/) {
6118: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6119: if (@blockers > 0) {
6120: $thisallowed = 'B';
6121: } else {
6122: $thisallowed.=$1;
6123: }
6124: }
6125: } else {
6126: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
6127: if ($refuri) {
6128: if ($refuri =~ m|^/adm/|) {
6129: $thisallowed='F';
6130: } else {
6131: $refuri=&declutter($refuri);
6132: my ($match) = &is_on_map($refuri);
6133: if ($match) {
6134: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6135: if (@blockers > 0) {
6136: $thisallowed = 'B';
6137: } else {
6138: $thisallowed='F';
6139: }
6140: }
6141: }
6142: }
6143: }
6144: }
6145:
6146: if ($priv eq 'bre'
6147: && $thisallowed ne 'F'
6148: && $thisallowed ne '2'
6149: && &is_portfolio_url($uri)) {
6150: $thisallowed = &portfolio_access($uri);
6151: }
6152:
6153: # Full access at system, domain or course-wide level? Exit.
6154: if ($thisallowed=~/F/) {
6155: return 'F';
6156: }
6157:
6158: # If this is generating or modifying users, exit with special codes
6159:
6160: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6161: if (($priv eq 'cca') || ($priv eq 'caa')) {
6162: my ($audom,$auname)=split('/',$uri);
6163: # no author name given, so this just checks on the general right to make a co-author in this domain
6164: unless ($auname) { return $thisallowed; }
6165: # an author name is given, so we are about to actually make a co-author for a certain account
6166: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6167: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6168: ($audom ne $env{'request.role.domain'}))) { return ''; }
6169: }
6170: return $thisallowed;
6171: }
6172: #
6173: # Gathered so far: system, domain and course wide privileges
6174: #
6175: # Course: See if uri or referer is an individual resource that is part of
6176: # the course
6177:
6178: if ($env{'request.course.id'}) {
6179:
6180: $courseprivid=$env{'request.course.id'};
6181: if ($env{'request.course.sec'}) {
6182: $courseprivid.='/'.$env{'request.course.sec'};
6183: }
6184: $courseprivid=~s/\_/\//;
6185: my $checkreferer=1;
6186: my ($match,$cond)=&is_on_map($uri);
6187: if ($match) {
6188: $statecond=$cond;
6189: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6190: =~/\Q$priv\E\&([^\:]*)/) {
6191: my $value = $1;
6192: if ($priv eq 'bre') {
6193: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6194: if (@blockers > 0) {
6195: $thisallowed = 'B';
6196: } else {
6197: $thisallowed.=$value;
6198: }
6199: } else {
6200: $thisallowed.=$value;
6201: }
6202: $checkreferer=0;
6203: }
6204: }
6205:
6206: if ($checkreferer) {
6207: my $refuri=$env{'httpref.'.$orguri};
6208: unless ($refuri) {
6209: foreach my $key (keys(%env)) {
6210: if ($key=~/^httpref\..*\*/) {
6211: my $pattern=$key;
6212: $pattern=~s/^httpref\.\/res\///;
6213: $pattern=~s/\*/\[\^\/\]\+/g;
6214: $pattern=~s/\//\\\//g;
6215: if ($orguri=~/$pattern/) {
6216: $refuri=$env{$key};
6217: }
6218: }
6219: }
6220: }
6221:
6222: if ($refuri) {
6223: $refuri=&declutter($refuri);
6224: my ($match,$cond)=&is_on_map($refuri);
6225: if ($match) {
6226: my $refstatecond=$cond;
6227: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
6228: =~/\Q$priv\E\&([^\:]*)/) {
6229: my $value = $1;
6230: if ($priv eq 'bre') {
6231: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6232: if (@blockers > 0) {
6233: $thisallowed = 'B';
6234: } else {
6235: $thisallowed.=$value;
6236: }
6237: } else {
6238: $thisallowed.=$value;
6239: }
6240: $uri=$refuri;
6241: $statecond=$refstatecond;
6242: }
6243: }
6244: }
6245: }
6246: }
6247:
6248: #
6249: # Gathered now: all privileges that could apply, and condition number
6250: #
6251: #
6252: # Full or no access?
6253: #
6254:
6255: if ($thisallowed=~/F/) {
6256: return 'F';
6257: }
6258:
6259: unless ($thisallowed) {
6260: return '';
6261: }
6262:
6263: # Restrictions exist, deal with them
6264: #
6265: # C:according to course preferences
6266: # R:according to resource settings
6267: # L:unless locked
6268: # X:according to user session state
6269: #
6270:
6271: # Possibly locked functionality, check all courses
6272: # Locks might take effect only after 10 minutes cache expiration for other
6273: # courses, and 2 minutes for current course
6274:
6275: my $envkey;
6276: if ($thisallowed=~/L/) {
6277: foreach $envkey (keys(%env)) {
6278: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6279: my $courseid=$2;
6280: my $roleid=$1.'.'.$2;
6281: $courseid=~s/^\///;
6282: my $expiretime=600;
6283: if ($env{'request.role'} eq $roleid) {
6284: $expiretime=120;
6285: }
6286: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6287: my $prefix='course.'.$cdom.'_'.$cnum.'.';
6288: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
6289: &coursedescription($courseid,{'freshen_cache' => 1});
6290: }
6291: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6292: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6293: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6294: &log($env{'user.domain'},$env{'user.name'},
6295: $env{'user.home'},
6296: 'Locked by res: '.$priv.' for '.$uri.' due to '.
6297: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6298: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6299: return '';
6300: }
6301: }
6302: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6303: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6304: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6305: &log($env{'user.domain'},$env{'user.name'},
6306: $env{'user.home'},
6307: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
6308: $cdom.'/'.$cnum.'/'.$csec.' expire '.
6309: $env{$prefix.'priv.'.$priv.'.lock.expire'});
6310: return '';
6311: }
6312: }
6313: }
6314: }
6315: }
6316:
6317: #
6318: # Rest of the restrictions depend on selected course
6319: #
6320:
6321: unless ($env{'request.course.id'}) {
6322: if ($thisallowed eq 'A') {
6323: return 'A';
6324: } elsif ($thisallowed eq 'B') {
6325: return 'B';
6326: } else {
6327: return '1';
6328: }
6329: }
6330:
6331: #
6332: # Now user is definitely in a course
6333: #
6334:
6335:
6336: # Course preferences
6337:
6338: if ($thisallowed=~/C/) {
6339: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6340: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6341: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
6342: =~/\Q$rolecode\E/) {
6343: if (($priv ne 'pch') && ($priv ne 'plc')) {
6344: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6345: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6346: $env{'request.course.id'});
6347: }
6348: return '';
6349: }
6350:
6351: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
6352: =~/\Q$unamedom\E/) {
6353: if (($priv ne 'pch') && ($priv ne 'plc')) {
6354: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6355: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6356: $env{'request.course.id'});
6357: }
6358: return '';
6359: }
6360: }
6361:
6362: # Resource preferences
6363:
6364: if ($thisallowed=~/R/) {
6365: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6366: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
6367: if (($priv ne 'pch') && ($priv ne 'plc')) {
6368: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6369: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6370: }
6371: return '';
6372: }
6373: }
6374:
6375: # Restricted by state or randomout?
6376:
6377: if ($thisallowed=~/X/) {
6378: if ($env{'acc.randomout'}) {
6379: if (!$symb) { $symb=&symbread($uri,1); }
6380: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
6381: return '';
6382: }
6383: }
6384: if (&condval($statecond)) {
6385: return '2';
6386: } else {
6387: return '';
6388: }
6389: }
6390:
6391: if ($thisallowed eq 'A') {
6392: return 'A';
6393: } elsif ($thisallowed eq 'B') {
6394: return 'B';
6395: }
6396: return 'F';
6397: }
6398:
6399: sub get_comm_blocks {
6400: my ($cdom,$cnum) = @_;
6401: if ($cdom eq '' || $cnum eq '') {
6402: return unless ($env{'request.course.id'});
6403: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6404: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6405: }
6406: my %commblocks;
6407: my $hashid=$cdom.'_'.$cnum;
6408: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6409: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6410: %commblocks = %{$blocksref};
6411: } else {
6412: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6413: my $cachetime = 600;
6414: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6415: }
6416: return %commblocks;
6417: }
6418:
6419: sub has_comm_blocking {
6420: my ($priv,$symb,$uri,$blocks) = @_;
6421: return unless ($env{'request.course.id'});
6422: return unless ($priv eq 'bre');
6423: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6424: my %commblocks;
6425: if (ref($blocks) eq 'HASH') {
6426: %commblocks = %{$blocks};
6427: } else {
6428: %commblocks = &get_comm_blocks();
6429: }
6430: return unless (keys(%commblocks) > 0);
6431: if (!$symb) { $symb=&symbread($uri,1); }
6432: my ($map,$resid,undef)=&decode_symb($symb);
6433: my %tocheck = (
6434: maps => $map,
6435: resources => $symb,
6436: );
6437: my @blockers;
6438: my $now = time;
6439: my $navmap = Apache::lonnavmaps::navmap->new();
6440: foreach my $block (keys(%commblocks)) {
6441: if ($block =~ /^(\d+)____(\d+)$/) {
6442: my ($start,$end) = ($1,$2);
6443: if ($start <= $now && $end >= $now) {
6444: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6445: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6446: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6447: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6448: unless (grep(/^\Q$block\E$/,@blockers)) {
6449: push(@blockers,$block);
6450: }
6451: }
6452: }
6453: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6454: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6455: unless (grep(/^\Q$block\E$/,@blockers)) {
6456: push(@blockers,$block);
6457: }
6458: }
6459: }
6460: }
6461: }
6462: }
6463: } elsif ($block =~ /^firstaccess____(.+)$/) {
6464: my $item = $1;
6465: my @to_test;
6466: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6467: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6468: my $check_interval;
6469: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6470: my @interval;
6471: my $type = 'map';
6472: if ($item eq 'course') {
6473: $type = 'course';
6474: @interval=&EXT("resource.0.interval");
6475: } else {
6476: if ($item =~ /___\d+___/) {
6477: $type = 'resource';
6478: @interval=&EXT("resource.0.interval",$item);
6479: if (ref($navmap)) {
6480: my $res = $navmap->getBySymb($item);
6481: push(@to_test,$res);
6482: }
6483: } else {
6484: my $mapsymb = &symbread($item,1);
6485: if ($mapsymb) {
6486: if (ref($navmap)) {
6487: my $mapres = $navmap->getBySymb($mapsymb);
6488: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6489: foreach my $res (@to_test) {
6490: my $symb = $res->symb();
6491: next if ($symb eq $mapsymb);
6492: if ($symb ne '') {
6493: @interval=&EXT("resource.0.interval",$symb);
6494: last;
6495: }
6496: }
6497: }
6498: }
6499: }
6500: }
6501: if ($interval[0] =~ /\d+/) {
6502: my $first_access;
6503: if ($type eq 'resource') {
6504: $first_access=&get_first_access($interval[1],$item);
6505: } elsif ($type eq 'map') {
6506: $first_access=&get_first_access($interval[1],undef,$item);
6507: } else {
6508: $first_access=&get_first_access($interval[1]);
6509: }
6510: if ($first_access) {
6511: my $timesup = $first_access+$interval[0];
6512: if ($timesup > $now) {
6513: foreach my $res (@to_test) {
6514: if ($res->is_problem()) {
6515: if ($res->completable()) {
6516: unless (grep(/^\Q$block\E$/,@blockers)) {
6517: push(@blockers,$block);
6518: }
6519: last;
6520: }
6521: }
6522: }
6523: }
6524: }
6525: }
6526: }
6527: }
6528: }
6529: }
6530: }
6531: return @blockers;
6532: }
6533:
6534: sub check_docs_block {
6535: my ($docsblock,$tocheck) =@_;
6536: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6537: return;
6538: }
6539: if (ref($docsblock->{'maps'}) eq 'HASH') {
6540: if ($tocheck->{'maps'}) {
6541: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6542: return 1;
6543: }
6544: }
6545: }
6546: if (ref($docsblock->{'resources'}) eq 'HASH') {
6547: if ($tocheck->{'resources'}) {
6548: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6549: return 1;
6550: }
6551: }
6552: }
6553: return;
6554: }
6555:
6556: #
6557: # Removes the versino from a URI and
6558: # splits it in to its filename and path to the filename.
6559: # Seems like File::Basename could have done this more clearly.
6560: # Parameters:
6561: # $uri - input URI
6562: # Returns:
6563: # Two element list consisting of
6564: # $pathname - the URI up to and excluding the trailing /
6565: # $filename - The part of the URI following the last /
6566: # NOTE:
6567: # Another realization of this is simply:
6568: # use File::Basename;
6569: # ...
6570: # $uri = shift;
6571: # $filename = basename($uri);
6572: # $path = dirname($uri);
6573: # return ($filename, $path);
6574: #
6575: # The implementation below is probably faster however.
6576: #
6577: sub split_uri_for_cond {
6578: my $uri=&deversion(&declutter(shift));
6579: my @uriparts=split(/\//,$uri);
6580: my $filename=pop(@uriparts);
6581: my $pathname=join('/',@uriparts);
6582: return ($pathname,$filename);
6583: }
6584: # --------------------------------------------------- Is a resource on the map?
6585:
6586: sub is_on_map {
6587: my ($pathname,$filename) = &split_uri_for_cond(shift);
6588: #Trying to find the conditional for the file
6589: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
6590: /\&\Q$filename\E\:([\d\|]+)\&/);
6591: if ($match) {
6592: return (1,$1);
6593: } else {
6594: return (0,0);
6595: }
6596: }
6597:
6598: # --------------------------------------------------------- Get symb from alias
6599:
6600: sub get_symb_from_alias {
6601: my $symb=shift;
6602: my ($map,$resid,$url)=&decode_symb($symb);
6603: # Already is a symb
6604: if ($url) { return $symb; }
6605: # Must be an alias
6606: my $aliassymb='';
6607: my %bighash;
6608: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6609: &GDBM_READER(),0640)) {
6610: my $rid=$bighash{'mapalias_'.$symb};
6611: if ($rid) {
6612: my ($mapid,$resid)=split(/\./,$rid);
6613: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6614: $resid,$bighash{'src_'.$rid});
6615: }
6616: untie %bighash;
6617: }
6618: return $aliassymb;
6619: }
6620:
6621: # ----------------------------------------------------------------- Define Role
6622:
6623: sub definerole {
6624: if (allowed('mcr','/')) {
6625: my ($rolename,$sysrole,$domrole,$courole)=@_;
6626: foreach my $role (split(':',$sysrole)) {
6627: my ($crole,$cqual)=split(/\&/,$role);
6628: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6629: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6630: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6631: return "refused:s:$crole&$cqual";
6632: }
6633: }
6634: }
6635: foreach my $role (split(':',$domrole)) {
6636: my ($crole,$cqual)=split(/\&/,$role);
6637: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6638: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6639: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
6640: return "refused:d:$crole&$cqual";
6641: }
6642: }
6643: }
6644: foreach my $role (split(':',$courole)) {
6645: my ($crole,$cqual)=split(/\&/,$role);
6646: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6647: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6648: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
6649: return "refused:c:$crole&$cqual";
6650: }
6651: }
6652: }
6653: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6654: "$env{'user.domain'}:$env{'user.name'}:".
6655: "rolesdef_$rolename=".
6656: escape($sysrole.'_'.$domrole.'_'.$courole);
6657: return reply($command,$env{'user.home'});
6658: } else {
6659: return 'refused';
6660: }
6661: }
6662:
6663: # ---------------- Make a metadata query against the network of library servers
6664:
6665: sub metadata_query {
6666: my ($query,$custom,$customshow,$server_array)=@_;
6667: my %rhash;
6668: my %libserv = &all_library();
6669: my @server_list = (defined($server_array) ? @$server_array
6670: : keys(%libserv) );
6671: for my $server (@server_list) {
6672: unless ($custom or $customshow) {
6673: my $reply=&reply("querysend:".&escape($query),$server);
6674: $rhash{$server}=$reply;
6675: }
6676: else {
6677: my $reply=&reply("querysend:".&escape($query).':'.
6678: &escape($custom).':'.&escape($customshow),
6679: $server);
6680: $rhash{$server}=$reply;
6681: }
6682: }
6683: return \%rhash;
6684: }
6685:
6686: # ----------------------------------------- Send log queries and wait for reply
6687:
6688: sub log_query {
6689: my ($uname,$udom,$query,%filters)=@_;
6690: my $uhome=&homeserver($uname,$udom);
6691: if ($uhome eq 'no_host') { return 'error: no_host'; }
6692: my $uhost=&hostname($uhome);
6693: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
6694: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6695: $uhome);
6696: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
6697: return get_query_reply($queryid);
6698: }
6699:
6700: # -------------------------- Update MySQL table for portfolio file
6701:
6702: sub update_portfolio_table {
6703: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
6704: if ($group ne '') {
6705: $file_name =~s /^\Q$group\E//;
6706: }
6707: my $homeserver = &homeserver($uname,$udom);
6708: my $queryid=
6709: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6710: ':'.&escape($file_name).':'.$action,$homeserver);
6711: my $reply = &get_query_reply($queryid);
6712: return $reply;
6713: }
6714:
6715: # -------------------------- Update MySQL allusers table
6716:
6717: sub update_allusers_table {
6718: my ($uname,$udom,$names) = @_;
6719: my $homeserver = &homeserver($uname,$udom);
6720: my $queryid=
6721: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6722: 'lastname='.&escape($names->{'lastname'}).'%%'.
6723: 'firstname='.&escape($names->{'firstname'}).'%%'.
6724: 'middlename='.&escape($names->{'middlename'}).'%%'.
6725: 'generation='.&escape($names->{'generation'}).'%%'.
6726: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6727: 'id='.&escape($names->{'id'}),$homeserver);
6728: return;
6729: }
6730:
6731: # ------- Request retrieval of institutional classlists for course(s)
6732:
6733: sub fetch_enrollment_query {
6734: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
6735: my $homeserver;
6736: my $maxtries = 1;
6737: if ($context eq 'automated') {
6738: $homeserver = $perlvar{'lonHostID'};
6739: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
6740: } else {
6741: $homeserver = &homeserver($cnum,$dom);
6742: }
6743: my $host=&hostname($homeserver);
6744: my $cmd = '';
6745: foreach my $affiliate (keys(%{$affiliatesref})) {
6746: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
6747: }
6748: $cmd =~ s/%%$//;
6749: $cmd = &escape($cmd);
6750: my $query = 'fetchenrollment';
6751: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
6752: unless ($queryid=~/^\Q$host\E\_/) {
6753: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6754: return 'error: '.$queryid;
6755: }
6756: my $reply = &get_query_reply($queryid);
6757: my $tries = 1;
6758: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6759: $reply = &get_query_reply($queryid);
6760: $tries ++;
6761: }
6762: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6763: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6764: } else {
6765: my @responses = split(/:/,$reply);
6766: if ($homeserver eq $perlvar{'lonHostID'}) {
6767: foreach my $line (@responses) {
6768: my ($key,$value) = split(/=/,$line,2);
6769: $$replyref{$key} = $value;
6770: }
6771: } else {
6772: my $pathname = LONCAPA::tempdir();
6773: foreach my $line (@responses) {
6774: my ($key,$value) = split(/=/,$line);
6775: $$replyref{$key} = $value;
6776: if ($value > 0) {
6777: foreach my $item (@{$$affiliatesref{$key}}) {
6778: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
6779: my $destname = $pathname.'/'.$filename;
6780: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
6781: if ($xml_classlist =~ /^error/) {
6782: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6783: } else {
6784: if ( open(FILE,">$destname") ) {
6785: print FILE &unescape($xml_classlist);
6786: close(FILE);
6787: } else {
6788: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
6789: }
6790: }
6791: }
6792: }
6793: }
6794: }
6795: return 'ok';
6796: }
6797: return 'error';
6798: }
6799:
6800: sub get_query_reply {
6801: my $queryid=shift;
6802: my $replyfile=LONCAPA::tempdir().$queryid;
6803: my $reply='';
6804: for (1..100) {
6805: sleep 2;
6806: if (-e $replyfile.'.end') {
6807: if (open(my $fh,$replyfile)) {
6808: $reply = join('',<$fh>);
6809: close($fh);
6810: } else { return 'error: reply_file_error'; }
6811: return &unescape($reply);
6812: }
6813: }
6814: return 'timeout:'.$queryid;
6815: }
6816:
6817: sub courselog_query {
6818: #
6819: # possible filters:
6820: # url: url or symb
6821: # username
6822: # domain
6823: # action: view, submit, grade
6824: # start: timestamp
6825: # end: timestamp
6826: #
6827: my (%filters)=@_;
6828: unless ($env{'request.course.id'}) { return 'no_course'; }
6829: if ($filters{'url'}) {
6830: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6831: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6832: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6833: }
6834: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6835: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
6836: return &log_query($cname,$cdom,'courselog',%filters);
6837: }
6838:
6839: sub userlog_query {
6840: #
6841: # possible filters:
6842: # action: log check role
6843: # start: timestamp
6844: # end: timestamp
6845: #
6846: my ($uname,$udom,%filters)=@_;
6847: return &log_query($uname,$udom,'userlog',%filters);
6848: }
6849:
6850: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6851:
6852: sub auto_run {
6853: my ($cnum,$cdom) = @_;
6854: my $response = 0;
6855: my $settings;
6856: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6857: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6858: $settings = $domconfig{'autoenroll'};
6859: if ($settings->{'run'} eq '1') {
6860: $response = 1;
6861: }
6862: } else {
6863: my $homeserver;
6864: if (&is_course($cdom,$cnum)) {
6865: $homeserver = &homeserver($cnum,$cdom);
6866: } else {
6867: $homeserver = &domain($cdom,'primary');
6868: }
6869: if ($homeserver ne 'no_host') {
6870: $response = &reply('autorun:'.$cdom,$homeserver);
6871: }
6872: }
6873: return $response;
6874: }
6875:
6876: sub auto_get_sections {
6877: my ($cnum,$cdom,$inst_coursecode) = @_;
6878: my $homeserver;
6879: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6880: $homeserver = &homeserver($cnum,$cdom);
6881: }
6882: if (!defined($homeserver)) {
6883: if ($cdom =~ /^$match_domain$/) {
6884: $homeserver = &domain($cdom,'primary');
6885: }
6886: }
6887: my @secs;
6888: if (defined($homeserver)) {
6889: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6890: unless ($response eq 'refused') {
6891: @secs = split(/:/,$response);
6892: }
6893: }
6894: return @secs;
6895: }
6896:
6897: sub auto_new_course {
6898: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
6899: my $homeserver = &homeserver($cnum,$cdom);
6900: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
6901: return $response;
6902: }
6903:
6904: sub auto_validate_courseID {
6905: my ($cnum,$cdom,$inst_course_id) = @_;
6906: my $homeserver = &homeserver($cnum,$cdom);
6907: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
6908: return $response;
6909: }
6910:
6911: sub auto_validate_instcode {
6912: my ($cnum,$cdom,$instcode,$owner) = @_;
6913: my ($homeserver,$response);
6914: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6915: $homeserver = &homeserver($cnum,$cdom);
6916: }
6917: if (!defined($homeserver)) {
6918: if ($cdom =~ /^$match_domain$/) {
6919: $homeserver = &domain($cdom,'primary');
6920: }
6921: }
6922: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6923: &escape($instcode).':'.&escape($owner),$homeserver));
6924: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6925: return ($outcome,$description);
6926: }
6927:
6928: sub auto_create_password {
6929: my ($cnum,$cdom,$authparam,$udom) = @_;
6930: my ($homeserver,$response);
6931: my $create_passwd = 0;
6932: my $authchk = '';
6933: if ($udom =~ /^$match_domain$/) {
6934: $homeserver = &domain($udom,'primary');
6935: }
6936: if ($homeserver eq '') {
6937: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6938: $homeserver = &homeserver($cnum,$cdom);
6939: }
6940: }
6941: if ($homeserver eq '') {
6942: $authchk = 'nodomain';
6943: } else {
6944: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6945: if ($response eq 'refused') {
6946: $authchk = 'refused';
6947: } else {
6948: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
6949: }
6950: }
6951: return ($authparam,$create_passwd,$authchk);
6952: }
6953:
6954: sub auto_photo_permission {
6955: my ($cnum,$cdom,$students) = @_;
6956: my $homeserver = &homeserver($cnum,$cdom);
6957: my ($outcome,$perm_reqd,$conditions) =
6958: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
6959: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6960: return (undef,undef);
6961: }
6962: return ($outcome,$perm_reqd,$conditions);
6963: }
6964:
6965: sub auto_checkphotos {
6966: my ($uname,$udom,$pid) = @_;
6967: my $homeserver = &homeserver($uname,$udom);
6968: my ($result,$resulttype);
6969: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
6970: &escape($uname).':'.&escape($pid),
6971: $homeserver));
6972: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6973: return (undef,undef);
6974: }
6975: if ($outcome) {
6976: ($result,$resulttype) = split(/:/,$outcome);
6977: }
6978: return ($result,$resulttype);
6979: }
6980:
6981: sub auto_photochoice {
6982: my ($cnum,$cdom) = @_;
6983: my $homeserver = &homeserver($cnum,$cdom);
6984: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
6985: &escape($cdom),
6986: $homeserver)));
6987: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6988: return (undef,undef);
6989: }
6990: return ($update,$comment);
6991: }
6992:
6993: sub auto_photoupdate {
6994: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6995: my $homeserver = &homeserver($cnum,$dom);
6996: my $host=&hostname($homeserver);
6997: my $cmd = '';
6998: my $maxtries = 1;
6999: foreach my $affiliate (keys(%{$affiliatesref})) {
7000: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
7001: }
7002: $cmd =~ s/%%$//;
7003: $cmd = &escape($cmd);
7004: my $query = 'institutionalphotos';
7005: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7006: unless ($queryid=~/^\Q$host\E\_/) {
7007: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7008: return 'error: '.$queryid;
7009: }
7010: my $reply = &get_query_reply($queryid);
7011: my $tries = 1;
7012: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7013: $reply = &get_query_reply($queryid);
7014: $tries ++;
7015: }
7016: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7017: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7018: } else {
7019: my @responses = split(/:/,$reply);
7020: my $outcome = shift(@responses);
7021: foreach my $item (@responses) {
7022: my ($key,$value) = split(/=/,$item);
7023: $$photo{$key} = $value;
7024: }
7025: return $outcome;
7026: }
7027: return 'error';
7028: }
7029:
7030: sub auto_instcode_format {
7031: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7032: $cat_order) = @_;
7033: my $courses = '';
7034: my @homeservers;
7035: if ($caller eq 'global') {
7036: my %servers = &get_servers($codedom,'library');
7037: foreach my $tryserver (keys(%servers)) {
7038: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7039: push(@homeservers,$tryserver);
7040: }
7041: }
7042: } elsif ($caller eq 'requests') {
7043: if ($codedom =~ /^$match_domain$/) {
7044: my $chome = &domain($codedom,'primary');
7045: unless ($chome eq 'no_host') {
7046: push(@homeservers,$chome);
7047: }
7048: }
7049: } else {
7050: push(@homeservers,&homeserver($caller,$codedom));
7051: }
7052: foreach my $code (keys(%{$instcodes})) {
7053: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
7054: }
7055: chop($courses);
7056: my $ok_response = 0;
7057: my $response;
7058: while (@homeservers > 0 && $ok_response == 0) {
7059: my $server = shift(@homeservers);
7060: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7061: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7062: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
7063: split(/:/,$response);
7064: %{$codes} = (%{$codes},&str2hash($codes_str));
7065: push(@{$codetitles},&str2array($codetitles_str));
7066: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7067: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7068: $ok_response = 1;
7069: }
7070: }
7071: if ($ok_response) {
7072: return 'ok';
7073: } else {
7074: return $response;
7075: }
7076: }
7077:
7078: sub auto_instcode_defaults {
7079: my ($domain,$returnhash,$code_order) = @_;
7080: my @homeservers;
7081:
7082: my %servers = &get_servers($domain,'library');
7083: foreach my $tryserver (keys(%servers)) {
7084: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7085: push(@homeservers,$tryserver);
7086: }
7087: }
7088:
7089: my $response;
7090: foreach my $server (@homeservers) {
7091: $response=&reply('autoinstcodedefaults:'.$domain,$server);
7092: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7093:
7094: foreach my $pair (split(/\&/,$response)) {
7095: my ($name,$value)=split(/\=/,$pair);
7096: if ($name eq 'code_order') {
7097: @{$code_order} = split(/\&/,&unescape($value));
7098: } else {
7099: $returnhash->{&unescape($name)}=&unescape($value);
7100: }
7101: }
7102: return 'ok';
7103: }
7104:
7105: return $response;
7106: }
7107:
7108: sub auto_possible_instcodes {
7109: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7110: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7111: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7112: return;
7113: }
7114: my (@homeservers,$uhome);
7115: if (defined(&domain($domain,'primary'))) {
7116: $uhome=&domain($domain,'primary');
7117: push(@homeservers,&domain($domain,'primary'));
7118: } else {
7119: my %servers = &get_servers($domain,'library');
7120: foreach my $tryserver (keys(%servers)) {
7121: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7122: push(@homeservers,$tryserver);
7123: }
7124: }
7125: }
7126: my $response;
7127: foreach my $server (@homeservers) {
7128: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7129: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7130: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7131: split(':',$response);
7132: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7133: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
7134: foreach my $item (split('&',$cat_title)) {
7135: my ($name,$value)=split('=',$item);
7136: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
7137: }
7138: foreach my $item (split('&',$cat_order)) {
7139: my ($name,$value)=split('=',$item);
7140: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
7141: }
7142: return 'ok';
7143: }
7144: return $response;
7145: }
7146:
7147: sub auto_courserequest_checks {
7148: my ($dom) = @_;
7149: my ($homeserver,%validations);
7150: if ($dom =~ /^$match_domain$/) {
7151: $homeserver = &domain($dom,'primary');
7152: }
7153: unless ($homeserver eq 'no_host') {
7154: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7155: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7156: my @items = split(/&/,$response);
7157: foreach my $item (@items) {
7158: my ($key,$value) = split('=',$item);
7159: $validations{&unescape($key)} = &thaw_unescape($value);
7160: }
7161: }
7162: }
7163: return %validations;
7164: }
7165:
7166: sub auto_courserequest_validation {
7167: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7168: my ($homeserver,$response);
7169: if ($dom =~ /^$match_domain$/) {
7170: $homeserver = &domain($dom,'primary');
7171: }
7172: unless ($homeserver eq 'no_host') {
7173:
7174: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
7175: ':'.&escape($crstype).':'.&escape($inststatuslist).
7176: ':'.&escape($instcode).':'.&escape($instseclist),
7177: $homeserver));
7178: }
7179: return $response;
7180: }
7181:
7182: sub auto_validate_class_sec {
7183: my ($cdom,$cnum,$owners,$inst_class) = @_;
7184: my $homeserver = &homeserver($cnum,$cdom);
7185: my $ownerlist;
7186: if (ref($owners) eq 'ARRAY') {
7187: $ownerlist = join(',',@{$owners});
7188: } else {
7189: $ownerlist = $owners;
7190: }
7191: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
7192: &escape($ownerlist).':'.$cdom,$homeserver);
7193: return $response;
7194: }
7195:
7196: # ------------------------------------------------------- Course Group routines
7197:
7198: sub get_coursegroups {
7199: my ($cdom,$cnum,$group,$namespace) = @_;
7200: return(&dump($namespace,$cdom,$cnum,$group));
7201: }
7202:
7203: sub modify_coursegroup {
7204: my ($cdom,$cnum,$groupsettings) = @_;
7205: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7206: }
7207:
7208: sub toggle_coursegroup_status {
7209: my ($cdom,$cnum,$group,$action) = @_;
7210: my ($from_namespace,$to_namespace);
7211: if ($action eq 'delete') {
7212: $from_namespace = 'coursegroups';
7213: $to_namespace = 'deleted_groups';
7214: } else {
7215: $from_namespace = 'deleted_groups';
7216: $to_namespace = 'coursegroups';
7217: }
7218: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
7219: if (my $tmp = &error(%curr_group)) {
7220: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7221: return ('read error',$tmp);
7222: } else {
7223: my %savedsettings = %curr_group;
7224: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
7225: my $deloutcome;
7226: if ($result eq 'ok') {
7227: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
7228: } else {
7229: return ('write error',$result);
7230: }
7231: if ($deloutcome eq 'ok') {
7232: return 'ok';
7233: } else {
7234: return ('delete error',$deloutcome);
7235: }
7236: }
7237: }
7238:
7239: sub modify_group_roles {
7240: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
7241: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7242: my $role = 'gr/'.&escape($userprivs);
7243: my ($uname,$udom) = split(/:/,$user);
7244: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
7245: if ($result eq 'ok') {
7246: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7247: }
7248: return $result;
7249: }
7250:
7251: sub modify_coursegroup_membership {
7252: my ($cdom,$cnum,$membership) = @_;
7253: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7254: return $result;
7255: }
7256:
7257: sub get_active_groups {
7258: my ($udom,$uname,$cdom,$cnum) = @_;
7259: my $now = time;
7260: my %groups = ();
7261: foreach my $key (keys(%env)) {
7262: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
7263: my ($start,$end) = split(/\./,$env{$key});
7264: if (($end!=0) && ($end<$now)) { next; }
7265: if (($start!=0) && ($start>$now)) { next; }
7266: if ($1 eq $cdom && $2 eq $cnum) {
7267: $groups{$3} = $env{$key} ;
7268: }
7269: }
7270: }
7271: return %groups;
7272: }
7273:
7274: sub get_group_membership {
7275: my ($cdom,$cnum,$group) = @_;
7276: return(&dump('groupmembership',$cdom,$cnum,$group));
7277: }
7278:
7279: sub get_users_groups {
7280: my ($udom,$uname,$courseid) = @_;
7281: my @usersgroups;
7282: my $cachetime=1800;
7283:
7284: my $hashid="$udom:$uname:$courseid";
7285: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7286: if (defined($cached)) {
7287: @usersgroups = split(/:/,$grouplist);
7288: } else {
7289: $grouplist = '';
7290: my $courseurl = &courseid_to_courseurl($courseid);
7291: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
7292: my $access_end = $env{'course.'.$courseid.
7293: '.default_enrollment_end_date'};
7294: my $now = time;
7295: foreach my $key (keys(%roleshash)) {
7296: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7297: my $group = $1;
7298: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7299: my $start = $2;
7300: my $end = $1;
7301: if ($start == -1) { next; } # deleted from group
7302: if (($start!=0) && ($start>$now)) { next; }
7303: if (($end!=0) && ($end<$now)) {
7304: if ($access_end && $access_end < $now) {
7305: if ($access_end - $end < 86400) {
7306: push(@usersgroups,$group);
7307: }
7308: }
7309: next;
7310: }
7311: push(@usersgroups,$group);
7312: }
7313: }
7314: }
7315: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7316: $grouplist = join(':',@usersgroups);
7317: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
7318: }
7319: return @usersgroups;
7320: }
7321:
7322: sub devalidate_getgroups_cache {
7323: my ($udom,$uname,$cdom,$cnum)=@_;
7324: my $courseid = $cdom.'_'.$cnum;
7325:
7326: my $hashid="$udom:$uname:$courseid";
7327: &devalidate_cache_new('getgroups',$hashid);
7328: }
7329:
7330: # ------------------------------------------------------------------ Plain Text
7331:
7332: sub plaintext {
7333: my ($short,$type,$cid,$forcedefault) = @_;
7334: if ($short =~ m{^cr/}) {
7335: return (split('/',$short))[-1];
7336: }
7337: if (!defined($cid)) {
7338: $cid = $env{'request.course.id'};
7339: }
7340: my %rolenames = (
7341: Course => 'std',
7342: Community => 'alt1',
7343: );
7344: if ($cid ne '') {
7345: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7346: unless ($forcedefault) {
7347: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7348: &Apache::lonlocal::mt_escape(\$roletext);
7349: return &Apache::lonlocal::mt($roletext);
7350: }
7351: }
7352: }
7353: if ((defined($type)) && (defined($rolenames{$type})) &&
7354: (defined($rolenames{$type})) &&
7355: (defined($prp{$short}{$rolenames{$type}}))) {
7356: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
7357: } elsif ($cid ne '') {
7358: my $crstype = $env{'course.'.$cid.'.type'};
7359: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7360: (defined($prp{$short}{$rolenames{$crstype}}))) {
7361: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7362: }
7363: }
7364: return &Apache::lonlocal::mt($prp{$short}{'std'});
7365: }
7366:
7367: # ----------------------------------------------------------------- Assign Role
7368:
7369: sub assignrole {
7370: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7371: $context)=@_;
7372: my $mrole;
7373: if ($role =~ /^cr\//) {
7374: my $cwosec=$url;
7375: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7376: unless (&allowed('ccr',$cwosec)) {
7377: my $refused = 1;
7378: if ($context eq 'requestcourses') {
7379: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7380: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7381: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7382: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7383: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7384: if ($crsenv{'internal.courseowner'} eq
7385: $env{'user.name'}.':'.$env{'user.domain'}) {
7386: $refused = '';
7387: }
7388: }
7389: }
7390: }
7391: }
7392: if ($refused) {
7393: &logthis('Refused custom assignrole: '.
7394: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7395: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7396: return 'refused';
7397: }
7398: }
7399: $mrole='cr';
7400: } elsif ($role =~ /^gr\//) {
7401: my $cwogrp=$url;
7402: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
7403: unless (&allowed('mdg',$cwogrp)) {
7404: &logthis('Refused group assignrole: '.
7405: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7406: $env{'user.name'}.' at '.$env{'user.domain'});
7407: return 'refused';
7408: }
7409: $mrole='gr';
7410: } else {
7411: my $cwosec=$url;
7412: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
7413: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7414: my $refused;
7415: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7416: if (!(&allowed('c'.$role,$url))) {
7417: $refused = 1;
7418: }
7419: } else {
7420: $refused = 1;
7421: }
7422: if ($refused) {
7423: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7424: if (!$selfenroll && $context eq 'course') {
7425: my %crsenv;
7426: if ($role eq 'cc' || $role eq 'co') {
7427: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7428: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7429: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7430: if ($crsenv{'internal.courseowner'} eq
7431: $env{'user.name'}.':'.$env{'user.domain'}) {
7432: $refused = '';
7433: }
7434: }
7435: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7436: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7437: if ($crsenv{'internal.courseowner'} eq
7438: $env{'user.name'}.':'.$env{'user.domain'}) {
7439: $refused = '';
7440: }
7441: }
7442: }
7443: }
7444: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7445: $refused = '';
7446: } elsif ($context eq 'requestcourses') {
7447: my @possroles = ('st','ta','ep','in','cc','co');
7448: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
7449: my $wrongcc;
7450: if ($cnum =~ /^$match_community$/) {
7451: $wrongcc = 1 if ($role eq 'cc');
7452: } else {
7453: $wrongcc = 1 if ($role eq 'co');
7454: }
7455: unless ($wrongcc) {
7456: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7457: if ($crsenv{'internal.courseowner'} eq
7458: $env{'user.name'}.':'.$env{'user.domain'}) {
7459: $refused = '';
7460: }
7461: }
7462: }
7463: }
7464: if ($refused) {
7465: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7466: ' '.$role.' '.$end.' '.$start.' by '.
7467: $env{'user.name'}.' at '.$env{'user.domain'});
7468: return 'refused';
7469: }
7470: }
7471: } elsif ($role eq 'au') {
7472: if ($url ne '/'.$udom.'/') {
7473: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7474: ' to assign author role for '.$uname.':'.$udom.
7475: ' in domain: '.$url.' refused (wrong domain).');
7476: return 'refused';
7477: }
7478: }
7479: $mrole=$role;
7480: }
7481: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
7482: "$udom:$uname:$url".'_'."$mrole=$role";
7483: if ($end) { $command.='_'.$end; }
7484: if ($start) {
7485: if ($end) {
7486: $command.='_'.$start;
7487: } else {
7488: $command.='_0_'.$start;
7489: }
7490: }
7491: my $origstart = $start;
7492: my $origend = $end;
7493: my $delflag;
7494: # actually delete
7495: if ($deleteflag) {
7496: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
7497: # modify command to delete the role
7498: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
7499: "$udom:$uname:$url".'_'."$mrole";
7500: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
7501: # set start and finish to negative values for userrolelog
7502: $start=-1;
7503: $end=-1;
7504: $delflag = 1;
7505: }
7506: }
7507: # send command
7508: my $answer=&reply($command,&homeserver($uname,$udom));
7509: # log new user role if status is ok
7510: if ($answer eq 'ok') {
7511: &userrolelog($role,$uname,$udom,$url,$start,$end);
7512: # for course roles, perform group memberships changes triggered by role change.
7513: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
7514: unless ($role =~ /^gr/) {
7515: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
7516: $origstart,$selfenroll,$context);
7517: }
7518: if ($role eq 'cc') {
7519: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7520: }
7521: }
7522: return $answer;
7523: }
7524:
7525: sub autoupdate_coowners {
7526: my ($url,$end,$start,$uname,$udom) = @_;
7527: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7528: if (($cdom ne '') && ($cnum ne '')) {
7529: my $now = time;
7530: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7531: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7532: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7533: my $instcode = $coursehash{'internal.coursecode'};
7534: if ($instcode ne '') {
7535: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7536: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
7537: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
7538: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7539: if ($result eq 'valid') {
7540: if ($coursehash{'internal.co-owners'}) {
7541: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7542: push(@newcoowners,$coowner);
7543: }
7544: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7545: push(@newcoowners,$uname.':'.$udom);
7546: }
7547: @newcoowners = sort(@newcoowners);
7548: } else {
7549: push(@newcoowners,$uname.':'.$udom);
7550: }
7551: } else {
7552: if ($coursehash{'internal.co-owners'}) {
7553: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7554: unless ($coowner eq $uname.':'.$udom) {
7555: push(@newcoowners,$coowner);
7556: }
7557: }
7558: unless (@newcoowners > 0) {
7559: $delcoowners = 1;
7560: $coowners = '';
7561: }
7562: }
7563: }
7564: if (@newcoowners || $delcoowners) {
7565: &store_coowners($cdom,$cnum,$coursehash{'home'},
7566: $delcoowners,@newcoowners);
7567: }
7568: }
7569: }
7570: }
7571: }
7572: }
7573: }
7574:
7575: sub store_coowners {
7576: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7577: my $cid = $cdom.'_'.$cnum;
7578: my ($coowners,$delresult,$putresult);
7579: if (@newcoowners) {
7580: $coowners = join(',',@newcoowners);
7581: my %coownershash = (
7582: 'internal.co-owners' => $coowners,
7583: );
7584: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7585: if ($putresult eq 'ok') {
7586: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7587: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7588: }
7589: }
7590: }
7591: if ($delcoowners) {
7592: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7593: if ($delresult eq 'ok') {
7594: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7595: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7596: }
7597: }
7598: }
7599: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7600: my %crsinfo =
7601: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7602: if (ref($crsinfo{$cid}) eq 'HASH') {
7603: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7604: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7605: }
7606: }
7607: }
7608:
7609: # -------------------------------------------------- Modify user authentication
7610: # Overrides without validation
7611:
7612: sub modifyuserauth {
7613: my ($udom,$uname,$umode,$upass)=@_;
7614: my $uhome=&homeserver($uname,$udom);
7615: unless (&allowed('mau',$udom)) { return 'refused'; }
7616: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
7617: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7618: ' in domain '.$env{'request.role.domain'});
7619: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7620: &escape($upass),$uhome);
7621: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
7622: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7623: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7624: &log($udom,,$uname,$uhome,
7625: 'Authentication changed by '.$env{'user.domain'}.', '.
7626: $env{'user.name'}.', '.$umode.
7627: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7628: unless ($reply eq 'ok') {
7629: &logthis('Authentication mode error: '.$reply);
7630: return 'error: '.$reply;
7631: }
7632: return 'ok';
7633: }
7634:
7635: # --------------------------------------------------------------- Modify a user
7636:
7637: sub modifyuser {
7638: my ($udom, $uname, $uid,
7639: $umode, $upass, $first,
7640: $middle, $last, $gene,
7641: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
7642: $udom= &LONCAPA::clean_domain($udom);
7643: $uname=&LONCAPA::clean_username($uname);
7644: my $showcandelete = 'none';
7645: if (ref($candelete) eq 'ARRAY') {
7646: if (@{$candelete} > 0) {
7647: $showcandelete = join(', ',@{$candelete});
7648: }
7649: }
7650: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
7651: $umode.', '.$first.', '.$middle.', '.
7652: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
7653: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7654: ' desiredhome not specified').
7655: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7656: ' in domain '.$env{'request.role.domain'});
7657: my $uhome=&homeserver($uname,$udom,'true');
7658: my $newuser;
7659: if ($uhome eq 'no_host') {
7660: $newuser = 1;
7661: }
7662: # ----------------------------------------------------------------- Create User
7663: if (($uhome eq 'no_host') &&
7664: (($umode && $upass) || ($umode eq 'localauth'))) {
7665: my $unhome='';
7666: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
7667: $unhome = $desiredhome;
7668: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7669: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
7670: } else { # load balancing routine for determining $unhome
7671: my $loadm=10000000;
7672: my %servers = &get_servers($udom,'library');
7673: foreach my $tryserver (keys(%servers)) {
7674: my $answer=reply('load',$tryserver);
7675: if (($answer=~/\d+/) && ($answer<$loadm)) {
7676: $loadm=$answer;
7677: $unhome=$tryserver;
7678: }
7679: }
7680: }
7681: if (($unhome eq '') || ($unhome eq 'no_host')) {
7682: return 'error: unable to find a home server for '.$uname.
7683: ' in domain '.$udom;
7684: }
7685: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7686: &escape($upass),$unhome);
7687: unless ($reply eq 'ok') {
7688: return 'error: '.$reply;
7689: }
7690: $uhome=&homeserver($uname,$udom,'true');
7691: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
7692: return 'error: unable verify users home machine.';
7693: }
7694: } # End of creation of new user
7695: # ---------------------------------------------------------------------- Add ID
7696: if ($uid) {
7697: $uid=~tr/A-Z/a-z/;
7698: my %uidhash=&idrget($udom,$uname);
7699: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7700: && (!$forceid)) {
7701: unless ($uid eq $uidhash{$uname}) {
7702: return 'error: user id "'.$uid.'" does not match '.
7703: 'current user id "'.$uidhash{$uname}.'".';
7704: }
7705: } else {
7706: &idput($udom,($uname => $uid));
7707: }
7708: }
7709: # -------------------------------------------------------------- Add names, etc
7710: my @tmp=&get('environment',
7711: ['firstname','middlename','lastname','generation','id',
7712: 'permanentemail','inststatus'],
7713: $udom,$uname);
7714: my (%names,%oldnames);
7715: if ($tmp[0] =~ m/^error:.*/) {
7716: %names=();
7717: } else {
7718: %names = @tmp;
7719: %oldnames = %names;
7720: }
7721: #
7722: # If name, email and/or uid are blank (e.g., because an uploaded file
7723: # of users did not contain them), do not overwrite existing values
7724: # unless field is in $candelete array ref.
7725: #
7726:
7727: my @fields = ('firstname','middlename','lastname','generation',
7728: 'permanentemail','id');
7729: my %newvalues;
7730: if (ref($candelete) eq 'ARRAY') {
7731: foreach my $field (@fields) {
7732: if (grep(/^\Q$field\E$/,@{$candelete})) {
7733: if ($field eq 'firstname') {
7734: $names{$field} = $first;
7735: } elsif ($field eq 'middlename') {
7736: $names{$field} = $middle;
7737: } elsif ($field eq 'lastname') {
7738: $names{$field} = $last;
7739: } elsif ($field eq 'generation') {
7740: $names{$field} = $gene;
7741: } elsif ($field eq 'permanentemail') {
7742: $names{$field} = $email;
7743: } elsif ($field eq 'id') {
7744: $names{$field} = $uid;
7745: }
7746: }
7747: }
7748: }
7749: if ($first) { $names{'firstname'} = $first; }
7750: if (defined($middle)) { $names{'middlename'} = $middle; }
7751: if ($last) { $names{'lastname'} = $last; }
7752: if (defined($gene)) { $names{'generation'} = $gene; }
7753: if ($email) {
7754: $email=~s/[^\w\@\.\-\,]//gs;
7755: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
7756: }
7757: if ($uid) { $names{'id'} = $uid; }
7758: if (defined($inststatus)) {
7759: $names{'inststatus'} = '';
7760: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7761: if (ref($usertypes) eq 'HASH') {
7762: my @okstatuses;
7763: foreach my $item (split(/:/,$inststatus)) {
7764: if (defined($usertypes->{$item})) {
7765: push(@okstatuses,$item);
7766: }
7767: }
7768: if (@okstatuses) {
7769: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7770: }
7771: }
7772: }
7773: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
7774: $umode.', '.$first.', '.$middle.', '.
7775: $last.', '.$gene.', '.$email.', '.$inststatus;
7776: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7777: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7778: } else {
7779: $logmsg .= ' during self creation';
7780: }
7781: my $changed;
7782: if ($newuser) {
7783: $changed = 1;
7784: } else {
7785: foreach my $field (@fields) {
7786: if ($names{$field} ne $oldnames{$field}) {
7787: $changed = 1;
7788: last;
7789: }
7790: }
7791: }
7792: unless ($changed) {
7793: $logmsg = 'No changes in user information needed for: '.$logmsg;
7794: &logthis($logmsg);
7795: return 'ok';
7796: }
7797: my $reply = &put('environment', \%names, $udom,$uname);
7798: if ($reply ne 'ok') {
7799: return 'error: '.$reply;
7800: }
7801: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7802: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7803: }
7804: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7805: &devalidate_cache_new('namescache',$uname.':'.$udom);
7806: $logmsg = 'Success modifying user '.$logmsg;
7807: &logthis($logmsg);
7808: return 'ok';
7809: }
7810:
7811: # -------------------------------------------------------------- Modify student
7812:
7813: sub modifystudent {
7814: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
7815: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
7816: $selfenroll,$context,$inststatus)=@_;
7817: if (!$cid) {
7818: unless ($cid=$env{'request.course.id'}) {
7819: return 'not_in_class';
7820: }
7821: }
7822: # --------------------------------------------------------------- Make the user
7823: my $reply=&modifyuser
7824: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
7825: $desiredhome,$email,$inststatus);
7826: unless ($reply eq 'ok') { return $reply; }
7827: # This will cause &modify_student_enrollment to get the uid from the
7828: # students environment
7829: $uid = undef if (!$forceid);
7830: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
7831: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
7832: return $reply;
7833: }
7834:
7835: sub modify_student_enrollment {
7836: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
7837: my ($cdom,$cnum,$chome);
7838: if (!$cid) {
7839: unless ($cid=$env{'request.course.id'}) {
7840: return 'not_in_class';
7841: }
7842: $cdom=$env{'course.'.$cid.'.domain'};
7843: $cnum=$env{'course.'.$cid.'.num'};
7844: } else {
7845: ($cdom,$cnum)=split(/_/,$cid);
7846: }
7847: $chome=$env{'course.'.$cid.'.home'};
7848: if (!$chome) {
7849: $chome=&homeserver($cnum,$cdom);
7850: }
7851: if (!$chome) { return 'unknown_course'; }
7852: # Make sure the user exists
7853: my $uhome=&homeserver($uname,$udom);
7854: if (($uhome eq '') || ($uhome eq 'no_host')) {
7855: return 'error: no such user';
7856: }
7857: # Get student data if we were not given enough information
7858: if (!defined($first) || $first eq '' ||
7859: !defined($last) || $last eq '' ||
7860: !defined($uid) || $uid eq '' ||
7861: !defined($middle) || $middle eq '' ||
7862: !defined($gene) || $gene eq '') {
7863: # They did not supply us with enough data to enroll the student, so
7864: # we need to pick up more information.
7865: my %tmp = &get('environment',
7866: ['firstname','middlename','lastname', 'generation','id']
7867: ,$udom,$uname);
7868:
7869: #foreach my $key (keys(%tmp)) {
7870: # &logthis("key $key = ".$tmp{$key});
7871: #}
7872: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7873: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7874: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
7875: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
7876: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7877: }
7878: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
7879: my $user = "$uname:$udom";
7880: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
7881: my $reply=cput('classlist',
7882: {$user =>
7883: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
7884: $cdom,$cnum);
7885: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7886: &devalidate_getsection_cache($udom,$uname,$cid);
7887: } else {
7888: return 'error: '.$reply;
7889: }
7890: # Add student role to user
7891: my $uurl='/'.$cid;
7892: $uurl=~s/\_/\//g;
7893: if ($usec) {
7894: $uurl.='/'.$usec;
7895: }
7896: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7897: $selfenroll,$context);
7898: if ($result ne 'ok') {
7899: if ($old_entry{$user} ne '') {
7900: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7901: } else {
7902: $reply = &del('classlist',[$user],$cdom,$cnum);
7903: }
7904: }
7905: return $result;
7906: }
7907:
7908: sub format_name {
7909: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7910: my $name;
7911: if ($first ne 'lastname') {
7912: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7913: } else {
7914: if ($lastname=~/\S/) {
7915: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7916: $name=~s/\s+,/,/;
7917: } else {
7918: $name.= $firstname.' '.$middlename.' '.$generation;
7919: }
7920: }
7921: $name=~s/^\s+//;
7922: $name=~s/\s+$//;
7923: $name=~s/\s+/ /g;
7924: return $name;
7925: }
7926:
7927: # ------------------------------------------------- Write to course preferences
7928:
7929: sub writecoursepref {
7930: my ($courseid,%prefs)=@_;
7931: $courseid=~s/^\///;
7932: $courseid=~s/\_/\//g;
7933: my ($cdomain,$cnum)=split(/\//,$courseid);
7934: my $chome=homeserver($cnum,$cdomain);
7935: if (($chome eq '') || ($chome eq 'no_host')) {
7936: return 'error: no such course';
7937: }
7938: my $cstring='';
7939: foreach my $pref (keys(%prefs)) {
7940: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
7941: }
7942: $cstring=~s/\&$//;
7943: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7944: }
7945:
7946: # ---------------------------------------------------------- Make/modify course
7947:
7948: sub createcourse {
7949: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
7950: $course_owner,$crstype,$cnum,$context,$category)=@_;
7951: $url=&declutter($url);
7952: my $cid='';
7953: if ($context eq 'requestcourses') {
7954: my $can_create = 0;
7955: my ($ownername,$ownerdom) = split(':',$course_owner);
7956: if ($udom eq $ownerdom) {
7957: if (&usertools_access($ownername,$ownerdom,$category,undef,
7958: $context)) {
7959: $can_create = 1;
7960: }
7961: } else {
7962: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7963: $category);
7964: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7965: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7966: if (@curr > 0) {
7967: my @options = qw(approval validate autolimit);
7968: my $optregex = join('|',@options);
7969: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7970: $can_create = 1;
7971: }
7972: }
7973: }
7974: }
7975: if ($can_create) {
7976: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7977: unless (&allowed('ccc',$udom)) {
7978: return 'refused';
7979: }
7980: }
7981: } else {
7982: return 'refused';
7983: }
7984: } elsif (!&allowed('ccc',$udom)) {
7985: return 'refused';
7986: }
7987: # --------------------------------------------------------------- Get Unique ID
7988: my $uname;
7989: if ($cnum =~ /^$match_courseid$/) {
7990: my $chome=&homeserver($cnum,$udom,'true');
7991: if (($chome eq '') || ($chome eq 'no_host')) {
7992: $uname = $cnum;
7993: } else {
7994: $uname = &generate_coursenum($udom,$crstype);
7995: }
7996: } else {
7997: $uname = &generate_coursenum($udom,$crstype);
7998: }
7999: return $uname if ($uname =~ /^error/);
8000: # -------------------------------------------------- Check supplied server name
8001: if (!defined($course_server)) {
8002: if (defined(&domain($udom,'primary'))) {
8003: $course_server = &domain($udom,'primary');
8004: } else {
8005: $course_server = $env{'user.home'};
8006: }
8007: }
8008: my %host_servers =
8009: &Apache::lonnet::get_servers($udom,'library');
8010: unless ($host_servers{$course_server}) {
8011: return 'error: invalid home server for course: '.$course_server;
8012: }
8013: # ------------------------------------------------------------- Make the course
8014: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
8015: $course_server);
8016: unless ($reply eq 'ok') { return 'error: '.$reply; }
8017: my $uhome=&homeserver($uname,$udom,'true');
8018: if (($uhome eq '') || ($uhome eq 'no_host')) {
8019: return 'error: no such course';
8020: }
8021: # ----------------------------------------------------------------- Course made
8022: # log existence
8023: my $now = time;
8024: my $newcourse = {
8025: $udom.'_'.$uname => {
8026: description => $description,
8027: inst_code => $inst_code,
8028: owner => $course_owner,
8029: type => $crstype,
8030: creator => $env{'user.name'}.':'.
8031: $env{'user.domain'},
8032: created => $now,
8033: context => $context,
8034: },
8035: };
8036: &courseidput($udom,$newcourse,$uhome,'notime');
8037: # set toplevel url
8038: my $topurl=$url;
8039: unless ($nonstandard) {
8040: # ------------------------------------------ For standard courses, make top url
8041: my $mapurl=&clutter($url);
8042: if ($mapurl eq '/res/') { $mapurl=''; }
8043: $env{'form.initmap'}=(<<ENDINITMAP);
8044: <map>
8045: <resource id="1" type="start"></resource>
8046: <resource id="2" src="$mapurl"></resource>
8047: <resource id="3" type="finish"></resource>
8048: <link index="1" from="1" to="2"></link>
8049: <link index="2" from="2" to="3"></link>
8050: </map>
8051: ENDINITMAP
8052: $topurl=&declutter(
8053: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
8054: );
8055: }
8056: # ----------------------------------------------------------- Write preferences
8057: &writecoursepref($udom.'_'.$uname,
8058: ('description' => $description,
8059: 'url' => $topurl,
8060: 'internal.creator' => $env{'user.name'}.':'.
8061: $env{'user.domain'},
8062: 'internal.created' => $now,
8063: 'internal.creationcontext' => $context)
8064: );
8065: return '/'.$udom.'/'.$uname;
8066: }
8067:
8068: # ------------------------------------------------------------------- Create ID
8069: sub generate_coursenum {
8070: my ($udom,$crstype) = @_;
8071: my $domdesc = &domain($udom);
8072: return 'error: invalid domain' if ($domdesc eq '');
8073: my $first;
8074: if ($crstype eq 'Community') {
8075: $first = '0';
8076: } else {
8077: $first = int(1+rand(9));
8078: }
8079: my $uname=$first.
8080: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8081: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8082: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8083: # ----------------------------------------------- Make sure that does not exist
8084: my $uhome=&homeserver($uname,$udom,'true');
8085: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8086: if ($crstype eq 'Community') {
8087: $first = '0';
8088: } else {
8089: $first = int(1+rand(9));
8090: }
8091: $uname=$first.
8092: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8093: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8094: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8095: $uhome=&homeserver($uname,$udom,'true');
8096: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8097: return 'error: unable to generate unique course-ID';
8098: }
8099: }
8100: return $uname;
8101: }
8102:
8103: sub is_course {
8104: my ($cdom, $cnum) = scalar(@_) == 1 ?
8105: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8106:
8107: return unless $cdom and $cnum;
8108:
8109: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8110: '.');
8111:
8112: return unless exists($courses{$cdom.'_'.$cnum});
8113: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
8114: }
8115:
8116: sub store_userdata {
8117: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
8118: my $result;
8119: if ($datakey ne '') {
8120: if (ref($storehash) eq 'HASH') {
8121: if ($udom eq '' || $uname eq '') {
8122: $udom = $env{'user.domain'};
8123: $uname = $env{'user.name'};
8124: }
8125: my $uhome=&homeserver($uname,$udom);
8126: if (($uhome eq '') || ($uhome eq 'no_host')) {
8127: $result = 'error: no_host';
8128: } else {
8129: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8130: $storehash->{'host'} = $perlvar{'lonHostID'};
8131:
8132: my $namevalue='';
8133: foreach my $key (keys(%{$storehash})) {
8134: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8135: }
8136: $namevalue=~s/\&$//;
8137: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8138: $namevalue,$uhome);
8139: }
8140: } else {
8141: $result = 'error: data to store was not a hash reference';
8142: }
8143: } else {
8144: $result= 'error: invalid requestkey';
8145: }
8146: return $result;
8147: }
8148:
8149: # ---------------------------------------------------------- Assign Custom Role
8150:
8151: sub assigncustomrole {
8152: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
8153: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
8154: $end,$start,$deleteflag,$selfenroll,$context);
8155: }
8156:
8157: # ----------------------------------------------------------------- Revoke Role
8158:
8159: sub revokerole {
8160: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
8161: my $now=time;
8162: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
8163: }
8164:
8165: # ---------------------------------------------------------- Revoke Custom Role
8166:
8167: sub revokecustomrole {
8168: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
8169: my $now=time;
8170: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
8171: $deleteflag,$selfenroll,$context);
8172: }
8173:
8174: # ------------------------------------------------------------ Disk usage
8175: sub diskusage {
8176: my ($udom,$uname,$directorypath,$getpropath)=@_;
8177: $directorypath =~ s/\/$//;
8178: my $listing=&reply('du2:'.&escape($directorypath).':'
8179: .&escape($getpropath).':'.&escape($uname).':'
8180: .&escape($udom),homeserver($uname,$udom));
8181: if ($listing eq 'unknown_cmd') {
8182: if ($getpropath) {
8183: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8184: }
8185: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8186: }
8187: return $listing;
8188: }
8189:
8190: sub is_locked {
8191: my ($file_name, $domain, $user, $which) = @_;
8192: my @check;
8193: my $is_locked;
8194: push (@check,$file_name);
8195: my %locked = &get('file_permissions',\@check,
8196: $env{'user.domain'},$env{'user.name'});
8197: my ($tmp)=keys(%locked);
8198: if ($tmp=~/^error:/) { undef(%locked); }
8199:
8200: if (ref($locked{$file_name}) eq 'ARRAY') {
8201: $is_locked = 'false';
8202: foreach my $entry (@{$locked{$file_name}}) {
8203: if (ref($entry) eq 'ARRAY') {
8204: $is_locked = 'true';
8205: if (ref($which) eq 'ARRAY') {
8206: push(@{$which},$entry);
8207: } else {
8208: last;
8209: }
8210: }
8211: }
8212: } else {
8213: $is_locked = 'false';
8214: }
8215: return $is_locked;
8216: }
8217:
8218: sub declutter_portfile {
8219: my ($file) = @_;
8220: $file =~ s{^(/portfolio/|portfolio/)}{/};
8221: return $file;
8222: }
8223:
8224: # ------------------------------------------------------------- Mark as Read Only
8225:
8226: sub mark_as_readonly {
8227: my ($domain,$user,$files,$what) = @_;
8228: my %current_permissions = &dump('file_permissions',$domain,$user);
8229: my ($tmp)=keys(%current_permissions);
8230: if ($tmp=~/^error:/) { undef(%current_permissions); }
8231: foreach my $file (@{$files}) {
8232: $file = &declutter_portfile($file);
8233: push(@{$current_permissions{$file}},$what);
8234: }
8235: &put('file_permissions',\%current_permissions,$domain,$user);
8236: return;
8237: }
8238:
8239: # ------------------------------------------------------------Save Selected Files
8240:
8241: sub save_selected_files {
8242: my ($user, $path, @files) = @_;
8243: my $filename = $user."savedfiles";
8244: my @other_files = &files_not_in_path($user, $path);
8245: open (OUT, '>'.$tmpdir.$filename);
8246: foreach my $file (@files) {
8247: print (OUT $env{'form.currentpath'}.$file."\n");
8248: }
8249: foreach my $file (@other_files) {
8250: print (OUT $file."\n");
8251: }
8252: close (OUT);
8253: return 'ok';
8254: }
8255:
8256: sub clear_selected_files {
8257: my ($user) = @_;
8258: my $filename = $user."savedfiles";
8259: open (OUT, '>'.LONCAPA::tempdir().$filename);
8260: print (OUT undef);
8261: close (OUT);
8262: return ("ok");
8263: }
8264:
8265: sub files_in_path {
8266: my ($user, $path) = @_;
8267: my $filename = $user."savedfiles";
8268: my %return_files;
8269: open (IN, '<'.LONCAPA::tempdir().$filename);
8270: while (my $line_in = <IN>) {
8271: chomp ($line_in);
8272: my @paths_and_file = split (m!/!, $line_in);
8273: my $file_part = pop (@paths_and_file);
8274: my $path_part = join ('/', @paths_and_file);
8275: $path_part.='/';
8276: my $path_and_file = $path_part.$file_part;
8277: if ($path_part eq $path) {
8278: $return_files{$file_part}= 'selected';
8279: }
8280: }
8281: close (IN);
8282: return (\%return_files);
8283: }
8284:
8285: # called in portfolio select mode, to show files selected NOT in current directory
8286: sub files_not_in_path {
8287: my ($user, $path) = @_;
8288: my $filename = $user."savedfiles";
8289: my @return_files;
8290: my $path_part;
8291: open(IN, '<'.LONCAPA::.$filename);
8292: while (my $line = <IN>) {
8293: #ok, I know it's clunky, but I want it to work
8294: my @paths_and_file = split(m|/|, $line);
8295: my $file_part = pop(@paths_and_file);
8296: chomp($file_part);
8297: my $path_part = join('/', @paths_and_file);
8298: $path_part .= '/';
8299: my $path_and_file = $path_part.$file_part;
8300: if ($path_part ne $path) {
8301: push(@return_files, ($path_and_file));
8302: }
8303: }
8304: close(OUT);
8305: return (@return_files);
8306: }
8307:
8308: #----------------------------------------------Get portfolio file permissions
8309:
8310: sub get_portfile_permissions {
8311: my ($domain,$user) = @_;
8312: my %current_permissions = &dump('file_permissions',$domain,$user);
8313: my ($tmp)=keys(%current_permissions);
8314: if ($tmp=~/^error:/) { undef(%current_permissions); }
8315: return \%current_permissions;
8316: }
8317:
8318: #---------------------------------------------Get portfolio file access controls
8319:
8320: sub get_access_controls {
8321: my ($current_permissions,$group,$file) = @_;
8322: my %access;
8323: my $real_file = $file;
8324: $file =~ s/\.meta$//;
8325: if (defined($file)) {
8326: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8327: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
8328: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
8329: }
8330: }
8331: } else {
8332: foreach my $key (keys(%{$current_permissions})) {
8333: if ($key =~ /\0accesscontrol$/) {
8334: if (defined($group)) {
8335: if ($key !~ m-^\Q$group\E/-) {
8336: next;
8337: }
8338: }
8339: my ($fullpath) = split(/\0/,$key);
8340: if (ref($$current_permissions{$key}) eq 'HASH') {
8341: foreach my $control (keys(%{$$current_permissions{$key}})) {
8342: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8343: }
8344: }
8345: }
8346: }
8347: }
8348: return %access;
8349: }
8350:
8351: sub modify_access_controls {
8352: my ($file_name,$changes,$domain,$user)=@_;
8353: my ($outcome,$deloutcome);
8354: my %store_permissions;
8355: my %new_values;
8356: my %new_control;
8357: my %translation;
8358: my @deletions = ();
8359: my $now = time;
8360: if (exists($$changes{'activate'})) {
8361: if (ref($$changes{'activate'}) eq 'HASH') {
8362: my @newitems = sort(keys(%{$$changes{'activate'}}));
8363: my $numnew = scalar(@newitems);
8364: for (my $i=0; $i<$numnew; $i++) {
8365: my $newkey = $newitems[$i];
8366: my $newid = &Apache::loncommon::get_cgi_id();
8367: if ($newkey =~ /^\d+:/) {
8368: $newkey =~ s/^(\d+)/$newid/;
8369: $translation{$1} = $newid;
8370: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8371: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8372: $translation{$1} = $newid;
8373: }
8374: $new_values{$file_name."\0".$newkey} =
8375: $$changes{'activate'}{$newitems[$i]};
8376: $new_control{$newkey} = $now;
8377: }
8378: }
8379: }
8380: my %todelete;
8381: my %changed_items;
8382: foreach my $action ('delete','update') {
8383: if (exists($$changes{$action})) {
8384: if (ref($$changes{$action}) eq 'HASH') {
8385: foreach my $key (keys(%{$$changes{$action}})) {
8386: my ($itemnum) = ($key =~ /^([^:]+):/);
8387: if ($action eq 'delete') {
8388: $todelete{$itemnum} = 1;
8389: } else {
8390: $changed_items{$itemnum} = $key;
8391: }
8392: }
8393: }
8394: }
8395: }
8396: # get lock on access controls for file.
8397: my $lockhash = {
8398: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8399: ':'.$env{'user.domain'},
8400: };
8401: my $tries = 0;
8402: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8403:
8404: while (($gotlock ne 'ok') && $tries <3) {
8405: $tries ++;
8406: sleep 1;
8407: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8408: }
8409: if ($gotlock eq 'ok') {
8410: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8411: my ($tmp)=keys(%curr_permissions);
8412: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8413: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8414: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8415: if (ref($curr_controls) eq 'HASH') {
8416: foreach my $control_item (keys(%{$curr_controls})) {
8417: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8418: if (defined($todelete{$itemnum})) {
8419: push(@deletions,$file_name."\0".$control_item);
8420: } else {
8421: if (defined($changed_items{$itemnum})) {
8422: $new_control{$changed_items{$itemnum}} = $now;
8423: push(@deletions,$file_name."\0".$control_item);
8424: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8425: } else {
8426: $new_control{$control_item} = $$curr_controls{$control_item};
8427: }
8428: }
8429: }
8430: }
8431: }
8432: my ($group);
8433: if (&is_course($domain,$user)) {
8434: ($group,my $file) = split(/\//,$file_name,2);
8435: }
8436: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8437: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8438: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8439: # remove lock
8440: my @del_lock = ($file_name."\0".'locked_access_records');
8441: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
8442: my $sqlresult =
8443: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
8444: $group);
8445: } else {
8446: $outcome = "error: could not obtain lockfile\n";
8447: }
8448: return ($outcome,$deloutcome,\%new_values,\%translation);
8449: }
8450:
8451: sub make_public_indefinitely {
8452: my ($requrl) = @_;
8453: my $now = time;
8454: my $action = 'activate';
8455: my $aclnum = 0;
8456: if (&is_portfolio_url($requrl)) {
8457: my (undef,$udom,$unum,$file_name,$group) =
8458: &parse_portfolio_url($requrl);
8459: my $current_perms = &get_portfile_permissions($udom,$unum);
8460: my %access_controls = &get_access_controls($current_perms,
8461: $group,$file_name);
8462: foreach my $key (keys(%{$access_controls{$file_name}})) {
8463: my ($num,$scope,$end,$start) =
8464: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8465: if ($scope eq 'public') {
8466: if ($start <= $now && $end == 0) {
8467: $action = 'none';
8468: } else {
8469: $action = 'update';
8470: $aclnum = $num;
8471: }
8472: last;
8473: }
8474: }
8475: if ($action eq 'none') {
8476: return 'ok';
8477: } else {
8478: my %changes;
8479: my $newend = 0;
8480: my $newstart = $now;
8481: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8482: $changes{$action}{$newkey} = {
8483: type => 'public',
8484: time => {
8485: start => $newstart,
8486: end => $newend,
8487: },
8488: };
8489: my ($outcome,$deloutcome,$new_values,$translation) =
8490: &modify_access_controls($file_name,\%changes,$udom,$unum);
8491: return $outcome;
8492: }
8493: } else {
8494: return 'invalid';
8495: }
8496: }
8497:
8498: #------------------------------------------------------Get Marked as Read Only
8499:
8500: sub get_marked_as_readonly {
8501: my ($domain,$user,$what,$group) = @_;
8502: my $current_permissions = &get_portfile_permissions($domain,$user);
8503: my @readonly_files;
8504: my $cmp1=$what;
8505: if (ref($what)) { $cmp1=join('',@{$what}) };
8506: while (my ($file_name,$value) = each(%{$current_permissions})) {
8507: if (defined($group)) {
8508: if ($file_name !~ m-^\Q$group\E/-) {
8509: next;
8510: }
8511: }
8512: if (ref($value) eq "ARRAY"){
8513: foreach my $stored_what (@{$value}) {
8514: my $cmp2=$stored_what;
8515: if (ref($stored_what) eq 'ARRAY') {
8516: $cmp2=join('',@{$stored_what});
8517: }
8518: if ($cmp1 eq $cmp2) {
8519: push(@readonly_files, $file_name);
8520: last;
8521: } elsif (!defined($what)) {
8522: push(@readonly_files, $file_name);
8523: last;
8524: }
8525: }
8526: }
8527: }
8528: return @readonly_files;
8529: }
8530: #-----------------------------------------------------------Get Marked as Read Only Hash
8531:
8532: sub get_marked_as_readonly_hash {
8533: my ($current_permissions,$group,$what) = @_;
8534: my %readonly_files;
8535: while (my ($file_name,$value) = each(%{$current_permissions})) {
8536: if (defined($group)) {
8537: if ($file_name !~ m-^\Q$group\E/-) {
8538: next;
8539: }
8540: }
8541: if (ref($value) eq "ARRAY"){
8542: foreach my $stored_what (@{$value}) {
8543: if (ref($stored_what) eq 'ARRAY') {
8544: foreach my $lock_descriptor(@{$stored_what}) {
8545: if ($lock_descriptor eq 'graded') {
8546: $readonly_files{$file_name} = 'graded';
8547: } elsif ($lock_descriptor eq 'handback') {
8548: $readonly_files{$file_name} = 'handback';
8549: } else {
8550: if (!exists($readonly_files{$file_name})) {
8551: $readonly_files{$file_name} = 'locked';
8552: }
8553: }
8554: }
8555: }
8556: }
8557: }
8558: }
8559: return %readonly_files;
8560: }
8561: # ------------------------------------------------------------ Unmark as Read Only
8562:
8563: sub unmark_as_readonly {
8564: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8565: # for portfolio submissions, $what contains [$symb,$crsid]
8566: my ($domain,$user,$what,$file_name,$group) = @_;
8567: $file_name = &declutter_portfile($file_name);
8568: my $symb_crs = $what;
8569: if (ref($what)) { $symb_crs=join('',@$what); }
8570: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
8571: my ($tmp)=keys(%current_permissions);
8572: if ($tmp=~/^error:/) { undef(%current_permissions); }
8573: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
8574: foreach my $file (@readonly_files) {
8575: my $clean_file = &declutter_portfile($file);
8576: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
8577: my $current_locks = $current_permissions{$file};
8578: my @new_locks;
8579: my @del_keys;
8580: if (ref($current_locks) eq "ARRAY"){
8581: foreach my $locker (@{$current_locks}) {
8582: my $compare=$locker;
8583: if (ref($locker) eq 'ARRAY') {
8584: $compare=join('',@{$locker});
8585: if ($compare ne $symb_crs) {
8586: push(@new_locks, $locker);
8587: }
8588: }
8589: }
8590: if (scalar(@new_locks) > 0) {
8591: $current_permissions{$file} = \@new_locks;
8592: } else {
8593: push(@del_keys, $file);
8594: &del('file_permissions',\@del_keys, $domain, $user);
8595: delete($current_permissions{$file});
8596: }
8597: }
8598: }
8599: &put('file_permissions',\%current_permissions,$domain,$user);
8600: return;
8601: }
8602:
8603: # ------------------------------------------------------------ Directory lister
8604:
8605: sub dirlist {
8606: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
8607: $uri=~s/^\///;
8608: $uri=~s/\/$//;
8609: my ($udom, $uname);
8610: if ($getuserdir) {
8611: $udom = $userdomain;
8612: $uname = $username;
8613: } else {
8614: (undef,$udom,$uname)=split(/\//,$uri);
8615: if(defined($userdomain)) {
8616: $udom = $userdomain;
8617: }
8618: if(defined($username)) {
8619: $uname = $username;
8620: }
8621: }
8622: my ($dirRoot,$listing,@listing_results);
8623:
8624: $dirRoot = $perlvar{'lonDocRoot'};
8625: if (defined($getpropath)) {
8626: $dirRoot = &propath($udom,$uname);
8627: $dirRoot =~ s/\/$//;
8628: } elsif (defined($getuserdir)) {
8629: my $subdir=$uname.'__';
8630: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8631: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8632: ."/$udom/$subdir/$uname";
8633: } elsif (defined($alternateRoot)) {
8634: $dirRoot = $alternateRoot;
8635: }
8636:
8637: if($udom) {
8638: if($uname) {
8639: my $uhome = &homeserver($uname,$udom);
8640: if ($uhome eq 'no_host') {
8641: return ([],'no_host');
8642: }
8643: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
8644: .$getuserdir.':'.&escape($dirRoot)
8645: .':'.&escape($uname).':'.&escape($udom),$uhome);
8646: if ($listing eq 'unknown_cmd') {
8647: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
8648: } else {
8649: @listing_results = map { &unescape($_); } split(/:/,$listing);
8650: }
8651: if ($listing eq 'unknown_cmd') {
8652: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
8653: @listing_results = split(/:/,$listing);
8654: } else {
8655: @listing_results = map { &unescape($_); } split(/:/,$listing);
8656: }
8657: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8658: ($listing eq 'rejected') || ($listing eq 'refused') ||
8659: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8660: return ([],$listing);
8661: } else {
8662: return (\@listing_results);
8663: }
8664: } elsif(!$alternateRoot) {
8665: my (%allusers,%listerror);
8666: my %servers = &get_servers($udom,'library');
8667: foreach my $tryserver (keys(%servers)) {
8668: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8669: &escape($udom),$tryserver);
8670: if ($listing eq 'unknown_cmd') {
8671: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8672: $udom, $tryserver);
8673: } else {
8674: @listing_results = map { &unescape($_); } split(/:/,$listing);
8675: }
8676: if ($listing eq 'unknown_cmd') {
8677: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8678: $udom, $tryserver);
8679: @listing_results = split(/:/,$listing);
8680: } else {
8681: @listing_results =
8682: map { &unescape($_); } split(/:/,$listing);
8683: }
8684: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8685: ($listing eq 'rejected') || ($listing eq 'refused') ||
8686: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8687: $listerror{$tryserver} = $listing;
8688: } else {
8689: foreach my $line (@listing_results) {
8690: my ($entry) = split(/&/,$line,2);
8691: $allusers{$entry} = 1;
8692: }
8693: }
8694: }
8695: my @alluserslist=();
8696: foreach my $user (sort(keys(%allusers))) {
8697: push(@alluserslist,$user.'&user');
8698: }
8699: return (\@alluserslist);
8700: } else {
8701: return ([],'missing username');
8702: }
8703: } elsif(!defined($getpropath)) {
8704: my $path = $perlvar{'lonDocRoot'}.'/res/';
8705: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8706: return (\@all_domains);
8707: } else {
8708: return ([],'missing domain');
8709: }
8710: }
8711:
8712: # --------------------------------------------- GetFileTimestamp
8713: # This function utilizes dirlist and returns the date stamp for
8714: # when it was last modified. It will also return an error of -1
8715: # if an error occurs
8716:
8717: sub GetFileTimestamp {
8718: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
8719: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8720: $studentName = &LONCAPA::clean_username($studentName);
8721: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8722: undef,$getuserdir);
8723: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8724: return -1;
8725: }
8726: if (ref($fileref) eq 'ARRAY') {
8727: my @stats = split('&',$fileref->[0]);
8728: # @stats contains first the filename, then the stat output
8729: return $stats[10]; # so this is 10 instead of 9.
8730: } else {
8731: return -1;
8732: }
8733: }
8734:
8735: sub stat_file {
8736: my ($uri) = @_;
8737: $uri = &clutter_with_no_wrapper($uri);
8738:
8739: my ($udom,$uname,$file);
8740: if ($uri =~ m-^/(uploaded|editupload)/-) {
8741: ($udom,$uname,$file) =
8742: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
8743: $file = 'userfiles/'.$file;
8744: }
8745: if ($uri =~ m-^/res/-) {
8746: ($udom,$uname) =
8747: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
8748: $file = $uri;
8749: }
8750:
8751: if (!$udom || !$uname || !$file) {
8752: # unable to handle the uri
8753: return ();
8754: }
8755: my $getpropath;
8756: if ($file =~ /^userfiles\//) {
8757: $getpropath = 1;
8758: }
8759: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8760: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8761: return ();
8762: } else {
8763: if (ref($listref) eq 'ARRAY') {
8764: my @stats = split('&',$listref->[0]);
8765: shift(@stats); #filename is first
8766: return @stats;
8767: }
8768: }
8769: return ();
8770: }
8771:
8772: # -------------------------------------------------------- Value of a Condition
8773:
8774: # gets the value of a specific preevaluated condition
8775: # stored in the string $env{user.state.<cid>}
8776: # or looks up a condition reference in the bighash and if if hasn't
8777: # already been evaluated recurses into docondval to get the value of
8778: # the condition, then memoizing it to
8779: # $env{user.state.<cid>.<condition>}
8780: sub directcondval {
8781: my $number=shift;
8782: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
8783: &Apache::lonuserstate::evalstate();
8784: }
8785: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8786: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8787: } elsif ($number =~ /^_/) {
8788: my $sub_condition;
8789: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8790: &GDBM_READER(),0640)) {
8791: $sub_condition=$bighash{'conditions'.$number};
8792: untie(%bighash);
8793: }
8794: my $value = &docondval($sub_condition);
8795: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
8796: return $value;
8797: }
8798: if ($env{'user.state.'.$env{'request.course.id'}}) {
8799: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
8800: } else {
8801: return 2;
8802: }
8803: }
8804:
8805: # get the collection of conditions for this resource
8806: sub condval {
8807: my $condidx=shift;
8808: my $allpathcond='';
8809: foreach my $cond (split(/\|/,$condidx)) {
8810: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8811: $allpathcond.=
8812: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8813: }
8814: }
8815: $allpathcond=~s/\|$//;
8816: return &docondval($allpathcond);
8817: }
8818:
8819: #evaluates an expression of conditions
8820: sub docondval {
8821: my ($allpathcond) = @_;
8822: my $result=0;
8823: if ($env{'request.course.id'}
8824: && defined($allpathcond)) {
8825: my $operand='|';
8826: my @stack;
8827: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8828: if ($chunk eq '(') {
8829: push @stack,($operand,$result);
8830: } elsif ($chunk eq ')') {
8831: my $before=pop @stack;
8832: if (pop @stack eq '&') {
8833: $result=$result>$before?$before:$result;
8834: } else {
8835: $result=$result>$before?$result:$before;
8836: }
8837: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8838: $operand=$chunk;
8839: } else {
8840: my $new=directcondval($chunk);
8841: if ($operand eq '&') {
8842: $result=$result>$new?$new:$result;
8843: } else {
8844: $result=$result>$new?$result:$new;
8845: }
8846: }
8847: }
8848: }
8849: return $result;
8850: }
8851:
8852: # ---------------------------------------------------- Devalidate courseresdata
8853:
8854: sub devalidatecourseresdata {
8855: my ($coursenum,$coursedomain)=@_;
8856: my $hashid=$coursenum.':'.$coursedomain;
8857: &devalidate_cache_new('courseres',$hashid);
8858: }
8859:
8860:
8861: # --------------------------------------------------- Course Resourcedata Query
8862: #
8863: # Parameters:
8864: # $coursenum - Number of the course.
8865: # $coursedomain - Domain at which the course was created.
8866: # Returns:
8867: # A hash of the course parameters along (I think) with timestamps
8868: # and version info.
8869:
8870: sub get_courseresdata {
8871: my ($coursenum,$coursedomain)=@_;
8872: my $coursehom=&homeserver($coursenum,$coursedomain);
8873: my $hashid=$coursenum.':'.$coursedomain;
8874: my ($result,$cached)=&is_cached_new('courseres',$hashid);
8875: my %dumpreply;
8876: unless (defined($cached)) {
8877: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
8878: $result=\%dumpreply;
8879: my ($tmp) = keys(%dumpreply);
8880: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
8881: &do_cache_new('courseres',$hashid,$result,600);
8882: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8883: return $tmp;
8884: } elsif ($tmp =~ /^(error)/) {
8885: $result=undef;
8886: &do_cache_new('courseres',$hashid,$result,600);
8887: }
8888: }
8889: return $result;
8890: }
8891:
8892: sub devalidateuserresdata {
8893: my ($uname,$udom)=@_;
8894: my $hashid="$udom:$uname";
8895: &devalidate_cache_new('userres',$hashid);
8896: }
8897:
8898: sub get_userresdata {
8899: my ($uname,$udom)=@_;
8900: #most student don\'t have any data set, check if there is some data
8901: if (&EXT_cache_status($udom,$uname)) { return undef; }
8902:
8903: my $hashid="$udom:$uname";
8904: my ($result,$cached)=&is_cached_new('userres',$hashid);
8905: if (!defined($cached)) {
8906: my %resourcedata=&dump('resourcedata',$udom,$uname);
8907: $result=\%resourcedata;
8908: &do_cache_new('userres',$hashid,$result,600);
8909: }
8910: my ($tmp)=keys(%$result);
8911: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8912: return $result;
8913: }
8914: #error 2 occurs when the .db doesn't exist
8915: if ($tmp!~/error: 2 /) {
8916: &logthis("<font color=\"blue\">WARNING:".
8917: " Trying to get resource data for ".
8918: $uname." at ".$udom.": ".
8919: $tmp."</font>");
8920: } elsif ($tmp=~/error: 2 /) {
8921: #&EXT_cache_set($udom,$uname);
8922: &do_cache_new('userres',$hashid,undef,600);
8923: undef($tmp); # not really an error so don't send it back
8924: }
8925: return $tmp;
8926: }
8927: #----------------------------------------------- resdata - return resource data
8928: # Purpose:
8929: # Return resource data for either users or for a course.
8930: # Parameters:
8931: # $name - Course/user name.
8932: # $domain - Name of the domain the user/course is registered on.
8933: # $type - Type of thing $name is (must be 'course' or 'user'
8934: # @which - Array of names of resources desired.
8935: # Returns:
8936: # The value of the first reasource in @which that is found in the
8937: # resource hash.
8938: # Exceptional Conditions:
8939: # If the $type passed in is not valid (not the string 'course' or
8940: # 'user', an undefined reference is returned.
8941: # If none of the resources are found, an undef is returned
8942: sub resdata {
8943: my ($name,$domain,$type,@which)=@_;
8944: my $result;
8945: if ($type eq 'course') {
8946: $result=&get_courseresdata($name,$domain);
8947: } elsif ($type eq 'user') {
8948: $result=&get_userresdata($name,$domain);
8949: }
8950: if (!ref($result)) { return $result; }
8951: foreach my $item (@which) {
8952: if (defined($result->{$item->[0]})) {
8953: return [$result->{$item->[0]},$item->[1]];
8954: }
8955: }
8956: return undef;
8957: }
8958:
8959: #
8960: # EXT resource caching routines
8961: #
8962:
8963: sub clear_EXT_cache_status {
8964: &delenv('cache.EXT.');
8965: }
8966:
8967: sub EXT_cache_status {
8968: my ($target_domain,$target_user) = @_;
8969: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8970: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
8971: # We know already the user has no data
8972: return 1;
8973: } else {
8974: return 0;
8975: }
8976: }
8977:
8978: sub EXT_cache_set {
8979: my ($target_domain,$target_user) = @_;
8980: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
8981: #&appenv({$cachename => time});
8982: }
8983:
8984: # --------------------------------------------------------- Value of a Variable
8985: sub EXT {
8986:
8987: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
8988: unless ($varname) { return ''; }
8989: #get real user name/domain, courseid and symb
8990: my $courseid;
8991: my $publicuser;
8992: if ($symbparm) {
8993: $symbparm=&get_symb_from_alias($symbparm);
8994: }
8995: if (!($uname && $udom)) {
8996: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
8997: if (!$symbparm) { $symbparm=$cursymb; }
8998: } else {
8999: $courseid=$env{'request.course.id'};
9000: }
9001: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9002: my $rest;
9003: if (defined($therest[0])) {
9004: $rest=join('.',@therest);
9005: } else {
9006: $rest='';
9007: }
9008:
9009: my $qualifierrest=$qualifier;
9010: if ($rest) { $qualifierrest.='.'.$rest; }
9011: my $spacequalifierrest=$space;
9012: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
9013: if ($realm eq 'user') {
9014: # --------------------------------------------------------------- user.resource
9015: if ($space eq 'resource') {
9016: if ( (defined($Apache::lonhomework::parsing_a_problem)
9017: || defined($Apache::lonhomework::parsing_a_task))
9018: &&
9019: ($symbparm eq &symbread()) ) {
9020: # if we are in the middle of processing the resource the
9021: # get the value we are planning on committing
9022: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9023: return $Apache::lonhomework::results{$qualifierrest};
9024: } else {
9025: return $Apache::lonhomework::history{$qualifierrest};
9026: }
9027: } else {
9028: my %restored;
9029: if ($publicuser || $env{'request.state'} eq 'construct') {
9030: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9031: } else {
9032: %restored=&restore($symbparm,$courseid,$udom,$uname);
9033: }
9034: return $restored{$qualifierrest};
9035: }
9036: # ----------------------------------------------------------------- user.access
9037: } elsif ($space eq 'access') {
9038: # FIXME - not supporting calls for a specific user
9039: return &allowed($qualifier,$rest);
9040: # ------------------------------------------ user.preferences, user.environment
9041: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
9042: if (($uname eq $env{'user.name'}) &&
9043: ($udom eq $env{'user.domain'})) {
9044: return $env{join('.',('environment',$qualifierrest))};
9045: } else {
9046: my %returnhash;
9047: if (!$publicuser) {
9048: %returnhash=&userenvironment($udom,$uname,
9049: $qualifierrest);
9050: }
9051: return $returnhash{$qualifierrest};
9052: }
9053: # ----------------------------------------------------------------- user.course
9054: } elsif ($space eq 'course') {
9055: # FIXME - not supporting calls for a specific user
9056: return $env{join('.',('request.course',$qualifier))};
9057: # ------------------------------------------------------------------- user.role
9058: } elsif ($space eq 'role') {
9059: # FIXME - not supporting calls for a specific user
9060: my ($role,$where)=split(/\./,$env{'request.role'});
9061: if ($qualifier eq 'value') {
9062: return $role;
9063: } elsif ($qualifier eq 'extent') {
9064: return $where;
9065: }
9066: # ----------------------------------------------------------------- user.domain
9067: } elsif ($space eq 'domain') {
9068: return $udom;
9069: # ------------------------------------------------------------------- user.name
9070: } elsif ($space eq 'name') {
9071: return $uname;
9072: # ---------------------------------------------------- Any other user namespace
9073: } else {
9074: my %reply;
9075: if (!$publicuser) {
9076: %reply=&get($space,[$qualifierrest],$udom,$uname);
9077: }
9078: return $reply{$qualifierrest};
9079: }
9080: } elsif ($realm eq 'query') {
9081: # ---------------------------------------------- pull stuff out of query string
9082: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9083: [$spacequalifierrest]);
9084: return $env{'form.'.$spacequalifierrest};
9085: } elsif ($realm eq 'request') {
9086: # ------------------------------------------------------------- request.browser
9087: if ($space eq 'browser') {
9088: return $env{'browser.'.$qualifier};
9089: # ------------------------------------------------------------ request.filename
9090: } else {
9091: return $env{'request.'.$spacequalifierrest};
9092: }
9093: } elsif ($realm eq 'course') {
9094: # ---------------------------------------------------------- course.description
9095: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
9096: } elsif ($realm eq 'resource') {
9097:
9098: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
9099: if (!$symbparm) { $symbparm=&symbread(); }
9100: }
9101:
9102: if ($space eq 'title') {
9103: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9104: return &gettitle($symbparm);
9105: }
9106:
9107: if ($space eq 'map') {
9108: my ($map) = &decode_symb($symbparm);
9109: return &symbread($map);
9110: }
9111: if ($space eq 'filename') {
9112: if ($symbparm) {
9113: return &clutter((&decode_symb($symbparm))[2]);
9114: }
9115: return &hreflocation('',$env{'request.filename'});
9116: }
9117:
9118: my ($section, $group, @groups);
9119: my ($courselevelm,$courselevel);
9120: if ($symbparm && defined($courseid) &&
9121: $courseid eq $env{'request.course.id'}) {
9122:
9123: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
9124:
9125: # ----------------------------------------------------- Cascading lookup scheme
9126: my $symbp=$symbparm;
9127: my $mapp=&deversion((&decode_symb($symbp))[0]);
9128:
9129: my $symbparm=$symbp.'.'.$spacequalifierrest;
9130: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9131:
9132: if (($env{'user.name'} eq $uname) &&
9133: ($env{'user.domain'} eq $udom)) {
9134: $section=$env{'request.course.sec'};
9135: @groups = split(/:/,$env{'request.course.groups'});
9136: @groups=&sort_course_groups($courseid,@groups);
9137: } else {
9138: if (! defined($usection)) {
9139: $section=&getsection($udom,$uname,$courseid);
9140: } else {
9141: $section = $usection;
9142: }
9143: @groups = &get_users_groups($udom,$uname,$courseid);
9144: }
9145:
9146: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9147: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9148: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9149:
9150: $courselevel=$courseid.'.'.$spacequalifierrest;
9151: my $courselevelr=$courseid.'.'.$symbparm;
9152: $courselevelm=$courseid.'.'.$mapparm;
9153:
9154: # ----------------------------------------------------------- first, check user
9155:
9156: my $userreply=&resdata($uname,$udom,'user',
9157: ([$courselevelr,'resource'],
9158: [$courselevelm,'map' ],
9159: [$courselevel, 'course' ]));
9160: if (defined($userreply)) { return &get_reply($userreply); }
9161:
9162: # ------------------------------------------------ second, check some of course
9163: my $coursereply;
9164: if (@groups > 0) {
9165: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9166: $mapparm,$spacequalifierrest);
9167: if (defined($coursereply)) { return &get_reply($coursereply); }
9168: }
9169:
9170: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9171: $env{'course.'.$courseid.'.domain'},
9172: 'course',
9173: ([$seclevelr, 'resource'],
9174: [$seclevelm, 'map' ],
9175: [$seclevel, 'course' ],
9176: [$courselevelr,'resource']));
9177: if (defined($coursereply)) { return &get_reply($coursereply); }
9178:
9179: # ------------------------------------------------------ third, check map parms
9180: my %parmhash=();
9181: my $thisparm='';
9182: if (tie(%parmhash,'GDBM_File',
9183: $env{'request.course.fn'}.'_parms.db',
9184: &GDBM_READER(),0640)) {
9185: $thisparm=$parmhash{$symbparm};
9186: untie(%parmhash);
9187: }
9188: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
9189: }
9190: # ------------------------------------------ fourth, look in resource metadata
9191:
9192: $spacequalifierrest=~s/\./\_/;
9193: my $filename;
9194: if (!$symbparm) { $symbparm=&symbread(); }
9195: if ($symbparm) {
9196: $filename=(&decode_symb($symbparm))[2];
9197: } else {
9198: $filename=$env{'request.filename'};
9199: }
9200: my $metadata=&metadata($filename,$spacequalifierrest);
9201: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9202: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
9203: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
9204:
9205: # ---------------------------------------------- fourth, look in rest of course
9206: if ($symbparm && defined($courseid) &&
9207: $courseid eq $env{'request.course.id'}) {
9208: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9209: $env{'course.'.$courseid.'.domain'},
9210: 'course',
9211: ([$courselevelm,'map' ],
9212: [$courselevel, 'course']));
9213: if (defined($coursereply)) { return &get_reply($coursereply); }
9214: }
9215: # ------------------------------------------------------------------ Cascade up
9216: unless ($space eq '0') {
9217: my @parts=split(/_/,$space);
9218: my $id=pop(@parts);
9219: my $part=join('_',@parts);
9220: if ($part eq '') { $part='0'; }
9221: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
9222: $symbparm,$udom,$uname,$section,1);
9223: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
9224: }
9225: if ($recurse) { return undef; }
9226: my $pack_def=&packages_tab_default($filename,$varname);
9227: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
9228: # ---------------------------------------------------- Any other user namespace
9229: } elsif ($realm eq 'environment') {
9230: # ----------------------------------------------------------------- environment
9231: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9232: return $env{'environment.'.$spacequalifierrest};
9233: } else {
9234: if ($uname eq 'anonymous' && $udom eq '') {
9235: return '';
9236: }
9237: my %returnhash=&userenvironment($udom,$uname,
9238: $spacequalifierrest);
9239: return $returnhash{$spacequalifierrest};
9240: }
9241: } elsif ($realm eq 'system') {
9242: # ----------------------------------------------------------------- system.time
9243: if ($space eq 'time') {
9244: return time;
9245: }
9246: } elsif ($realm eq 'server') {
9247: # ----------------------------------------------------------------- system.time
9248: if ($space eq 'name') {
9249: return $ENV{'SERVER_NAME'};
9250: }
9251: }
9252: return '';
9253: }
9254:
9255: sub get_reply {
9256: my ($reply_value) = @_;
9257: if (ref($reply_value) eq 'ARRAY') {
9258: if (wantarray) {
9259: return @$reply_value;
9260: }
9261: return $reply_value->[0];
9262: } else {
9263: return $reply_value;
9264: }
9265: }
9266:
9267: sub check_group_parms {
9268: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9269: my @groupitems = ();
9270: my $resultitem;
9271: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
9272: foreach my $group (@{$groups}) {
9273: foreach my $level (@levels) {
9274: my $item = $courseid.'.['.$group.'].'.$level->[0];
9275: push(@groupitems,[$item,$level->[1]]);
9276: }
9277: }
9278: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9279: $env{'course.'.$courseid.'.domain'},
9280: 'course',@groupitems);
9281: return $coursereply;
9282: }
9283:
9284: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
9285: my ($courseid,@groups) = @_;
9286: @groups = sort(@groups);
9287: return @groups;
9288: }
9289:
9290: sub packages_tab_default {
9291: my ($uri,$varname)=@_;
9292: my (undef,$part,$name)=split(/\./,$varname);
9293:
9294: my (@extension,@specifics,$do_default);
9295: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
9296: my ($pack_type,$pack_part)=split(/_/,$package,2);
9297: if ($pack_type eq 'default') {
9298: $do_default=1;
9299: } elsif ($pack_type eq 'extension') {
9300: push(@extension,[$package,$pack_type,$pack_part]);
9301: } elsif ($pack_part eq $part || $pack_type eq 'part') {
9302: # only look at packages defaults for packages that this id is
9303: push(@specifics,[$package,$pack_type,$pack_part]);
9304: }
9305: }
9306: # first look for a package that matches the requested part id
9307: foreach my $package (@specifics) {
9308: my (undef,$pack_type,$pack_part)=@{$package};
9309: next if ($pack_part ne $part);
9310: if (defined($packagetab{"$pack_type&$name&default"})) {
9311: return $packagetab{"$pack_type&$name&default"};
9312: }
9313: }
9314: # look for any possible matching non extension_ package
9315: foreach my $package (@specifics) {
9316: my (undef,$pack_type,$pack_part)=@{$package};
9317: if (defined($packagetab{"$pack_type&$name&default"})) {
9318: return $packagetab{"$pack_type&$name&default"};
9319: }
9320: if ($pack_type eq 'part') { $pack_part='0'; }
9321: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9322: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
9323: }
9324: }
9325: # look for any posible extension_ match
9326: foreach my $package (@extension) {
9327: my ($package,$pack_type)=@{$package};
9328: if (defined($packagetab{"$pack_type&$name&default"})) {
9329: return $packagetab{"$pack_type&$name&default"};
9330: }
9331: if (defined($packagetab{$package."&$name&default"})) {
9332: return $packagetab{$package."&$name&default"};
9333: }
9334: }
9335: # look for a global default setting
9336: if ($do_default && defined($packagetab{"default&$name&default"})) {
9337: return $packagetab{"default&$name&default"};
9338: }
9339: return undef;
9340: }
9341:
9342: sub add_prefix_and_part {
9343: my ($prefix,$part)=@_;
9344: my $keyroot;
9345: if (defined($prefix) && $prefix !~ /^__/) {
9346: # prefix that has a part already
9347: $keyroot=$prefix;
9348: } elsif (defined($prefix)) {
9349: # prefix that is missing a part
9350: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9351: } else {
9352: # no prefix at all
9353: if (defined($part)) { $keyroot='_'.$part; }
9354: }
9355: return $keyroot;
9356: }
9357:
9358: # ---------------------------------------------------------------- Get metadata
9359:
9360: my %metaentry;
9361: my %importedpartids;
9362: sub metadata {
9363: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
9364: $uri=&declutter($uri);
9365: # if it is a non metadata possible uri return quickly
9366: if (($uri eq '') ||
9367: (($uri =~ m|^/*adm/|) &&
9368: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
9369: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
9370: return undef;
9371: }
9372: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
9373: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
9374: return undef;
9375: }
9376: my $filename=$uri;
9377: $uri=~s/\.meta$//;
9378: #
9379: # Is the metadata already cached?
9380: # Look at timestamp of caching
9381: # Everything is cached by the main uri, libraries are never directly cached
9382: #
9383: if (!defined($liburi)) {
9384: my ($result,$cached)=&is_cached_new('meta',$uri);
9385: if (defined($cached)) { return $result->{':'.$what}; }
9386: }
9387: {
9388: # Imported parts would go here
9389: my %importedids=();
9390: my @origfileimportpartids=();
9391: my $importedparts=0;
9392: #
9393: # Is this a recursive call for a library?
9394: #
9395: # if (! exists($metacache{$uri})) {
9396: # $metacache{$uri}={};
9397: # }
9398: my $cachetime = 60*60;
9399: if ($liburi) {
9400: $liburi=&declutter($liburi);
9401: $filename=$liburi;
9402: } else {
9403: &devalidate_cache_new('meta',$uri);
9404: undef(%metaentry);
9405: }
9406: my %metathesekeys=();
9407: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
9408: my $metastring;
9409: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
9410: my $which = &hreflocation('','/'.($liburi || $uri));
9411: $metastring =
9412: &Apache::lonnet::ssi_body($which,
9413: ('grade_target' => 'meta'));
9414: $cachetime = 1; # only want this cached in the child not long term
9415: } elsif (($uri !~ m -^(editupload)/-) &&
9416: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
9417: my $file=&filelocation('',&clutter($filename));
9418: #push(@{$metaentry{$uri.'.file'}},$file);
9419: $metastring=&getfile($file);
9420: }
9421: my $parser=HTML::LCParser->new(\$metastring);
9422: my $token;
9423: undef %metathesekeys;
9424: while ($token=$parser->get_token) {
9425: if ($token->[0] eq 'S') {
9426: if (defined($token->[2]->{'package'})) {
9427: #
9428: # This is a package - get package info
9429: #
9430: my $package=$token->[2]->{'package'};
9431: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9432: if (defined($token->[2]->{'id'})) {
9433: $keyroot.='_'.$token->[2]->{'id'};
9434: }
9435: if ($metaentry{':packages'}) {
9436: $metaentry{':packages'}.=','.$package.$keyroot;
9437: } else {
9438: $metaentry{':packages'}=$package.$keyroot;
9439: }
9440: foreach my $pack_entry (keys(%packagetab)) {
9441: my $part=$keyroot;
9442: $part=~s/^\_//;
9443: if ($pack_entry=~/^\Q$package\E\&/ ||
9444: $pack_entry=~/^\Q$package\E_0\&/) {
9445: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
9446: # ignore package.tab specified default values
9447: # here &package_tab_default() will fetch those
9448: if ($subp eq 'default') { next; }
9449: my $value=$packagetab{$pack_entry};
9450: my $unikey;
9451: if ($pack =~ /_0$/) {
9452: $unikey='parameter_0_'.$name;
9453: $part=0;
9454: } else {
9455: $unikey='parameter'.$keyroot.'_'.$name;
9456: }
9457: if ($subp eq 'display') {
9458: $value.=' [Part: '.$part.']';
9459: }
9460: $metaentry{':'.$unikey.'.part'}=$part;
9461: $metathesekeys{$unikey}=1;
9462: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9463: $metaentry{':'.$unikey.'.'.$subp}=$value;
9464: }
9465: if (defined($metaentry{':'.$unikey.'.default'})) {
9466: $metaentry{':'.$unikey}=
9467: $metaentry{':'.$unikey.'.default'};
9468: }
9469: }
9470: }
9471: } else {
9472: #
9473: # This is not a package - some other kind of start tag
9474: #
9475: my $entry=$token->[1];
9476: my $unikey='';
9477:
9478: if ($entry eq 'import') {
9479: #
9480: # Importing a library here
9481: #
9482: my $location=$parser->get_text('/import');
9483: my $dir=$filename;
9484: $dir=~s|[^/]*$||;
9485: $location=&filelocation($dir,$location);
9486:
9487: my $importmode=$token->[2]->{'importmode'};
9488: if ($importmode eq 'problem') {
9489: # Import as problem/response
9490: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9491: } elsif ($importmode eq 'part') {
9492: # Import as part(s)
9493: $importedparts=1;
9494: # We need to get the original file and the imported file to get the part order correct
9495: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9496: # Load and inspect original file
9497: if ($#origfileimportpartids<0) {
9498: undef(%importedpartids);
9499: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9500: my $origfile=&getfile($origfilelocation);
9501: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9502: }
9503:
9504: # Load and inspect imported file
9505: my $impfile=&getfile($location);
9506: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9507: if ($#impfilepartids>=0) {
9508: # This problem had parts
9509: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
9510: } else {
9511: # Importing by turning a single problem into a problem part
9512: # It gets the import-tags ID as part-ID
9513: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
9514: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
9515: }
9516: } else {
9517: # Normal import
9518: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9519: if (defined($token->[2]->{'id'})) {
9520: $unikey.='_'.$token->[2]->{'id'};
9521: }
9522: }
9523:
9524: if ($depthcount<20) {
9525: my $metadata =
9526: &metadata($uri,'keys', $location,$unikey,
9527: $depthcount+1);
9528: foreach my $meta (split(',',$metadata)) {
9529: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9530: $metathesekeys{$meta}=1;
9531: }
9532:
9533: }
9534: } else {
9535: #
9536: # Not importing, some other kind of non-package, non-library start tag
9537: #
9538: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9539: if (defined($token->[2]->{'id'})) {
9540: $unikey.='_'.$token->[2]->{'id'};
9541: }
9542: if (defined($token->[2]->{'name'})) {
9543: $unikey.='_'.$token->[2]->{'name'};
9544: }
9545: $metathesekeys{$unikey}=1;
9546: foreach my $param (@{$token->[3]}) {
9547: $metaentry{':'.$unikey.'.'.$param} =
9548: $token->[2]->{$param};
9549: }
9550: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
9551: my $default=$metaentry{':'.$unikey.'.default'};
9552: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9553: # only ws inside the tag, and not in default, so use default
9554: # as value
9555: $metaentry{':'.$unikey}=$default;
9556: } elsif ( $internaltext =~ /\S/ ) {
9557: # something interesting inside the tag
9558: $metaentry{':'.$unikey}=$internaltext;
9559: } else {
9560: # no interesting values, don't set a default
9561: }
9562: # end of not-a-package not-a-library import
9563: }
9564: # end of not-a-package start tag
9565: }
9566: # the next is the end of "start tag"
9567: }
9568: }
9569: my ($extension) = ($uri =~ /\.(\w+)$/);
9570: $extension = lc($extension);
9571: if ($extension eq 'htm') { $extension='html'; }
9572:
9573: foreach my $key (keys(%packagetab)) {
9574: #no specific packages #how's our extension
9575: if ($key!~/^extension_\Q$extension\E&/) { next; }
9576: &metadata_create_package_def($uri,$key,'extension_'.$extension,
9577: \%metathesekeys);
9578: }
9579:
9580: if (!exists($metaentry{':packages'})
9581: || $packagetab{"import_defaults&extension_$extension"}) {
9582: foreach my $key (keys(%packagetab)) {
9583: #no specific packages well let's get default then
9584: if ($key!~/^default&/) { next; }
9585: &metadata_create_package_def($uri,$key,'default',
9586: \%metathesekeys);
9587: }
9588: }
9589: # are there custom rights to evaluate
9590: if ($metaentry{':copyright'} eq 'custom') {
9591:
9592: #
9593: # Importing a rights file here
9594: #
9595: unless ($depthcount) {
9596: my $location=$metaentry{':customdistributionfile'};
9597: my $dir=$filename;
9598: $dir=~s|[^/]*$||;
9599: $location=&filelocation($dir,$location);
9600: my $rights_metadata =
9601: &metadata($uri,'keys',$location,'_rights',
9602: $depthcount+1);
9603: foreach my $rights (split(',',$rights_metadata)) {
9604: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9605: $metathesekeys{$rights}=1;
9606: }
9607: }
9608: }
9609: # uniqifiy package listing
9610: my %seen;
9611: my @uniq_packages =
9612: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9613: $metaentry{':packages'} = join(',',@uniq_packages);
9614:
9615: if ($importedparts) {
9616: # We had imported parts and need to rebuild partorder
9617: $metaentry{':partorder'}='';
9618: $metathesekeys{'partorder'}=1;
9619: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9620: if ($origfileimportpartids[$index] eq 'part') {
9621: # original part, part of the problem
9622: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9623: } else {
9624: # we have imported parts at this position
9625: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9626: }
9627: }
9628: $metaentry{':partorder'}=~s/^\,//;
9629: }
9630:
9631: $metaentry{':keys'} = join(',',keys(%metathesekeys));
9632: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9633: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
9634: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
9635: # this is the end of "was not already recently cached
9636: }
9637: return $metaentry{':'.$what};
9638: }
9639:
9640: sub metadata_create_package_def {
9641: my ($uri,$key,$package,$metathesekeys)=@_;
9642: my ($pack,$name,$subp)=split(/\&/,$key);
9643: if ($subp eq 'default') { next; }
9644:
9645: if (defined($metaentry{':packages'})) {
9646: $metaentry{':packages'}.=','.$package;
9647: } else {
9648: $metaentry{':packages'}=$package;
9649: }
9650: my $value=$packagetab{$key};
9651: my $unikey;
9652: $unikey='parameter_0_'.$name;
9653: $metaentry{':'.$unikey.'.part'}=0;
9654: $$metathesekeys{$unikey}=1;
9655: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9656: $metaentry{':'.$unikey.'.'.$subp}=$value;
9657: }
9658: if (defined($metaentry{':'.$unikey.'.default'})) {
9659: $metaentry{':'.$unikey}=
9660: $metaentry{':'.$unikey.'.default'};
9661: }
9662: }
9663:
9664: sub metadata_generate_part0 {
9665: my ($metadata,$metacache,$uri) = @_;
9666: my %allnames;
9667: foreach my $metakey (keys(%$metadata)) {
9668: if ($metakey=~/^parameter\_(.*)/) {
9669: my $part=$$metacache{':'.$metakey.'.part'};
9670: my $name=$$metacache{':'.$metakey.'.name'};
9671: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
9672: $allnames{$name}=$part;
9673: }
9674: }
9675: }
9676: foreach my $name (keys(%allnames)) {
9677: $$metadata{"parameter_0_$name"}=1;
9678: my $key=":parameter_0_$name";
9679: $$metacache{"$key.part"}='0';
9680: $$metacache{"$key.name"}=$name;
9681: $$metacache{"$key.type"}=$$metacache{':parameter_'.
9682: $allnames{$name}.'_'.$name.
9683: '.type'};
9684: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
9685: '.display'};
9686: my $expr='[Part: '.$allnames{$name}.']';
9687: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
9688: $$metacache{"$key.display"}=$olddis;
9689: }
9690: }
9691:
9692: # ------------------------------------------------------ Devalidate title cache
9693:
9694: sub devalidate_title_cache {
9695: my ($url)=@_;
9696: if (!$env{'request.course.id'}) { return; }
9697: my $symb=&symbread($url);
9698: if (!$symb) { return; }
9699: my $key=$env{'request.course.id'}."\0".$symb;
9700: &devalidate_cache_new('title',$key);
9701: }
9702:
9703: # ------------------------------------------------- Get the title of a course
9704:
9705: sub current_course_title {
9706: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9707: }
9708: # ------------------------------------------------- Get the title of a resource
9709:
9710: sub gettitle {
9711: my $urlsymb=shift;
9712: my $symb=&symbread($urlsymb);
9713: if ($symb) {
9714: my $key=$env{'request.course.id'}."\0".$symb;
9715: my ($result,$cached)=&is_cached_new('title',$key);
9716: if (defined($cached)) {
9717: return $result;
9718: }
9719: my ($map,$resid,$url)=&decode_symb($symb);
9720: my $title='';
9721: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9722: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9723: } else {
9724: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9725: &GDBM_READER(),0640)) {
9726: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9727: $title=$bighash{'title_'.$mapid.'.'.$resid};
9728: untie(%bighash);
9729: }
9730: }
9731: $title=~s/\&colon\;/\:/gs;
9732: if ($title) {
9733: # Remember both $symb and $title for dynamic metadata
9734: $accesshash{$symb.'___crstitle'}=$title;
9735: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
9736: # Cache this title and then return it
9737: return &do_cache_new('title',$key,$title,600);
9738: }
9739: $urlsymb=$url;
9740: }
9741: my $title=&metadata($urlsymb,'title');
9742: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9743: return $title;
9744: }
9745:
9746: sub get_slot {
9747: my ($which,$cnum,$cdom)=@_;
9748: if (!$cnum || !$cdom) {
9749: (undef,my $courseid)=&whichuser();
9750: $cdom=$env{'course.'.$courseid.'.domain'};
9751: $cnum=$env{'course.'.$courseid.'.num'};
9752: }
9753: my $key=join("\0",'slots',$cdom,$cnum,$which);
9754: my %slotinfo;
9755: if (exists($remembered{$key})) {
9756: $slotinfo{$which} = $remembered{$key};
9757: } else {
9758: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9759: &Apache::lonhomework::showhash(%slotinfo);
9760: my ($tmp)=keys(%slotinfo);
9761: if ($tmp=~/^error:/) { return (); }
9762: $remembered{$key} = $slotinfo{$which};
9763: }
9764: if (ref($slotinfo{$which}) eq 'HASH') {
9765: return %{$slotinfo{$which}};
9766: }
9767: return $slotinfo{$which};
9768: }
9769:
9770: sub get_reservable_slots {
9771: my ($cnum,$cdom,$uname,$udom) = @_;
9772: my $now = time;
9773: my $reservable_info;
9774: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9775: if (exists($remembered{$key})) {
9776: $reservable_info = $remembered{$key};
9777: } else {
9778: my %resv;
9779: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9780: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9781: $reservable_info = \%resv;
9782: $remembered{$key} = $reservable_info;
9783: }
9784: return $reservable_info;
9785: }
9786:
9787: sub get_course_slots {
9788: my ($cnum,$cdom) = @_;
9789: my $hashid=$cnum.':'.$cdom;
9790: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9791: if (defined($cached)) {
9792: if (ref($result) eq 'HASH') {
9793: return %{$result};
9794: }
9795: } else {
9796: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9797: my ($tmp) = keys(%slots);
9798: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9799: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9800: return %slots;
9801: }
9802: }
9803: return;
9804: }
9805:
9806: sub devalidate_slots_cache {
9807: my ($cnum,$cdom)=@_;
9808: my $hashid=$cnum.':'.$cdom;
9809: &devalidate_cache_new('allslots',$hashid);
9810: }
9811:
9812: # ------------------------------------------------- Update symbolic store links
9813:
9814: sub symblist {
9815: my ($mapname,%newhash)=@_;
9816: $mapname=&deversion(&declutter($mapname));
9817: my %hash;
9818: if (($env{'request.course.fn'}) && (%newhash)) {
9819: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9820: &GDBM_WRCREAT(),0640)) {
9821: foreach my $url (keys(%newhash)) {
9822: next if ($url eq 'last_known'
9823: && $env{'form.no_update_last_known'});
9824: $hash{declutter($url)}=&encode_symb($mapname,
9825: $newhash{$url}->[1],
9826: $newhash{$url}->[0]);
9827: }
9828: if (untie(%hash)) {
9829: return 'ok';
9830: }
9831: }
9832: }
9833: return 'error';
9834: }
9835:
9836: # --------------------------------------------------------------- Verify a symb
9837:
9838: sub symbverify {
9839: my ($symb,$thisurl)=@_;
9840: my $thisfn=$thisurl;
9841: $thisfn=&declutter($thisfn);
9842: # direct jump to resource in page or to a sequence - will construct own symbs
9843: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9844: # check URL part
9845: my ($map,$resid,$url)=&decode_symb($symb);
9846:
9847: unless ($url eq $thisfn) { return 0; }
9848:
9849: $symb=&symbclean($symb);
9850: $thisurl=&deversion($thisurl);
9851: $thisfn=&deversion($thisfn);
9852:
9853: my %bighash;
9854: my $okay=0;
9855:
9856: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9857: &GDBM_READER(),0640)) {
9858: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9859: $thisurl =~ s/\?.+$//;
9860: }
9861: my $ids=$bighash{'ids_'.&clutter($thisurl)};
9862: unless ($ids) {
9863: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9864: $ids=$bighash{$idkey};
9865: }
9866: if ($ids) {
9867: # ------------------------------------------------------------------- Has ID(s)
9868: foreach my $id (split(/\,/,$ids)) {
9869: my ($mapid,$resid)=split(/\./,$id);
9870: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9871: $symb =~ s/\?.+$//;
9872: }
9873: if (
9874: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9875: eq $symb) {
9876: if (($env{'request.role.adv'}) ||
9877: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9878: ($thisurl eq '/adm/navmaps')) {
9879: $okay=1;
9880: }
9881: }
9882: }
9883: }
9884: untie(%bighash);
9885: }
9886: return $okay;
9887: }
9888:
9889: # --------------------------------------------------------------- Clean-up symb
9890:
9891: sub symbclean {
9892: my $symb=shift;
9893: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9894: # remove version from map
9895: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
9896:
9897: # remove version from URL
9898: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
9899:
9900: # remove wrapper
9901:
9902: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
9903: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
9904: return $symb;
9905: }
9906:
9907: # ---------------------------------------------- Split symb to find map and url
9908:
9909: sub encode_symb {
9910: my ($map,$resid,$url)=@_;
9911: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9912: }
9913:
9914: sub decode_symb {
9915: my $symb=shift;
9916: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9917: my ($map,$resid,$url)=split(/___/,$symb);
9918: return (&fixversion($map),$resid,&fixversion($url));
9919: }
9920:
9921: sub fixversion {
9922: my $fn=shift;
9923: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
9924: my %bighash;
9925: my $uri=&clutter($fn);
9926: my $key=$env{'request.course.id'}.'_'.$uri;
9927: # is this cached?
9928: my ($result,$cached)=&is_cached_new('courseresversion',$key);
9929: if (defined($cached)) { return $result; }
9930: # unfortunately not cached, or expired
9931: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9932: &GDBM_READER(),0640)) {
9933: if ($bighash{'version_'.$uri}) {
9934: my $version=$bighash{'version_'.$uri};
9935: unless (($version eq 'mostrecent') ||
9936: ($version==&getversion($uri))) {
9937: $uri=~s/\.(\w+)$/\.$version\.$1/;
9938: }
9939: }
9940: untie %bighash;
9941: }
9942: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
9943: }
9944:
9945: sub deversion {
9946: my $url=shift;
9947: $url=~s/\.\d+\.(\w+)$/\.$1/;
9948: return $url;
9949: }
9950:
9951: # ------------------------------------------------------ Return symb list entry
9952:
9953: sub symbread {
9954: my ($thisfn,$donotrecurse)=@_;
9955: my $cache_str='request.symbread.cached.'.$thisfn;
9956: if (defined($env{$cache_str})) { return $env{$cache_str}; }
9957: # no filename provided? try from environment
9958: unless ($thisfn) {
9959: if ($env{'request.symb'}) {
9960: return $env{$cache_str}=&symbclean($env{'request.symb'});
9961: }
9962: $thisfn=$env{'request.filename'};
9963: }
9964: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9965: # is that filename actually a symb? Verify, clean, and return
9966: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
9967: if (&symbverify($thisfn,$1)) {
9968: return $env{$cache_str}=&symbclean($thisfn);
9969: }
9970: }
9971: $thisfn=declutter($thisfn);
9972: my %hash;
9973: my %bighash;
9974: my $syval='';
9975: if (($env{'request.course.fn'}) && ($thisfn)) {
9976: my $targetfn = $thisfn;
9977: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
9978: $targetfn = 'adm/wrapper/'.$thisfn;
9979: }
9980: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9981: $targetfn=$1;
9982: }
9983: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
9984: &GDBM_READER(),0640)) {
9985: $syval=$hash{$targetfn};
9986: untie(%hash);
9987: }
9988: # ---------------------------------------------------------- There was an entry
9989: if ($syval) {
9990: #unless ($syval=~/\_\d+$/) {
9991: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
9992: #&appenv({'request.ambiguous' => $thisfn});
9993: #return $env{$cache_str}='';
9994: #}
9995: #$syval.=$1;
9996: #}
9997: } else {
9998: # ------------------------------------------------------- Was not in symb table
9999: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
10000: &GDBM_READER(),0640)) {
10001: # ---------------------------------------------- Get ID(s) for current resource
10002: my $ids=$bighash{'ids_'.&clutter($thisfn)};
10003: unless ($ids) {
10004: $ids=$bighash{'ids_/'.$thisfn};
10005: }
10006: unless ($ids) {
10007: # alias?
10008: $ids=$bighash{'mapalias_'.$thisfn};
10009: }
10010: if ($ids) {
10011: # ------------------------------------------------------------------- Has ID(s)
10012: my @possibilities=split(/\,/,$ids);
10013: if ($#possibilities==0) {
10014: # ----------------------------------------------- There is only one possibility
10015: my ($mapid,$resid)=split(/\./,$ids);
10016: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10017: $resid,$thisfn);
10018: } elsif (!$donotrecurse) {
10019: # ------------------------------------------ There is more than one possibility
10020: my $realpossible=0;
10021: foreach my $id (@possibilities) {
10022: my $file=$bighash{'src_'.$id};
10023: if (&allowed('bre',$file)) {
10024: my ($mapid,$resid)=split(/\./,$id);
10025: if ($bighash{'map_type_'.$mapid} ne 'page') {
10026: $realpossible++;
10027: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10028: $resid,$thisfn);
10029: }
10030: }
10031: }
10032: if ($realpossible!=1) { $syval=''; }
10033: } else {
10034: $syval='';
10035: }
10036: }
10037: untie(%bighash)
10038: }
10039: }
10040: if ($syval) {
10041: return $env{$cache_str}=$syval;
10042: }
10043: }
10044: &appenv({'request.ambiguous' => $thisfn});
10045: return $env{$cache_str}='';
10046: }
10047:
10048: # ---------------------------------------------------------- Return random seed
10049:
10050: sub numval {
10051: my $txt=shift;
10052: $txt=~tr/A-J/0-9/;
10053: $txt=~tr/a-j/0-9/;
10054: $txt=~tr/K-T/0-9/;
10055: $txt=~tr/k-t/0-9/;
10056: $txt=~tr/U-Z/0-5/;
10057: $txt=~tr/u-z/0-5/;
10058: $txt=~s/\D//g;
10059: if ($_64bit) { if ($txt > 2**32) { return -1; } }
10060: return int($txt);
10061: }
10062:
10063: sub numval2 {
10064: my $txt=shift;
10065: $txt=~tr/A-J/0-9/;
10066: $txt=~tr/a-j/0-9/;
10067: $txt=~tr/K-T/0-9/;
10068: $txt=~tr/k-t/0-9/;
10069: $txt=~tr/U-Z/0-5/;
10070: $txt=~tr/u-z/0-5/;
10071: $txt=~s/\D//g;
10072: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10073: my $total;
10074: foreach my $val (@txts) { $total+=$val; }
10075: if ($_64bit) { if ($total > 2**32) { return -1; } }
10076: return int($total);
10077: }
10078:
10079: sub numval3 {
10080: use integer;
10081: my $txt=shift;
10082: $txt=~tr/A-J/0-9/;
10083: $txt=~tr/a-j/0-9/;
10084: $txt=~tr/K-T/0-9/;
10085: $txt=~tr/k-t/0-9/;
10086: $txt=~tr/U-Z/0-5/;
10087: $txt=~tr/u-z/0-5/;
10088: $txt=~s/\D//g;
10089: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10090: my $total;
10091: foreach my $val (@txts) { $total+=$val; }
10092: if ($_64bit) { $total=(($total<<32)>>32); }
10093: return $total;
10094: }
10095:
10096: sub digest {
10097: my ($data)=@_;
10098: my $digest=&Digest::MD5::md5($data);
10099: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10100: my ($e,$f);
10101: {
10102: use integer;
10103: $e=($a+$b);
10104: $f=($c+$d);
10105: if ($_64bit) {
10106: $e=(($e<<32)>>32);
10107: $f=(($f<<32)>>32);
10108: }
10109: }
10110: if (wantarray) {
10111: return ($e,$f);
10112: } else {
10113: my $g;
10114: {
10115: use integer;
10116: $g=($e+$f);
10117: if ($_64bit) {
10118: $g=(($g<<32)>>32);
10119: }
10120: }
10121: return $g;
10122: }
10123: }
10124:
10125: sub latest_rnd_algorithm_id {
10126: return '64bit5';
10127: }
10128:
10129: sub get_rand_alg {
10130: my ($courseid)=@_;
10131: if (!$courseid) { $courseid=(&whichuser())[1]; }
10132: if ($courseid) {
10133: return $env{"course.$courseid.rndseed"};
10134: }
10135: return &latest_rnd_algorithm_id();
10136: }
10137:
10138: sub validCODE {
10139: my ($CODE)=@_;
10140: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10141: return 0;
10142: }
10143:
10144: sub getCODE {
10145: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
10146: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10147: defined($Apache::lonhomework::parsing_a_task) ) &&
10148: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
10149: return $Apache::lonhomework::history{'resource.CODE'};
10150: }
10151: return undef;
10152: }
10153: #
10154: # Determines the random seed for a specific context:
10155: #
10156: # parameters:
10157: # symb - in course context the symb for the seed.
10158: # course_id - The course id of the form domain_coursenum.
10159: # domain - Domain for the user.
10160: # course - Course for the user.
10161: # cenv - environment of the course.
10162: #
10163: # NOTE:
10164: # All parameters are picked out of the environment if missing
10165: # or not defined.
10166: # If a symb cannot be determined the current time is used instead.
10167: #
10168: # For a given well defined symb, courside, domain, username,
10169: # and course environment, the seed is reproducible.
10170: #
10171: sub rndseed {
10172: my ($symb,$courseid,$domain,$username, $cenv)=@_;
10173: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
10174: if (!defined($symb)) {
10175: unless ($symb=$wsymb) { return time; }
10176: }
10177: if (!defined $courseid) {
10178: $courseid=$wcourseid;
10179: }
10180: if (!defined $domain) { $domain=$wdomain; }
10181: if (!defined $username) { $username=$wusername }
10182:
10183: my $which;
10184: if (defined($cenv->{'rndseed'})) {
10185: $which = $cenv->{'rndseed'};
10186: } else {
10187: $which =&get_rand_alg($courseid);
10188: }
10189: if (defined(&getCODE())) {
10190:
10191: if ($which eq '64bit5') {
10192: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10193: } elsif ($which eq '64bit4') {
10194: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10195: } else {
10196: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10197: }
10198: } elsif ($which eq '64bit5') {
10199: return &rndseed_64bit5($symb,$courseid,$domain,$username);
10200: } elsif ($which eq '64bit4') {
10201: return &rndseed_64bit4($symb,$courseid,$domain,$username);
10202: } elsif ($which eq '64bit3') {
10203: return &rndseed_64bit3($symb,$courseid,$domain,$username);
10204: } elsif ($which eq '64bit2') {
10205: return &rndseed_64bit2($symb,$courseid,$domain,$username);
10206: } elsif ($which eq '64bit') {
10207: return &rndseed_64bit($symb,$courseid,$domain,$username);
10208: }
10209: return &rndseed_32bit($symb,$courseid,$domain,$username);
10210: }
10211:
10212: sub rndseed_32bit {
10213: my ($symb,$courseid,$domain,$username)=@_;
10214: {
10215: use integer;
10216: my $symbchck=unpack("%32C*",$symb) << 27;
10217: my $symbseed=numval($symb) << 22;
10218: my $namechck=unpack("%32C*",$username) << 17;
10219: my $nameseed=numval($username) << 12;
10220: my $domainseed=unpack("%32C*",$domain) << 7;
10221: my $courseseed=unpack("%32C*",$courseid);
10222: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
10223: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10224: #&logthis("rndseed :$num:$symb");
10225: if ($_64bit) { $num=(($num<<32)>>32); }
10226: return $num;
10227: }
10228: }
10229:
10230: sub rndseed_64bit {
10231: my ($symb,$courseid,$domain,$username)=@_;
10232: {
10233: use integer;
10234: my $symbchck=unpack("%32S*",$symb) << 21;
10235: my $symbseed=numval($symb) << 10;
10236: my $namechck=unpack("%32S*",$username);
10237:
10238: my $nameseed=numval($username) << 21;
10239: my $domainseed=unpack("%32S*",$domain) << 10;
10240: my $courseseed=unpack("%32S*",$courseid);
10241:
10242: my $num1=$symbchck+$symbseed+$namechck;
10243: my $num2=$nameseed+$domainseed+$courseseed;
10244: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10245: #&logthis("rndseed :$num:$symb");
10246: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10247: return "$num1,$num2";
10248: }
10249: }
10250:
10251: sub rndseed_64bit2 {
10252: my ($symb,$courseid,$domain,$username)=@_;
10253: {
10254: use integer;
10255: # strings need to be an even # of cahracters long, it it is odd the
10256: # last characters gets thrown away
10257: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10258: my $symbseed=numval($symb) << 10;
10259: my $namechck=unpack("%32S*",$username.' ');
10260:
10261: my $nameseed=numval($username) << 21;
10262: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10263: my $courseseed=unpack("%32S*",$courseid.' ');
10264:
10265: my $num1=$symbchck+$symbseed+$namechck;
10266: my $num2=$nameseed+$domainseed+$courseseed;
10267: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10268: #&logthis("rndseed :$num:$symb");
10269: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10270: return "$num1,$num2";
10271: }
10272: }
10273:
10274: sub rndseed_64bit3 {
10275: my ($symb,$courseid,$domain,$username)=@_;
10276: {
10277: use integer;
10278: # strings need to be an even # of cahracters long, it it is odd the
10279: # last characters gets thrown away
10280: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10281: my $symbseed=numval2($symb) << 10;
10282: my $namechck=unpack("%32S*",$username.' ');
10283:
10284: my $nameseed=numval2($username) << 21;
10285: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10286: my $courseseed=unpack("%32S*",$courseid.' ');
10287:
10288: my $num1=$symbchck+$symbseed+$namechck;
10289: my $num2=$nameseed+$domainseed+$courseseed;
10290: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10291: #&logthis("rndseed :$num1:$num2:$_64bit");
10292: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10293:
10294: return "$num1:$num2";
10295: }
10296: }
10297:
10298: sub rndseed_64bit4 {
10299: my ($symb,$courseid,$domain,$username)=@_;
10300: {
10301: use integer;
10302: # strings need to be an even # of cahracters long, it it is odd the
10303: # last characters gets thrown away
10304: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10305: my $symbseed=numval3($symb) << 10;
10306: my $namechck=unpack("%32S*",$username.' ');
10307:
10308: my $nameseed=numval3($username) << 21;
10309: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10310: my $courseseed=unpack("%32S*",$courseid.' ');
10311:
10312: my $num1=$symbchck+$symbseed+$namechck;
10313: my $num2=$nameseed+$domainseed+$courseseed;
10314: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10315: #&logthis("rndseed :$num1:$num2:$_64bit");
10316: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
10317:
10318: return "$num1:$num2";
10319: }
10320: }
10321:
10322: sub rndseed_64bit5 {
10323: my ($symb,$courseid,$domain,$username)=@_;
10324: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10325: return "$num1:$num2";
10326: }
10327:
10328: sub rndseed_CODE_64bit {
10329: my ($symb,$courseid,$domain,$username)=@_;
10330: {
10331: use integer;
10332: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10333: my $symbseed=numval2($symb);
10334: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10335: my $CODEseed=numval(&getCODE());
10336: my $courseseed=unpack("%32S*",$courseid.' ');
10337: my $num1=$symbseed+$CODEchck;
10338: my $num2=$CODEseed+$courseseed+$symbchck;
10339: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10340: #&logthis("rndseed :$num1:$num2:$symb");
10341: if ($_64bit) { $num1=(($num1<<32)>>32); }
10342: if ($_64bit) { $num2=(($num2<<32)>>32); }
10343: return "$num1:$num2";
10344: }
10345: }
10346:
10347: sub rndseed_CODE_64bit4 {
10348: my ($symb,$courseid,$domain,$username)=@_;
10349: {
10350: use integer;
10351: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10352: my $symbseed=numval3($symb);
10353: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10354: my $CODEseed=numval3(&getCODE());
10355: my $courseseed=unpack("%32S*",$courseid.' ');
10356: my $num1=$symbseed+$CODEchck;
10357: my $num2=$CODEseed+$courseseed+$symbchck;
10358: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10359: #&logthis("rndseed :$num1:$num2:$symb");
10360: if ($_64bit) { $num1=(($num1<<32)>>32); }
10361: if ($_64bit) { $num2=(($num2<<32)>>32); }
10362: return "$num1:$num2";
10363: }
10364: }
10365:
10366: sub rndseed_CODE_64bit5 {
10367: my ($symb,$courseid,$domain,$username)=@_;
10368: my $code = &getCODE();
10369: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10370: return "$num1:$num2";
10371: }
10372:
10373: sub setup_random_from_rndseed {
10374: my ($rndseed)=@_;
10375: if ($rndseed =~/([,:])/) {
10376: my ($num1,$num2)=split(/[,:]/,$rndseed);
10377: &Math::Random::random_set_seed(abs($num1),abs($num2));
10378: } else {
10379: &Math::Random::random_set_seed_from_phrase($rndseed);
10380: }
10381: }
10382:
10383: sub latest_receipt_algorithm_id {
10384: return 'receipt3';
10385: }
10386:
10387: sub recunique {
10388: my $fucourseid=shift;
10389: my $unique;
10390: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10391: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10392: $unique=$env{"course.$fucourseid.internal.encseed"};
10393: } else {
10394: $unique=$perlvar{'lonReceipt'};
10395: }
10396: return unpack("%32C*",$unique);
10397: }
10398:
10399: sub recprefix {
10400: my $fucourseid=shift;
10401: my $prefix;
10402: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10403: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
10404: $prefix=$env{"course.$fucourseid.internal.encpref"};
10405: } else {
10406: $prefix=$perlvar{'lonHostID'};
10407: }
10408: return unpack("%32C*",$prefix);
10409: }
10410:
10411: sub ireceipt {
10412: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
10413:
10414: my $return =&recprefix($fucourseid).'-';
10415:
10416: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10417: $env{'request.state'} eq 'construct') {
10418: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10419: return $return;
10420: }
10421:
10422: my $cuname=unpack("%32C*",$funame);
10423: my $cudom=unpack("%32C*",$fudom);
10424: my $cucourseid=unpack("%32C*",$fucourseid);
10425: my $cusymb=unpack("%32C*",$fusymb);
10426: my $cunique=&recunique($fucourseid);
10427: my $cpart=unpack("%32S*",$part);
10428: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10429:
10430: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
10431:
10432: $return.= ($cunique%$cuname+
10433: $cunique%$cudom+
10434: $cusymb%$cuname+
10435: $cusymb%$cudom+
10436: $cucourseid%$cuname+
10437: $cucourseid%$cudom+
10438: $cpart%$cuname+
10439: $cpart%$cudom);
10440: } else {
10441: $return.= ($cunique%$cuname+
10442: $cunique%$cudom+
10443: $cusymb%$cuname+
10444: $cusymb%$cudom+
10445: $cucourseid%$cuname+
10446: $cucourseid%$cudom);
10447: }
10448: return $return;
10449: }
10450:
10451: sub receipt {
10452: my ($part)=@_;
10453: my ($symb,$courseid,$domain,$name) = &whichuser();
10454: return &ireceipt($name,$domain,$courseid,$symb,$part);
10455: }
10456:
10457: sub whichuser {
10458: my ($passedsymb)=@_;
10459: my ($symb,$courseid,$domain,$name,$publicuser);
10460: if (defined($env{'form.grade_symb'})) {
10461: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10462: my $allowed=&allowed('vgr',$tmp_courseid);
10463: if (!$allowed &&
10464: exists($env{'request.course.sec'}) &&
10465: $env{'request.course.sec'} !~ /^\s*$/) {
10466: $allowed=&allowed('vgr',$tmp_courseid.
10467: '/'.$env{'request.course.sec'});
10468: }
10469: if ($allowed) {
10470: ($symb)=&get_env_multiple('form.grade_symb');
10471: $courseid=$tmp_courseid;
10472: ($domain)=&get_env_multiple('form.grade_domain');
10473: ($name)=&get_env_multiple('form.grade_username');
10474: return ($symb,$courseid,$domain,$name,$publicuser);
10475: }
10476: }
10477: if (!$passedsymb) {
10478: $symb=&symbread();
10479: } else {
10480: $symb=$passedsymb;
10481: }
10482: $courseid=$env{'request.course.id'};
10483: $domain=$env{'user.domain'};
10484: $name=$env{'user.name'};
10485: if ($name eq 'public' && $domain eq 'public') {
10486: if (!defined($env{'form.username'})) {
10487: $env{'form.username'}.=time.rand(10000000);
10488: }
10489: $name.=$env{'form.username'};
10490: }
10491: return ($symb,$courseid,$domain,$name,$publicuser);
10492:
10493: }
10494:
10495: # ------------------------------------------------------------ Serves up a file
10496: # returns either the contents of the file or
10497: # -1 if the file doesn't exist
10498: #
10499: # if the target is a file that was uploaded via DOCS,
10500: # a check will be made to see if a current copy exists on the local server,
10501: # if it does this will be served, otherwise a copy will be retrieved from
10502: # the home server for the course and stored in /home/httpd/html/userfiles on
10503: # the local server.
10504:
10505: sub getfile {
10506: my ($file) = @_;
10507: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
10508: &repcopy($file);
10509: return &readfile($file);
10510: }
10511:
10512: sub repcopy_userfile {
10513: my ($file)=@_;
10514: my $londocroot = $perlvar{'lonDocRoot'};
10515: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
10516: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
10517: my ($cdom,$cnum,$filename) =
10518: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
10519: my $uri="/uploaded/$cdom/$cnum/$filename";
10520: if (-e "$file") {
10521: # we already have a local copy, check it out
10522: my @fileinfo = stat($file);
10523: my $rtncode;
10524: my $info;
10525: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
10526: if ($lwpresp ne 'ok') {
10527: # there is no such file anymore, even though we had a local copy
10528: if ($rtncode eq '404') {
10529: unlink($file);
10530: }
10531: return -1;
10532: }
10533: if ($info < $fileinfo[9]) {
10534: # nice, the file we have is up-to-date, just say okay
10535: return 'ok';
10536: } else {
10537: # the file is outdated, get rid of it
10538: unlink($file);
10539: }
10540: }
10541: # one way or the other, at this point, we don't have the file
10542: # construct the correct path for the file
10543: my @parts = ($cdom,$cnum);
10544: if ($filename =~ m|^(.+)/[^/]+$|) {
10545: push @parts, split(/\//,$1);
10546: }
10547: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10548: foreach my $part (@parts) {
10549: $path .= '/'.$part;
10550: if (!-e $path) {
10551: mkdir($path,0770);
10552: }
10553: }
10554: # now the path exists for sure
10555: # get a user agent
10556: my $ua=new LWP::UserAgent;
10557: my $transferfile=$file.'.in.transfer';
10558: # FIXME: this should flock
10559: if (-e $transferfile) { return 'ok'; }
10560: my $request;
10561: $uri=~s/^\///;
10562: my $homeserver = &homeserver($cnum,$cdom);
10563: my $protocol = $protocol{$homeserver};
10564: $protocol = 'http' if ($protocol ne 'https');
10565: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
10566: my $response=$ua->request($request,$transferfile);
10567: # did it work?
10568: if ($response->is_error()) {
10569: unlink($transferfile);
10570: &logthis("Userfile repcopy failed for $uri");
10571: return -1;
10572: }
10573: # worked, rename the transfer file
10574: rename($transferfile,$file);
10575: return 'ok';
10576: }
10577:
10578: sub tokenwrapper {
10579: my $uri=shift;
10580: $uri=~s|^https?\://([^/]+)||;
10581: $uri=~s|^/||;
10582: $env{'user.environment'}=~/\/([^\/]+)\.id/;
10583: my $token=$1;
10584: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10585: if ($udom && $uname && $file) {
10586: $file=~s|(\?\.*)*$||;
10587: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
10588: my $homeserver = &homeserver($uname,$udom);
10589: my $protocol = $protocol{$homeserver};
10590: $protocol = 'http' if ($protocol ne 'https');
10591: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
10592: (($uri=~/\?/)?'&':'?').'token='.$token.
10593: '&tokenissued='.$perlvar{'lonHostID'};
10594: } else {
10595: return '/adm/notfound.html';
10596: }
10597: }
10598:
10599: # call with reqtype HEAD: get last modification time
10600: # call with reqtype GET: get the file contents
10601: # Do not call this with reqtype GET for large files! It loads everything into memory
10602: #
10603: sub getuploaded {
10604: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10605: $uri=~s/^\///;
10606: my $homeserver = &homeserver($cnum,$cdom);
10607: my $protocol = $protocol{$homeserver};
10608: $protocol = 'http' if ($protocol ne 'https');
10609: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
10610: my $ua=new LWP::UserAgent;
10611: my $request=new HTTP::Request($reqtype,$uri);
10612: my $response=$ua->request($request);
10613: $$rtncode = $response->code;
10614: if (! $response->is_success()) {
10615: return 'failed';
10616: }
10617: if ($reqtype eq 'HEAD') {
10618: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
10619: } elsif ($reqtype eq 'GET') {
10620: $$info = $response->content;
10621: }
10622: return 'ok';
10623: }
10624:
10625: sub readfile {
10626: my $file = shift;
10627: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10628: my $fh;
10629: open($fh,"<$file");
10630: my $a='';
10631: while (my $line = <$fh>) { $a .= $line; }
10632: return $a;
10633: }
10634:
10635: sub filelocation {
10636: my ($dir,$file) = @_;
10637: my $location;
10638: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
10639:
10640: if ($file =~ m-^/adm/-) {
10641: $file=~s-^/adm/wrapper/-/-;
10642: $file=~s-^/adm/coursedocs/showdoc/-/-;
10643: }
10644:
10645: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10646: $location = $file;
10647: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
10648: my ($udom,$uname,$filename)=
10649: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
10650: my $home=&homeserver($uname,$udom);
10651: my $is_me=0;
10652: my @ids=¤t_machine_ids();
10653: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10654: if ($is_me) {
10655: $location=propath($udom,$uname).'/userfiles/'.$filename;
10656: } else {
10657: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10658: $udom.'/'.$uname.'/'.$filename;
10659: }
10660: } elsif ($file =~ m-^/adm/-) {
10661: $location = $perlvar{'lonDocRoot'}.'/'.$file;
10662: } else {
10663: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10664: $file=~s:^/(res|priv)/:/:;
10665: my $space=$1;
10666: if ( !( $file =~ m:^/:) ) {
10667: $location = $dir. '/'.$file;
10668: } else {
10669: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
10670: }
10671: }
10672: $location=~s://+:/:g; # remove duplicate /
10673: while ($location=~m{/\.\./}) {
10674: if ($location =~ m{/[^/]+/\.\./}) {
10675: $location=~ s{/[^/]+/\.\./}{/}g;
10676: } else {
10677: $location=~ s{/\.\./}{/}g;
10678: }
10679: } #remove dir/..
10680: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10681: return $location;
10682: }
10683:
10684: sub hreflocation {
10685: my ($dir,$file)=@_;
10686: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
10687: $file=filelocation($dir,$file);
10688: } elsif ($file=~m-^/adm/-) {
10689: $file=~s-^/adm/wrapper/-/-;
10690: $file=~s-^/adm/coursedocs/showdoc/-/-;
10691: }
10692: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10693: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10694: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
10695: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10696: {/uploaded/$1/$2/}x;
10697: }
10698: if ($file=~ m{^/userfiles/}) {
10699: $file =~ s{^/userfiles/}{/uploaded/};
10700: }
10701: return $file;
10702: }
10703:
10704:
10705:
10706:
10707:
10708: sub current_machine_domains {
10709: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10710: }
10711:
10712: sub machine_domains {
10713: my ($hostname) = @_;
10714: my @domains;
10715: my %hostname = &all_hostnames();
10716: while( my($id, $name) = each(%hostname)) {
10717: # &logthis("-$id-$name-$hostname-");
10718: if ($hostname eq $name) {
10719: push(@domains,&host_domain($id));
10720: }
10721: }
10722: return @domains;
10723: }
10724:
10725: sub current_machine_ids {
10726: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10727: }
10728:
10729: sub machine_ids {
10730: my ($hostname) = @_;
10731: $hostname ||= &hostname($perlvar{'lonHostID'});
10732: my @ids;
10733: my %name_to_host = &all_names();
10734: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10735: return @{ $name_to_host{$hostname} };
10736: }
10737: return;
10738: }
10739:
10740: sub additional_machine_domains {
10741: my @domains;
10742: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10743: while( my $line = <$fh>) {
10744: $line =~ s/\s//g;
10745: push(@domains,$line);
10746: }
10747: return @domains;
10748: }
10749:
10750: sub default_login_domain {
10751: my $domain = $perlvar{'lonDefDomain'};
10752: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10753: foreach my $posdom (¤t_machine_domains(),
10754: &additional_machine_domains()) {
10755: if (lc($posdom) eq lc($testdomain)) {
10756: $domain=$posdom;
10757: last;
10758: }
10759: }
10760: return $domain;
10761: }
10762:
10763: # ------------------------------------------------------------- Declutters URLs
10764:
10765: sub declutter {
10766: my $thisfn=shift;
10767: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
10768: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10769: $thisfn=~s/^\///;
10770: $thisfn=~s|^adm/wrapper/||;
10771: $thisfn=~s|^adm/coursedocs/showdoc/||;
10772: $thisfn=~s/^res\///;
10773: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10774: $thisfn=~s/\?.+$//;
10775: }
10776: return $thisfn;
10777: }
10778:
10779: # ------------------------------------------------------------- Clutter up URLs
10780:
10781: sub clutter {
10782: my $thisfn='/'.&declutter(shift);
10783: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
10784: || $thisfn =~ m{^/adm/(includes|pages)} ) {
10785: $thisfn='/res'.$thisfn;
10786: }
10787: if ($thisfn !~m|^/adm|) {
10788: if ($thisfn =~ m|^/ext/|) {
10789: $thisfn='/adm/wrapper'.$thisfn;
10790: } else {
10791: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10792: my $embstyle=&Apache::loncommon::fileembstyle($ext);
10793: if ($embstyle eq 'ssi'
10794: || ($embstyle eq 'hdn')
10795: || ($embstyle eq 'rat')
10796: || ($embstyle eq 'prv')
10797: || ($embstyle eq 'ign')) {
10798: #do nothing with these
10799: } elsif (($embstyle eq 'img')
10800: || ($embstyle eq 'emb')
10801: || ($embstyle eq 'wrp')) {
10802: $thisfn='/adm/wrapper'.$thisfn;
10803: } elsif ($embstyle eq 'unk'
10804: && $thisfn!~/\.(sequence|page)$/) {
10805: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
10806: } else {
10807: # &logthis("Got a blank emb style");
10808: }
10809: }
10810: }
10811: return $thisfn;
10812: }
10813:
10814: sub clutter_with_no_wrapper {
10815: my $uri = &clutter(shift);
10816: if ($uri =~ m-^/adm/-) {
10817: $uri =~ s-^/adm/wrapper/-/-;
10818: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10819: }
10820: return $uri;
10821: }
10822:
10823: sub freeze_escape {
10824: my ($value)=@_;
10825: if (ref($value)) {
10826: $value=&nfreeze($value);
10827: return '__FROZEN__'.&escape($value);
10828: }
10829: return &escape($value);
10830: }
10831:
10832:
10833: sub thaw_unescape {
10834: my ($value)=@_;
10835: if ($value =~ /^__FROZEN__/) {
10836: substr($value,0,10,undef);
10837: $value=&unescape($value);
10838: return &thaw($value);
10839: }
10840: return &unescape($value);
10841: }
10842:
10843: sub correct_line_ends {
10844: my ($result)=@_;
10845: $$result =~s/\r\n/\n/mg;
10846: $$result =~s/\r/\n/mg;
10847: }
10848: # ================================================================ Main Program
10849:
10850: sub goodbye {
10851: &logthis("Starting Shut down");
10852: #not converted to using infrastruture and probably shouldn't be
10853: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
10854: #converted
10855: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
10856: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10857: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10858: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
10859: #1.1 only
10860: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10861: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10862: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10863: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10864: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
10865: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10866: &logthis(sprintf("%-20s is %s",'hits',$hits));
10867: &flushcourselogs();
10868: &logthis("Shutting down");
10869: }
10870:
10871: sub get_dns {
10872: my ($url,$func,$ignore_cache) = @_;
10873: if (!$ignore_cache) {
10874: my ($content,$cached)=
10875: &Apache::lonnet::is_cached_new('dns',$url);
10876: if ($cached) {
10877: &$func($content);
10878: return;
10879: }
10880: }
10881:
10882: my %alldns;
10883: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10884: foreach my $dns (<$config>) {
10885: next if ($dns !~ /^\^(\S*)/x);
10886: my $line = $1;
10887: my ($host,$protocol) = split(/:/,$line);
10888: if ($protocol ne 'https') {
10889: $protocol = 'http';
10890: }
10891: $alldns{$host} = $protocol;
10892: }
10893: while (%alldns) {
10894: my ($dns) = keys(%alldns);
10895: my $ua=new LWP::UserAgent;
10896: $ua->timeout(30);
10897: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
10898: my $response=$ua->request($request);
10899: delete($alldns{$dns});
10900: next if ($response->is_error());
10901: my @content = split("\n",$response->content);
10902: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
10903: &$func(\@content);
10904: return;
10905: }
10906: close($config);
10907: my $which = (split('/',$url))[3];
10908: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10909: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
10910: my @content = <$config>;
10911: &$func(\@content);
10912: return;
10913: }
10914: # ------------------------------------------------------------ Read domain file
10915: {
10916: my $loaded;
10917: my %domain;
10918:
10919: sub parse_domain_tab {
10920: my ($lines) = @_;
10921: foreach my $line (@$lines) {
10922: next if ($line =~ /^(\#|\s*$ )/x);
10923:
10924: chomp($line);
10925: my ($name,@elements) = split(/:/,$line,9);
10926: my %this_domain;
10927: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10928: 'lang_def', 'city', 'longi', 'lati',
10929: 'primary') {
10930: $this_domain{$field} = shift(@elements);
10931: }
10932: $domain{$name} = \%this_domain;
10933: }
10934: }
10935:
10936: sub reset_domain_info {
10937: undef($loaded);
10938: undef(%domain);
10939: }
10940:
10941: sub load_domain_tab {
10942: my ($ignore_cache) = @_;
10943: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
10944: my $fh;
10945: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10946: my @lines = <$fh>;
10947: &parse_domain_tab(\@lines);
10948: }
10949: close($fh);
10950: $loaded = 1;
10951: }
10952:
10953: sub domain {
10954: &load_domain_tab() if (!$loaded);
10955:
10956: my ($name,$what) = @_;
10957: return if ( !exists($domain{$name}) );
10958:
10959: if (!$what) {
10960: return $domain{$name}{'description'};
10961: }
10962: return $domain{$name}{$what};
10963: }
10964:
10965: sub domain_info {
10966: &load_domain_tab() if (!$loaded);
10967: return %domain;
10968: }
10969:
10970: }
10971:
10972:
10973: # ------------------------------------------------------------- Read hosts file
10974: {
10975: my %hostname;
10976: my %hostdom;
10977: my %libserv;
10978: my $loaded;
10979: my %name_to_host;
10980: my %internetdom;
10981: my %LC_dns_serv;
10982:
10983: sub parse_hosts_tab {
10984: my ($file) = @_;
10985: foreach my $configline (@$file) {
10986: next if ($configline =~ /^(\#|\s*$ )/x);
10987: chomp($configline);
10988: if ($configline =~ /^\^/) {
10989: if ($configline =~ /^\^([\w.\-]+)/) {
10990: $LC_dns_serv{$1} = 1;
10991: }
10992: next;
10993: }
10994: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
10995: $name=~s/\s//g;
10996: if ($id && $domain && $role && $name) {
10997: $hostname{$id}=$name;
10998: push(@{$name_to_host{$name}}, $id);
10999: $hostdom{$id}=$domain;
11000: if ($role eq 'library') { $libserv{$id}=$name; }
11001: if (defined($protocol)) {
11002: if ($protocol eq 'https') {
11003: $protocol{$id} = $protocol;
11004: } else {
11005: $protocol{$id} = 'http';
11006: }
11007: } else {
11008: $protocol{$id} = 'http';
11009: }
11010: if (defined($intdom)) {
11011: $internetdom{$id} = $intdom;
11012: }
11013: }
11014: }
11015: }
11016:
11017: sub reset_hosts_info {
11018: &purge_remembered();
11019: &reset_domain_info();
11020: &reset_hosts_ip_info();
11021: undef(%name_to_host);
11022: undef(%hostname);
11023: undef(%hostdom);
11024: undef(%libserv);
11025: undef($loaded);
11026: }
11027:
11028: sub load_hosts_tab {
11029: my ($ignore_cache) = @_;
11030: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
11031: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11032: my @config = <$config>;
11033: &parse_hosts_tab(\@config);
11034: close($config);
11035: $loaded=1;
11036: }
11037:
11038: sub hostname {
11039: &load_hosts_tab() if (!$loaded);
11040:
11041: my ($lonid) = @_;
11042: return $hostname{$lonid};
11043: }
11044:
11045: sub all_hostnames {
11046: &load_hosts_tab() if (!$loaded);
11047:
11048: return %hostname;
11049: }
11050:
11051: sub all_names {
11052: &load_hosts_tab() if (!$loaded);
11053:
11054: return %name_to_host;
11055: }
11056:
11057: sub all_host_domain {
11058: &load_hosts_tab() if (!$loaded);
11059: return %hostdom;
11060: }
11061:
11062: sub is_library {
11063: &load_hosts_tab() if (!$loaded);
11064:
11065: return exists($libserv{$_[0]});
11066: }
11067:
11068: sub all_library {
11069: &load_hosts_tab() if (!$loaded);
11070:
11071: return %libserv;
11072: }
11073:
11074: sub unique_library {
11075: #2x reverse removes all hostnames that appear more than once
11076: my %unique = reverse &all_library();
11077: return reverse %unique;
11078: }
11079:
11080: sub get_servers {
11081: &load_hosts_tab() if (!$loaded);
11082:
11083: my ($domain,$type) = @_;
11084: my %possible_hosts = ($type eq 'library') ? %libserv
11085: : %hostname;
11086: my %result;
11087: if (ref($domain) eq 'ARRAY') {
11088: while ( my ($host,$hostname) = each(%possible_hosts)) {
11089: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
11090: $result{$host} = $hostname;
11091: }
11092: }
11093: } else {
11094: while ( my ($host,$hostname) = each(%possible_hosts)) {
11095: if ($hostdom{$host} eq $domain) {
11096: $result{$host} = $hostname;
11097: }
11098: }
11099: }
11100: return %result;
11101: }
11102:
11103: sub get_unique_servers {
11104: my %unique = reverse &get_servers(@_);
11105: return reverse %unique;
11106: }
11107:
11108: sub host_domain {
11109: &load_hosts_tab() if (!$loaded);
11110:
11111: my ($lonid) = @_;
11112: return $hostdom{$lonid};
11113: }
11114:
11115: sub all_domains {
11116: &load_hosts_tab() if (!$loaded);
11117:
11118: my %seen;
11119: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11120: return @uniq;
11121: }
11122:
11123: sub internet_dom {
11124: &load_hosts_tab() if (!$loaded);
11125:
11126: my ($lonid) = @_;
11127: return $internetdom{$lonid};
11128: }
11129:
11130: sub is_LC_dns {
11131: &load_hosts_tab() if (!$loaded);
11132:
11133: my ($hostname) = @_;
11134: return exists($LC_dns_serv{$hostname});
11135: }
11136:
11137: }
11138:
11139: {
11140: my %iphost;
11141: my %name_to_ip;
11142: my %lonid_to_ip;
11143:
11144: sub get_hosts_from_ip {
11145: my ($ip) = @_;
11146: my %iphosts = &get_iphost();
11147: if (ref($iphosts{$ip})) {
11148: return @{$iphosts{$ip}};
11149: }
11150: return;
11151: }
11152:
11153: sub reset_hosts_ip_info {
11154: undef(%iphost);
11155: undef(%name_to_ip);
11156: undef(%lonid_to_ip);
11157: }
11158:
11159: sub get_host_ip {
11160: my ($lonid) = @_;
11161: if (exists($lonid_to_ip{$lonid})) {
11162: return $lonid_to_ip{$lonid};
11163: }
11164: my $name=&hostname($lonid);
11165: my $ip = gethostbyname($name);
11166: return if (!$ip || length($ip) ne 4);
11167: $ip=inet_ntoa($ip);
11168: $name_to_ip{$name} = $ip;
11169: $lonid_to_ip{$lonid} = $ip;
11170: return $ip;
11171: }
11172:
11173: sub get_iphost {
11174: my ($ignore_cache) = @_;
11175:
11176: if (!$ignore_cache) {
11177: if (%iphost) {
11178: return %iphost;
11179: }
11180: my ($ip_info,$cached)=
11181: &Apache::lonnet::is_cached_new('iphost','iphost');
11182: if ($cached) {
11183: %iphost = %{$ip_info->[0]};
11184: %name_to_ip = %{$ip_info->[1]};
11185: %lonid_to_ip = %{$ip_info->[2]};
11186: return %iphost;
11187: }
11188: }
11189:
11190: # get yesterday's info for fallback
11191: my %old_name_to_ip;
11192: my ($ip_info,$cached)=
11193: &Apache::lonnet::is_cached_new('iphost','iphost');
11194: if ($cached) {
11195: %old_name_to_ip = %{$ip_info->[1]};
11196: }
11197:
11198: my %name_to_host = &all_names();
11199: foreach my $name (keys(%name_to_host)) {
11200: my $ip;
11201: if (!exists($name_to_ip{$name})) {
11202: $ip = gethostbyname($name);
11203: if (!$ip || length($ip) ne 4) {
11204: if (defined($old_name_to_ip{$name})) {
11205: $ip = $old_name_to_ip{$name};
11206: &logthis("Can't find $name defaulting to old $ip");
11207: } else {
11208: &logthis("Name $name no IP found");
11209: next;
11210: }
11211: } else {
11212: $ip=inet_ntoa($ip);
11213: }
11214: $name_to_ip{$name} = $ip;
11215: } else {
11216: $ip = $name_to_ip{$name};
11217: }
11218: foreach my $id (@{ $name_to_host{$name} }) {
11219: $lonid_to_ip{$id} = $ip;
11220: }
11221: push(@{$iphost{$ip}},@{$name_to_host{$name}});
11222: }
11223: &Apache::lonnet::do_cache_new('iphost','iphost',
11224: [\%iphost,\%name_to_ip,\%lonid_to_ip],
11225: 48*60*60);
11226:
11227: return %iphost;
11228: }
11229:
11230: #
11231: # Given a DNS returns the loncapa host name for that DNS
11232: #
11233: sub host_from_dns {
11234: my ($dns) = @_;
11235: my @hosts;
11236: my $ip;
11237:
11238: if (exists($name_to_ip{$dns})) {
11239: $ip = $name_to_ip{$dns};
11240: }
11241: if (!$ip) {
11242: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11243: if (length($ip) == 4) {
11244: $ip = &IO::Socket::inet_ntoa($ip);
11245: }
11246: }
11247: if ($ip) {
11248: @hosts = get_hosts_from_ip($ip);
11249: return $hosts[0];
11250: }
11251: return undef;
11252: }
11253:
11254: sub get_internet_names {
11255: my ($lonid) = @_;
11256: return if ($lonid eq '');
11257: my ($idnref,$cached)=
11258: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11259: if ($cached) {
11260: return $idnref;
11261: }
11262: my $ip = &get_host_ip($lonid);
11263: my @hosts = &get_hosts_from_ip($ip);
11264: my %iphost = &get_iphost();
11265: my (@idns,%seen);
11266: foreach my $id (@hosts) {
11267: my $dom = &host_domain($id);
11268: my $prim_id = &domain($dom,'primary');
11269: my $prim_ip = &get_host_ip($prim_id);
11270: next if ($seen{$prim_ip});
11271: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11272: foreach my $id (@{$iphost{$prim_ip}}) {
11273: my $intdom = &internet_dom($id);
11274: unless (grep(/^\Q$intdom\E$/,@idns)) {
11275: push(@idns,$intdom);
11276: }
11277: }
11278: }
11279: $seen{$prim_ip} = 1;
11280: }
11281: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11282: }
11283:
11284: }
11285:
11286: sub all_loncaparevs {
11287: 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);
11288: }
11289:
11290: BEGIN {
11291:
11292: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11293: unless ($readit) {
11294: {
11295: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11296: %perlvar = (%perlvar,%{$configvars});
11297: }
11298:
11299:
11300: # ------------------------------------------------------ Read spare server file
11301: {
11302: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
11303:
11304: while (my $configline=<$config>) {
11305: chomp($configline);
11306: if ($configline) {
11307: my ($host,$type) = split(':',$configline,2);
11308: if (!defined($type) || $type eq '') { $type = 'default' };
11309: push(@{ $spareid{$type} }, $host);
11310: }
11311: }
11312: close($config);
11313: }
11314: # ------------------------------------------------------------ Read permissions
11315: {
11316: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
11317:
11318: while (my $configline=<$config>) {
11319: chomp($configline);
11320: if ($configline) {
11321: my ($role,$perm)=split(/ /,$configline);
11322: if ($perm ne '') { $pr{$role}=$perm; }
11323: }
11324: }
11325: close($config);
11326: }
11327:
11328: # -------------------------------------------- Read plain texts for permissions
11329: {
11330: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
11331:
11332: while (my $configline=<$config>) {
11333: chomp($configline);
11334: if ($configline) {
11335: my ($short,@plain)=split(/:/,$configline);
11336: %{$prp{$short}} = ();
11337: if (@plain > 0) {
11338: $prp{$short}{'std'} = $plain[0];
11339: for (my $i=1; $i<@plain; $i++) {
11340: $prp{$short}{'alt'.$i} = $plain[$i];
11341: }
11342: }
11343: }
11344: }
11345: close($config);
11346: }
11347:
11348: # ---------------------------------------------------------- Read package table
11349: {
11350: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
11351:
11352: while (my $configline=<$config>) {
11353: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
11354: chomp($configline);
11355: my ($short,$plain)=split(/:/,$configline);
11356: my ($pack,$name)=split(/\&/,$short);
11357: if ($plain ne '') {
11358: $packagetab{$pack.'&'.$name.'&name'}=$name;
11359: $packagetab{$short}=$plain;
11360: }
11361: }
11362: close($config);
11363: }
11364:
11365: # ---------------------------------------------------------- Read loncaparev table
11366: {
11367: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11368: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11369: while (my $configline=<$config>) {
11370: chomp($configline);
11371: my ($hostid,$loncaparev)=split(/:/,$configline);
11372: $loncaparevs{$hostid}=$loncaparev;
11373: }
11374: close($config);
11375: }
11376: }
11377: }
11378:
11379: # ---------------------------------------------------------- Read serverhostID table
11380: {
11381: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11382: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11383: while (my $configline=<$config>) {
11384: chomp($configline);
11385: my ($name,$id)=split(/:/,$configline);
11386: $serverhomeIDs{$name}=$id;
11387: }
11388: close($config);
11389: }
11390: }
11391: }
11392:
11393: {
11394: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11395: if (-e $file) {
11396: my $parser = HTML::LCParser->new($file);
11397: while (my $token = $parser->get_token()) {
11398: if ($token->[0] eq 'S') {
11399: my $item = $token->[1];
11400: my $name = $token->[2]{'name'};
11401: my $value = $token->[2]{'value'};
11402: if ($item ne '' && $name ne '' && $value ne '') {
11403: my $release = $parser->get_text();
11404: $release =~ s/(^\s*|\s*$ )//gx;
11405: $needsrelease{$item.':'.$name.':'.$value} = $release;
11406: }
11407: }
11408: }
11409: }
11410: }
11411:
11412: # ---------------------------------------------------------- Read managers table
11413: {
11414: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11415: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11416: while (my $configline=<$config>) {
11417: chomp($configline);
11418: next if ($configline =~ /^\#/);
11419: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11420: $managerstab{$configline} = 1;
11421: }
11422: }
11423: close($config);
11424: }
11425: }
11426: }
11427:
11428: # ------------- set up temporary directory
11429: {
11430: $tmpdir = LONCAPA::tempdir();
11431:
11432: }
11433:
11434: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11435: 'compress_threshold'=> 20_000,
11436: });
11437:
11438: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
11439: $dumpcount=0;
11440: $locknum=0;
11441:
11442: &logtouch();
11443: &logthis('<font color="yellow">INFO: Read configuration</font>');
11444: $readit=1;
11445: {
11446: use integer;
11447: my $test=(2**32)+1;
11448: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
11449: &logthis(" Detected 64bit platform ($_64bit)");
11450: }
11451: }
11452: }
11453:
11454: 1;
11455: __END__
11456:
11457: =pod
11458:
11459: =head1 NAME
11460:
11461: Apache::lonnet - Subroutines to ask questions about things in the network.
11462:
11463: =head1 SYNOPSIS
11464:
11465: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
11466:
11467: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11468:
11469: Common parameters:
11470:
11471: =over 4
11472:
11473: =item *
11474:
11475: $uname : an internal username (if $cname expecting a course Id specifically)
11476:
11477: =item *
11478:
11479: $udom : a domain (if $cdom expecting a course's domain specifically)
11480:
11481: =item *
11482:
11483: $symb : a resource instance identifier
11484:
11485: =item *
11486:
11487: $namespace : the name of a .db file that contains the data needed or
11488: being set.
11489:
11490: =back
11491:
11492: =head1 OVERVIEW
11493:
11494: lonnet provides subroutines which interact with the
11495: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11496: about classes, users, and resources.
11497:
11498: For many of these objects you can also use this to store data about
11499: them or modify them in various ways.
11500:
11501: =head2 Symbs
11502:
11503: To identify a specific instance of a resource, LON-CAPA uses symbols
11504: or "symbs"X<symb>. These identifiers are built from the URL of the
11505: map, the resource number of the resource in the map, and the URL of
11506: the resource itself. The latter is somewhat redundant, but might help
11507: if maps change.
11508:
11509: An example is
11510:
11511: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11512:
11513: The respective map entry is
11514:
11515: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11516: title="Problem 2">
11517: </resource>
11518:
11519: Symbs are used by the random number generator, as well as to store and
11520: restore data specific to a certain instance of for example a problem.
11521:
11522: =head2 Storing And Retrieving Data
11523:
11524: X<store()>X<cstore()>X<restore()>Three of the most important functions
11525: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11526: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11527: is is the non-critical message twin of cstore. These functions are for
11528: handlers to store a perl hash to a user's permanent data space in an
11529: easy manner, and to retrieve it again on another call. It is expected
11530: that a handler would use this once at the beginning to retrieve data,
11531: and then again once at the end to send only the new data back.
11532:
11533: The data is stored in the user's data directory on the user's
11534: homeserver under the ID of the course.
11535:
11536: The hash that is returned by restore will have all of the previous
11537: value for all of the elements of the hash.
11538:
11539: Example:
11540:
11541: #creating a hash
11542: my %hash;
11543: $hash{'foo'}='bar';
11544:
11545: #storing it
11546: &Apache::lonnet::cstore(\%hash);
11547:
11548: #changing a value
11549: $hash{'foo'}='notbar';
11550:
11551: #adding a new value
11552: $hash{'bar'}='foo';
11553: &Apache::lonnet::cstore(\%hash);
11554:
11555: #retrieving the hash
11556: my %history=&Apache::lonnet::restore();
11557:
11558: #print the hash
11559: foreach my $key (sort(keys(%history))) {
11560: print("\%history{$key} = $history{$key}");
11561: }
11562:
11563: Will print out:
11564:
11565: %history{1:foo} = bar
11566: %history{1:keys} = foo:timestamp
11567: %history{1:timestamp} = 990455579
11568: %history{2:bar} = foo
11569: %history{2:foo} = notbar
11570: %history{2:keys} = foo:bar:timestamp
11571: %history{2:timestamp} = 990455580
11572: %history{bar} = foo
11573: %history{foo} = notbar
11574: %history{timestamp} = 990455580
11575: %history{version} = 2
11576:
11577: Note that the special hash entries C<keys>, C<version> and
11578: C<timestamp> were added to the hash. C<version> will be equal to the
11579: total number of versions of the data that have been stored. The
11580: C<timestamp> attribute will be the UNIX time the hash was
11581: stored. C<keys> is available in every historical section to list which
11582: keys were added or changed at a specific historical revision of a
11583: hash.
11584:
11585: B<Warning>: do not store the hash that restore returns directly. This
11586: will cause a mess since it will restore the historical keys as if the
11587: were new keys. I.E. 1:foo will become 1:1:foo etc.
11588:
11589: Calling convention:
11590:
11591: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11592: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
11593:
11594: For more detailed information, see lonnet specific documentation.
11595:
11596: =head1 RETURN MESSAGES
11597:
11598: =over 4
11599:
11600: =item * B<con_lost>: unable to contact remote host
11601:
11602: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11603: when the connection is brought back up
11604:
11605: =item * B<con_failed>: unable to contact remote host and unable to save message
11606: for later delivery
11607:
11608: =item * B<error:>: an error a occurred, a description of the error follows the :
11609:
11610: =item * B<no_such_host>: unable to fund a host associated with the user/domain
11611: that was requested
11612:
11613: =back
11614:
11615: =head1 PUBLIC SUBROUTINES
11616:
11617: =head2 Session Environment Functions
11618:
11619: =over 4
11620:
11621: =item *
11622: X<appenv()>
11623: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
11624: the user envirnoment file, and will be restored for each access this
11625: user makes during this session, also modifies the %env for the current
11626: process. Optional rolesarrayref - if defined contains a reference to an array
11627: of roles which are exempt from the restriction on modifying user.role entries
11628: in the user's environment.db and in %env.
11629:
11630: =item *
11631: X<delenv()>
11632: B<delenv($delthis,$regexp)>: removes all items from the session
11633: environment file that begin with $delthis. If the
11634: optional second arg - $regexp - is true, $delthis is treated as a
11635: regular expression, otherwise \Q$delthis\E is used.
11636: The values are also deleted from the current processes %env.
11637:
11638: =item * get_env_multiple($name)
11639:
11640: gets $name from the %env hash, it seemlessly handles the cases where multiple
11641: values may be defined and end up as an array ref.
11642:
11643: returns an array of values
11644:
11645: =back
11646:
11647: =head2 User Information
11648:
11649: =over 4
11650:
11651: =item *
11652: X<queryauthenticate()>
11653: B<queryauthenticate($uname,$udom)>: try to determine user's current
11654: authentication scheme
11655:
11656: =item *
11657: X<authenticate()>
11658: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
11659: authenticate user from domain's lib servers (first use the current
11660: one). C<$upass> should be the users password.
11661: $checkdefauth is optional (value is 1 if a check should be made to
11662: authenticate user using default authentication method, and allow
11663: account creation if username does not have account in the domain).
11664: $clientcancheckhost is optional (value is 1 if checking whether the
11665: server can host will occur on the client side in lonauth.pm).
11666:
11667: =item *
11668: X<homeserver()>
11669: B<homeserver($uname,$udom)>: find the server which has
11670: the user's directory and files (there must be only one), this caches
11671: the answer, and also caches if there is a borken connection.
11672:
11673: =item *
11674: X<idget()>
11675: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11676: (IDs are a unique resource in a domain, there must be only 1 ID per
11677: username, and only 1 username per ID in a specific domain) (returns
11678: hash: id=>name,id=>name)
11679:
11680: =item *
11681: X<idrget()>
11682: B<idrget($udom,@unames)>: find the IDs behind a list of
11683: usernames (returns hash: name=>id,name=>id)
11684:
11685: =item *
11686: X<idput()>
11687: B<idput($udom,%ids)>: store away a list of names and associated IDs
11688:
11689: =item *
11690: X<rolesinit()>
11691: B<rolesinit($udom,$username,$authhost)>: get user privileges
11692:
11693: =item *
11694: X<getsection()>
11695: B<getsection($udom,$uname,$cname)>: finds the section of student in the
11696: course $cname, return section name/number or '' for "not in course"
11697: and '-1' for "no section"
11698:
11699: =item *
11700: X<userenvironment()>
11701: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
11702: passed in @what from the requested user's environment, returns a hash
11703:
11704: =item *
11705: X<userlog_query()>
11706: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11707: activity.log file. %filters defines filters applied when parsing the
11708: log file. These can be start or end timestamps, or the type of action
11709: - log to look for Login or Logout events, check for Checkin or
11710: Checkout, role for role selection. The response is in the form
11711: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11712: escaped strings of the action recorded in the activity.log file.
11713:
11714: =back
11715:
11716: =head2 User Roles
11717:
11718: =over 4
11719:
11720: =item *
11721:
11722: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
11723: F: full access
11724: U,I,K: authentication modes (cxx only)
11725: '': forbidden
11726: 1: user needs to choose course
11727: 2: browse allowed
11728: A: passphrase authentication needed
11729:
11730: =item *
11731:
11732: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11733: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11734: and course level
11735:
11736: =item *
11737:
11738: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11739: (rolesplain.tab); plain text explanation of a user role term.
11740: $type is Course (default) or Community.
11741: If $forcedefault evaluates to true, text returned will be default
11742: text for $type. Otherwise, if this is a course, the text returned
11743: will be a custom name for the role (if defined in the course's
11744: environment). If no custom name is defined the default is returned.
11745:
11746: =item *
11747:
11748: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
11749: All arguments are optional. Returns a hash of a roles, either for
11750: co-author/assistant author roles for a user's Construction Space
11751: (default), or if $context is 'userroles', roles for the user himself,
11752: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11753: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11754: For each key, value is set to colon-separated start and end times for
11755: the role. If no username and domain are specified, will default to
11756: current user/domain. Types, roles, and roledoms are references to arrays
11757: of role statuses (active, future or previous), roles
11758: (e.g., cc,in, st etc.) and domains of the roles which can be used
11759: to restrict the list of roles reported. If no array ref is
11760: provided for types, will default to return only active roles.
11761:
11762: =back
11763:
11764: =head2 User Modification
11765:
11766: =over 4
11767:
11768: =item *
11769:
11770: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
11771: user for the level given by URL. Optional start and end dates (leave empty
11772: string or zero for "no date")
11773:
11774: =item *
11775:
11776: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11777: change a users, password, possible return values are: ok,
11778: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11779: refused
11780:
11781: =item *
11782:
11783: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
11784:
11785: =item *
11786:
11787: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11788: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11789:
11790: will update user information (firstname,middlename,lastname,generation,
11791: permanentemail), and if forceid is true, student/employee ID also.
11792: A user's institutional affiliation(s) can also be updated.
11793: User information fields will not be overwritten with empty entries
11794: unless the field is included in the $candelete array reference.
11795: This array is included when a single user is modified via "Manage Users",
11796: or when Autoupdate.pl is run by cron in a domain.
11797:
11798: =item *
11799:
11800: modifystudent
11801:
11802: modify a student's enrollment and identification information.
11803: The course id is resolved based on the current users environment.
11804: This means the envoking user must be a course coordinator or otherwise
11805: associated with a course.
11806:
11807: This call is essentially a wrapper for lonnet::modifyuser and
11808: lonnet::modify_student_enrollment
11809:
11810: Inputs:
11811:
11812: =over 4
11813:
11814: =item B<$udom> Student's loncapa domain
11815:
11816: =item B<$uname> Student's loncapa login name
11817:
11818: =item B<$uid> Student/Employee ID
11819:
11820: =item B<$umode> Student's authentication mode
11821:
11822: =item B<$upass> Student's password
11823:
11824: =item B<$first> Student's first name
11825:
11826: =item B<$middle> Student's middle name
11827:
11828: =item B<$last> Student's last name
11829:
11830: =item B<$gene> Student's generation
11831:
11832: =item B<$usec> Student's section in course
11833:
11834: =item B<$end> Unix time of the roles expiration
11835:
11836: =item B<$start> Unix time of the roles start date
11837:
11838: =item B<$forceid> If defined, allow $uid to be changed
11839:
11840: =item B<$desiredhome> server to use as home server for student
11841:
11842: =item B<$email> Student's permanent e-mail address
11843:
11844: =item B<$type> Type of enrollment (auto or manual)
11845:
11846: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11847:
11848: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
11849:
11850: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
11851:
11852: =item B<$context> role change context (shown in User Management Logs display in a course)
11853:
11854: =item B<$inststatus> institutional status of user - : separated string of escaped status types
11855:
11856: =back
11857:
11858: =item *
11859:
11860: modify_student_enrollment
11861:
11862: Change a students enrollment status in a class. The environment variable
11863: 'role.request.course' must be defined for this function to proceed.
11864:
11865: Inputs:
11866:
11867: =over 4
11868:
11869: =item $udom, students domain
11870:
11871: =item $uname, students name
11872:
11873: =item $uid, students user id
11874:
11875: =item $first, students first name
11876:
11877: =item $middle
11878:
11879: =item $last
11880:
11881: =item $gene
11882:
11883: =item $usec
11884:
11885: =item $end
11886:
11887: =item $start
11888:
11889: =item $type
11890:
11891: =item $locktype
11892:
11893: =item $cid
11894:
11895: =item $selfenroll
11896:
11897: =item $context
11898:
11899: =back
11900:
11901:
11902: =item *
11903:
11904: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11905: custom role; give a custom role to a user for the level given by URL. Specify
11906: name and domain of role author, and role name
11907:
11908: =item *
11909:
11910: revokerole($udom,$uname,$url,$role) : revoke a role for url
11911:
11912: =item *
11913:
11914: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11915:
11916: =back
11917:
11918: =head2 Course Infomation
11919:
11920: =over 4
11921:
11922: =item *
11923:
11924: coursedescription($courseid,$options) : returns a hash of information about the
11925: specified course id, including all environment settings for the
11926: course, the description of the course will be in the hash under the
11927: key 'description'
11928:
11929: $options is an optional parameter that if supplied is a hash reference that controls
11930: what how this function works. It has the following key/values:
11931:
11932: =over 4
11933:
11934: =item freshen_cache
11935:
11936: If defined, and the environment cache for the course is valid, it is
11937: returned in the returned hash.
11938:
11939: =item one_time
11940:
11941: If defined, the last cache time is set to _now_
11942:
11943: =item user
11944:
11945: If defined, the supplied username is used instead of the current user.
11946:
11947:
11948: =back
11949:
11950: =item *
11951:
11952: resdata($name,$domain,$type,@which) : request for current parameter
11953: setting for a specific $type, where $type is either 'course' or 'user',
11954: @what should be a list of parameters to ask about. This routine caches
11955: answers for 5 minutes.
11956:
11957: =item *
11958:
11959: get_courseresdata($courseid, $domain) : dump the entire course resource
11960: data base, returning a hash that is keyed by the resource name and has
11961: values that are the resource value. I believe that the timestamps and
11962: versions are also returned.
11963:
11964:
11965: =back
11966:
11967: =head2 Course Modification
11968:
11969: =over 4
11970:
11971: =item *
11972:
11973: writecoursepref($courseid,%prefs) : write preferences (environment
11974: database) for a course
11975:
11976: =item *
11977:
11978: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11979:
11980: =item *
11981:
11982: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
11983:
11984: =item *
11985:
11986: is_course($courseid), is_course($cdom, $cnum)
11987:
11988: Accepts either a combined $courseid (in the form of domain_courseid) or the
11989: two component version $cdom, $cnum. It checks if the specified course exists.
11990:
11991: Returns:
11992: undef if the course doesn't exist, otherwise
11993: in scalar context the combined courseid.
11994: in list context the two components of the course identifier, domain and
11995: courseid.
11996:
11997: =back
11998:
11999: =head2 Resource Subroutines
12000:
12001: =over 4
12002:
12003: =item *
12004:
12005: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
12006:
12007: =item *
12008:
12009: repcopy($filename) : subscribes to the requested file, and attempts to
12010: replicate from the owning library server, Might return
12011: 'unavailable', 'not_found', 'forbidden', 'ok', or
12012: 'bad_request', also attempts to grab the metadata for the
12013: resource. Expects the local filesystem pathname
12014: (/home/httpd/html/res/....)
12015:
12016: =back
12017:
12018: =head2 Resource Information
12019:
12020: =over 4
12021:
12022: =item *
12023:
12024: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12025: a vairety of different possible values, $varname should be a request
12026: string, and the other parameters can be used to specify who and what
12027: one is asking about.
12028:
12029: Possible values for $varname are environment.lastname (or other item
12030: from the envirnment hash), user.name (or someother aspect about the
12031: user), resource.0.maxtries (or some other part and parameter of a
12032: resource)
12033:
12034: =item *
12035:
12036: directcondval($number) : get current value of a condition; reads from a state
12037: string
12038:
12039: =item *
12040:
12041: condval($condidx) : value of condition index based on state
12042:
12043: =item *
12044:
12045: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12046: resource's metadata, $what should be either a specific key, or either
12047: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12048: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12049:
12050: this function automatically caches all requests
12051:
12052: =item *
12053:
12054: metadata_query($query,$custom,$customshow) : make a metadata query against the
12055: network of library servers; returns file handle of where SQL and regex results
12056: will be stored for query
12057:
12058: =item *
12059:
12060: symbread($filename) : return symbolic list entry (filename argument optional);
12061: returns the data handle
12062:
12063: =item *
12064:
12065: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
12066: a possible symb for the URL in $thisfn, and if is an encryypted
12067: resource that the user accessed using /enc/ returns a 1 on success, 0
12068: on failure, user must be in a course, as it assumes the existance of
12069: the course initial hash, and uses $env('request.course.id'}
12070:
12071:
12072: =item *
12073:
12074: symbclean($symb) : removes versions numbers from a symb, returns the
12075: cleaned symb
12076:
12077: =item *
12078:
12079: is_on_map($uri) : checks if the $uri is somewhere on the current
12080: course map, user must be in a course for it to work.
12081:
12082: =item *
12083:
12084: numval($salt) : return random seed value (addend for rndseed)
12085:
12086: =item *
12087:
12088: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12089: a random seed, all arguments are optional, if they aren't sent it uses the
12090: environment to derive them. Note: if symb isn't sent and it can't get one
12091: from &symbread it will use the current time as its return value
12092:
12093: =item *
12094:
12095: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12096: unfakeable, receipt
12097:
12098: =item *
12099:
12100: receipt() : API to ireceipt working off of env values; given out to users
12101:
12102: =item *
12103:
12104: countacc($url) : count the number of accesses to a given URL
12105:
12106: =item *
12107:
12108: 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
12109:
12110: =item *
12111:
12112: 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)
12113:
12114: =item *
12115:
12116: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
12117:
12118: =item *
12119:
12120: devalidate($symb) : devalidate temporary spreadsheet calculations,
12121: forcing spreadsheet to reevaluate the resource scores next time.
12122:
12123: =back
12124:
12125: =head2 Storing/Retreiving Data
12126:
12127: =over 4
12128:
12129: =item *
12130:
12131: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12132: for this url; hashref needs to be given and should be a \%hashname; the
12133: remaining args aren't required and if they aren't passed or are '' they will
12134: be derived from the env
12135:
12136: =item *
12137:
12138: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12139: uses critical subroutine
12140:
12141: =item *
12142:
12143: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12144: all args are optional
12145:
12146: =item *
12147:
12148: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12149: dumps the complete (or key matching regexp) namespace into a hash
12150: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12151: normally &store()ed into
12152:
12153: $range should be either an integer '100' (give me the first 100
12154: matching records)
12155: or be two integers sperated by a - with no spaces
12156: '30-50' (give me the 30th through the 50th matching
12157: records)
12158:
12159:
12160: =item *
12161:
12162: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12163: replaces a &store() version of data with a replacement set of data
12164: for a particular resource in a namespace passed in the $storehash hash
12165: reference
12166:
12167: =item *
12168:
12169: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12170: works very similar to store/cstore, but all data is stored in a
12171: temporary location and can be reset using tmpreset, $storehash should
12172: be a hash reference, returns nothing on success
12173:
12174: =item *
12175:
12176: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12177: similar to restore, but all data is stored in a temporary location and
12178: can be reset using tmpreset. Returns a hash of values on success,
12179: error string otherwise.
12180:
12181: =item *
12182:
12183: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12184: deltes all keys for $symb form the temporary storage hash.
12185:
12186: =item *
12187:
12188: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12189: reference filled in from namesp ($udom and $uname are optional)
12190:
12191: =item *
12192:
12193: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12194: namesp ($udom and $uname are optional)
12195:
12196: =item *
12197:
12198: dump($namespace,$udom,$uname,$regexp,$range) :
12199: dumps the complete (or key matching regexp) namespace into a hash
12200: ($udom, $uname, $regexp, $range are optional)
12201:
12202: $range should be either an integer '100' (give me the first 100
12203: matching records)
12204: or be two integers sperated by a - with no spaces
12205: '30-50' (give me the 30th through the 50th matching
12206: records)
12207: =item *
12208:
12209: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12210: $store can be a scalar, an array reference, or if the amount to be
12211: incremented is > 1, a hash reference.
12212:
12213: ($udom and $uname are optional)
12214:
12215: =item *
12216:
12217: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12218: ($udom and $uname are optional)
12219:
12220: =item *
12221:
12222: cput($namespace,$storehash,$udom,$uname) : critical put
12223: ($udom and $uname are optional)
12224:
12225: =item *
12226:
12227: newput($namespace,$storehash,$udom,$uname) :
12228:
12229: Attempts to store the items in the $storehash, but only if they don't
12230: currently exist, if this succeeds you can be certain that you have
12231: successfully created a new key value pair in the $namespace db.
12232:
12233:
12234: Args:
12235: $namespace: name of database to store values to
12236: $storehash: hashref to store to the db
12237: $udom: (optional) domain of user containing the db
12238: $uname: (optional) name of user caontaining the db
12239:
12240: Returns:
12241: 'ok' -> succeeded in storing all keys of $storehash
12242: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12243: least <key> already existed in the db (other
12244: requested keys may also already exist)
12245: 'error: <msg>' -> unable to tie the DB or other error occurred
12246: 'con_lost' -> unable to contact request server
12247: 'refused' -> action was not allowed by remote machine
12248:
12249:
12250: =item *
12251:
12252: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12253: reference filled in from namesp (encrypts the return communication)
12254: ($udom and $uname are optional)
12255:
12256: =item *
12257:
12258: log($udom,$name,$home,$message) : write to permanent log for user; use
12259: critical subroutine
12260:
12261: =item *
12262:
12263: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12264: array reference filled in from namespace found in domain level on either
12265: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
12266:
12267: =item *
12268:
12269: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12270: domain level either on specified domain server ($uhome) or primary domain
12271: server ($udom and $uhome are optional)
12272:
12273: =item *
12274:
12275: get_domain_defaults($target_domain) : returns hash with defaults for
12276: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12277: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12278: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12279: Values are retrieved from cache (if current), or from domain's configuration.db
12280: (if available), or lastly from values in lonTabs/dns_domain,tab,
12281: or lonTabs/domain.tab.
12282:
12283: %domdefaults = &get_auth_defaults($target_domain);
12284:
12285: =back
12286:
12287: =head2 Network Status Functions
12288:
12289: =over 4
12290:
12291: =item *
12292:
12293: dirlist() : return directory list based on URI (first arg).
12294:
12295: Inputs: 1 required, 5 optional.
12296:
12297: =over
12298:
12299: =item
12300: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12301:
12302: =item
12303: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12304:
12305: =item
12306: $username - username of user/course to be listed. Extracted from $uri if absent.
12307:
12308: =item
12309: $getpropath - boolean: 1 if prepend path using &propath().
12310:
12311: =item
12312: $getuserdir - boolean: 1 if prepend path for "userfiles".
12313:
12314: =item
12315: $alternateRoot - path to prepend in place of path from $uri.
12316:
12317: =back
12318:
12319: Returns: Array of up to two items.
12320:
12321: =over
12322:
12323: a reference to an array of files/subdirectories
12324:
12325: =over
12326:
12327: Each element in the array of files/subdirectories is a & separated list of
12328: item name and the result of running stat on the item. If dirlist was requested
12329: for a file instead of a directory, the item name will be ''. For a directory
12330: listing, if the item is a metadata file, the element will end &N&M
12331: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12332: default copyright set (1).
12333:
12334: =back
12335:
12336: a scalar containing error condition (if encountered).
12337:
12338: =over
12339:
12340: =item
12341: no_host (no homeserver identified for $username:$domain).
12342:
12343: =item
12344: no_such_host (server contacted for listing not identified as valid host).
12345:
12346: =item
12347: con_lost (connection to remote server failed).
12348:
12349: =item
12350: refused (invalid $username:$domain received on lond side).
12351:
12352: =item
12353: no_such_dir (directory at specified path on lond side does not exist).
12354:
12355: =item
12356: empty (directory at specified path on lond side is empty).
12357:
12358: =over
12359:
12360: This is currently not encountered because the &ls3, &ls2,
12361: &ls (_handler) routines on the lond side do not filter out
12362: . and .. from a directory listing.
12363:
12364: =back
12365:
12366: =back
12367:
12368: =back
12369:
12370: =item *
12371:
12372: spareserver() : find server with least workload from spare.tab
12373:
12374:
12375: =item *
12376:
12377: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12378: if there is no corresponding loncapa host.
12379:
12380: =back
12381:
12382:
12383: =head2 Apache Request
12384:
12385: =over 4
12386:
12387: =item *
12388:
12389: ssi($url,%hash) : server side include, does a complete request cycle on url to
12390: localhost, posts hash
12391:
12392: =back
12393:
12394: =head2 Data to String to Data
12395:
12396: =over 4
12397:
12398: =item *
12399:
12400: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12401: and '&' separators, supports elements that are arrayrefs and hashrefs
12402:
12403: =item *
12404:
12405: hashref2str($hashref) : convert a hashref into a string complete with
12406: escaping and '=' and '&' separators, supports elements that are
12407: arrayrefs and hashrefs
12408:
12409: =item *
12410:
12411: arrayref2str($arrayref) : convert an arrayref into a string complete
12412: with escaping and '&' separators, supports elements that are arrayrefs
12413: and hashrefs
12414:
12415: =item *
12416:
12417: str2hash($string) : convert string to hash using unescaping and
12418: splitting on '=' and '&', supports elements that are arrayrefs and
12419: hashrefs
12420:
12421: =item *
12422:
12423: str2array($string) : convert string to hash using unescaping and
12424: splitting on '&', supports elements that are arrayrefs and hashrefs
12425:
12426: =back
12427:
12428: =head2 Logging Routines
12429:
12430:
12431: These routines allow one to make log messages in the lonnet.log and
12432: lonnet.perm logfiles.
12433:
12434: =over 4
12435:
12436: =item *
12437:
12438: logtouch() : make sure the logfile, lonnet.log, exists
12439:
12440: =item *
12441:
12442: logthis() : append message to the normal lonnet.log file, it gets
12443: preiodically rolled over and deleted.
12444:
12445: =item *
12446:
12447: logperm() : append a permanent message to lonnet.perm.log, this log
12448: file never gets deleted by any automated portion of the system, only
12449: messages of critical importance should go in here.
12450:
12451:
12452: =back
12453:
12454: =head2 General File Helper Routines
12455:
12456: =over 4
12457:
12458: =item *
12459:
12460: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12461: (a) files in /uploaded
12462: (i) If a local copy of the file exists -
12463: compares modification date of local copy with last-modified date for
12464: definitive version stored on home server for course. If local copy is
12465: stale, requests a new version from the home server and stores it.
12466: If the original has been removed from the home server, then local copy
12467: is unlinked.
12468: (ii) If local copy does not exist -
12469: requests the file from the home server and stores it.
12470:
12471: If $caller is 'uploadrep':
12472: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12473: for request for files originally uploaded via DOCS.
12474: - returns 'ok' if fresh local copy now available, -1 otherwise.
12475:
12476: Otherwise:
12477: This indicates a call from the content generation phase of the request.
12478: - returns the entire contents of the file or -1.
12479:
12480: (b) files in /res
12481: - returns the entire contents of a file or -1;
12482: it properly subscribes to and replicates the file if neccessary.
12483:
12484:
12485: =item *
12486:
12487: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12488: reference
12489:
12490: returns either a stat() list of data about the file or an empty list
12491: if the file doesn't exist or couldn't find out about it (connection
12492: problems or user unknown)
12493:
12494: =item *
12495:
12496: filelocation($dir,$file) : returns file system location of a file
12497: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12498: directory that relative $file lookups are to looked in ($dir of /a/dir
12499: and a file of ../bob will become /a/bob)
12500:
12501: =item *
12502:
12503: hreflocation($dir,$file) : returns file system location or a URL; same as
12504: filelocation except for hrefs
12505:
12506: =item *
12507:
12508: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12509:
12510: =back
12511:
12512: =head2 Usererfile file routines (/uploaded*)
12513:
12514: =over 4
12515:
12516: =item *
12517:
12518: userfileupload(): main rotine for putting a file in a user or course's
12519: filespace, arguments are,
12520:
12521: formname - required - this is the name of the element in $env where the
12522: filename, and the contents of the file to create/modifed exist
12523: the filename is in $env{'form.'.$formname.'.filename'} and the
12524: contents of the file is located in $env{'form.'.$formname}
12525: context - if coursedoc, store the file in the course of the active role
12526: of the current user;
12527: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12528: if 'canceloverwrite': delete file in tmp/overwrites directory
12529: subdir - required - subdirectory to put the file in under ../userfiles/
12530: if undefined, it will be placed in "unknown"
12531:
12532: (This routine calls clean_filename() to remove any dangerous
12533: characters from the filename, and then calls finuserfileupload() to
12534: complete the transaction)
12535:
12536: returns either the url of the uploaded file (/uploaded/....) if successful
12537: and /adm/notfound.html if unsuccessful
12538:
12539: =item *
12540:
12541: clean_filename(): routine for cleaing a filename up for storage in
12542: userfile space, argument is:
12543:
12544: filename - proposed filename
12545:
12546: returns: the new clean filename
12547:
12548: =item *
12549:
12550: finishuserfileupload(): routine that creates and sends the file to
12551: userspace, probably shouldn't be called directly
12552:
12553: docuname: username or courseid of destination for the file
12554: docudom: domain of user/course of destination for the file
12555: formname: same as for userfileupload()
12556: fname: filename (including subdirectories) for the file
12557: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12558: allfiles: reference to hash used to store objects found by parser
12559: codebase: reference to hash used for codebases of java objects found by parser
12560: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12561: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12562: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12563: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12564: context: if 'overwrite', will move the uploaded file from its temporary location to
12565: userfiles to facilitate overwriting a previously uploaded file with same name.
12566: mimetype: reference to scalar to accommodate mime type determined
12567: from File::MMagic if $parser = parse.
12568:
12569: returns either the url of the uploaded file (/uploaded/....) if successful
12570: and /adm/notfound.html if unsuccessful (or an error message if context
12571: was 'overwrite').
12572:
12573:
12574: =item *
12575:
12576: renameuserfile(): renames an existing userfile to a new name
12577:
12578: Args:
12579: docuname: username or courseid of destination for the file
12580: docudom: domain of user/course of destination for the file
12581: old: current file name (including any subdirs under userfiles)
12582: new: desired file name (including any subdirs under userfiles)
12583:
12584: =item *
12585:
12586: mkdiruserfile(): creates a directory is a userfiles dir
12587:
12588: Args:
12589: docuname: username or courseid of destination for the file
12590: docudom: domain of user/course of destination for the file
12591: dir: dir to create (including any subdirs under userfiles)
12592:
12593: =item *
12594:
12595: removeuserfile(): removes a file that exists in userfiles
12596:
12597: Args:
12598: docuname: username or courseid of destination for the file
12599: docudom: domain of user/course of destination for the file
12600: fname: filname to delete (including any subdirs under userfiles)
12601:
12602: =item *
12603:
12604: removeuploadedurl(): convience function for removeuserfile()
12605:
12606: Args:
12607: url: a full /uploaded/... url to delete
12608:
12609: =item *
12610:
12611: get_portfile_permissions():
12612: Args:
12613: domain: domain of user or course contain the portfolio files
12614: user: name of user or num of course contain the portfolio files
12615: Returns:
12616: hashref of a dump of the proper file_permissions.db
12617:
12618:
12619: =item *
12620:
12621: get_access_controls():
12622:
12623: Args:
12624: current_permissions: the hash ref returned from get_portfile_permissions()
12625: group: (optional) the group you want the files associated with
12626: file: (optional) the file you want access info on
12627:
12628: Returns:
12629: a hash (keys are file names) of hashes containing
12630: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12631: values are XML containing access control settings (see below)
12632:
12633: Internal notes:
12634:
12635: access controls are stored in file_permissions.db as key=value pairs.
12636: key -> path to file/file_name\0uniqueID:scope_end_start
12637: where scope -> public,guest,course,group,domains or users.
12638: end -> UNIX time for end of access (0 -> no end date)
12639: start -> UNIX time for start of access
12640:
12641: value -> XML description of access control
12642: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12643: <start></start>
12644: <end></end>
12645:
12646: <password></password> for scope type = guest
12647:
12648: <domain></domain> for scope type = course or group
12649: <number></number>
12650: <roles id="">
12651: <role></role>
12652: <access></access>
12653: <section></section>
12654: <group></group>
12655: </roles>
12656:
12657: <dom></dom> for scope type = domains
12658:
12659: <users> for scope type = users
12660: <user>
12661: <uname></uname>
12662: <udom></udom>
12663: </user>
12664: </users>
12665: </scope>
12666:
12667: Access data is also aggregated for each file in an additional key=value pair:
12668: key -> path to file/file_name\0accesscontrol
12669: value -> reference to hash
12670: hash contains key = value pairs
12671: where key = uniqueID:scope_end_start
12672: value = UNIX time record was last updated
12673:
12674: Used to improve speed of look-ups of access controls for each file.
12675:
12676: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12677:
12678: modify_access_controls():
12679:
12680: Modifies access controls for a portfolio file
12681: Args
12682: 1. file name
12683: 2. reference to hash of required changes,
12684: 3. domain
12685: 4. username
12686: where domain,username are the domain of the portfolio owner
12687: (either a user or a course)
12688:
12689: Returns:
12690: 1. result of additions or updates ('ok' or 'error', with error message).
12691: 2. result of deletions ('ok' or 'error', with error message).
12692: 3. reference to hash of any new or updated access controls.
12693: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12694: key = integer (inbound ID)
12695: value = uniqueID
12696:
12697: =back
12698:
12699: =head2 HTTP Helper Routines
12700:
12701: =over 4
12702:
12703: =item *
12704:
12705: escape() : unpack non-word characters into CGI-compatible hex codes
12706:
12707: =item *
12708:
12709: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12710:
12711: =back
12712:
12713: =head1 PRIVATE SUBROUTINES
12714:
12715: =head2 Underlying communication routines (Shouldn't call)
12716:
12717: =over 4
12718:
12719: =item *
12720:
12721: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12722:
12723: =item *
12724:
12725: reply() : uses subreply to send a message to remote machine, logs all failures
12726:
12727: =item *
12728:
12729: critical() : passes a critical message to another server; if cannot
12730: get through then place message in connection buffer directory and
12731: returns con_delayed, if incapable of saving message, returns
12732: con_failed
12733:
12734: =item *
12735:
12736: reconlonc() : tries to reconnect lonc client processes.
12737:
12738: =back
12739:
12740: =head2 Resource Access Logging
12741:
12742: =over 4
12743:
12744: =item *
12745:
12746: flushcourselogs() : flush (save) buffer logs and access logs
12747:
12748: =item *
12749:
12750: courselog($what) : save message for course in hash
12751:
12752: =item *
12753:
12754: courseacclog($what) : save message for course using &courselog(). Perform
12755: special processing for specific resource types (problems, exams, quizzes, etc).
12756:
12757: =item *
12758:
12759: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12760: as a PerlChildExitHandler
12761:
12762: =back
12763:
12764: =head2 Other
12765:
12766: =over 4
12767:
12768: =item *
12769:
12770: symblist($mapname,%newhash) : update symbolic storage links
12771:
12772: =back
12773:
12774: =cut
12775:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>