1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1172.2.139 2021/02/10 15:00:54 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77: use CGI::Cookie;
78:
79: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir $deftex
80: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
81: %managerstab $passwdmin);
82:
83: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
84: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
85: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
86: %courseownerbuf, %coursetypebuf,$locknum);
87:
88: use IO::Socket;
89: use GDBM_File;
90: use HTML::LCParser;
91: use Fcntl qw(:flock);
92: use Storable qw(thaw nfreeze);
93: use Time::HiRes qw( sleep gettimeofday tv_interval );
94: use Cache::Memcached;
95: use Digest::MD5;
96: use Math::Random;
97: use File::MMagic;
98: use LONCAPA qw(:DEFAULT :match);
99: use LONCAPA::Configuration;
100: use LONCAPA::lonmetadata;
101: use LONCAPA::Lond;
102: use LONCAPA::transliterate;
103:
104: use File::Copy;
105:
106: my $readit;
107: my $max_connection_retries = 20; # Or some such value.
108:
109: require Exporter;
110:
111: our @ISA = qw (Exporter);
112: our @EXPORT = qw(%env);
113:
114: # ------------------------------------ Logging (parameters, docs, slots, roles)
115: {
116: my $logid;
117: sub write_log {
118: my ($context,$hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
119: if ($context eq 'course') {
120: if (($cnum eq '') || ($cdom eq '')) {
121: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
122: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
123: }
124: }
125: $logid ++;
126: my $now = time();
127: my $id=$now.'00000'.$$.'00000'.$logid;
128: my $ip = &get_requestor_ip();
129: my $logentry = {
130: $id => {
131: 'exe_uname' => $env{'user.name'},
132: 'exe_udom' => $env{'user.domain'},
133: 'exe_time' => $now,
134: 'exe_ip' => $ip,
135: 'delflag' => $delflag,
136: 'logentry' => $storehash,
137: 'uname' => $uname,
138: 'udom' => $udom,
139: }
140: };
141: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
142: }
143: }
144:
145: sub logtouch {
146: my $execdir=$perlvar{'lonDaemons'};
147: unless (-e "$execdir/logs/lonnet.log") {
148: open(my $fh,">>","$execdir/logs/lonnet.log");
149: close $fh;
150: }
151: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
152: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
153: }
154:
155: sub logthis {
156: my $message=shift;
157: my $execdir=$perlvar{'lonDaemons'};
158: my $now=time;
159: my $local=localtime($now);
160: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
161: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
162: print $fh $logstring;
163: close($fh);
164: }
165: return 1;
166: }
167:
168: sub logperm {
169: my $message=shift;
170: my $execdir=$perlvar{'lonDaemons'};
171: my $now=time;
172: my $local=localtime($now);
173: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
174: print $fh "$now:$message:$local\n";
175: close($fh);
176: }
177: return 1;
178: }
179:
180: sub create_connection {
181: my ($hostname,$lonid) = @_;
182: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
183: Type => SOCK_STREAM,
184: Timeout => 10);
185: return 0 if (!$client);
186: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
187: my $result = <$client>;
188: chomp($result);
189: return 1 if ($result eq 'done');
190: return 0;
191: }
192:
193: sub get_server_timezone {
194: my ($cnum,$cdom) = @_;
195: my $home=&homeserver($cnum,$cdom);
196: if ($home ne 'no_host') {
197: my $cachetime = 24*3600;
198: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
199: if (defined($cached)) {
200: return $timezone;
201: } else {
202: my $timezone = &reply('servertimezone',$home);
203: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
204: }
205: }
206: }
207:
208: sub get_server_distarch {
209: my ($lonhost,$ignore_cache) = @_;
210: if (defined($lonhost)) {
211: if (!defined(&hostname($lonhost))) {
212: return;
213: }
214: my $cachetime = 12*3600;
215: if (!$ignore_cache) {
216: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
217: if (defined($cached)) {
218: return $distarch;
219: }
220: }
221: my $rep = &reply('serverdistarch',$lonhost);
222: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
223: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
224: $rep eq '') {
225: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
226: }
227: }
228: return;
229: }
230:
231: sub get_server_loncaparev {
232: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
233: if (defined($lonhost)) {
234: if (!defined(&hostname($lonhost))) {
235: undef($lonhost);
236: }
237: }
238: if (!defined($lonhost)) {
239: if (defined(&domain($dom,'primary'))) {
240: $lonhost=&domain($dom,'primary');
241: if ($lonhost eq 'no_host') {
242: undef($lonhost);
243: }
244: }
245: }
246: if (defined($lonhost)) {
247: my $cachetime = 12*3600;
248: if (!$ignore_cache) {
249: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
250: if (defined($cached)) {
251: return $loncaparev;
252: }
253: }
254: my ($answer,$loncaparev);
255: my @ids=¤t_machine_ids();
256: if (grep(/^\Q$lonhost\E$/,@ids)) {
257: $answer = $perlvar{'lonVersion'};
258: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
259: $loncaparev = $1;
260: }
261: } else {
262: $answer = &reply('serverloncaparev',$lonhost);
263: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
264: if ($caller eq 'loncron') {
265: my $ua=new LWP::UserAgent;
266: $ua->timeout(4);
267: my $hostname = &hostname($lonhost);
268: my $protocol = $protocol{$lonhost};
269: $protocol = 'http' if ($protocol ne 'https');
270: my $url = $protocol.'://'.$hostname.'/adm/about.html';
271: my $request=new HTTP::Request('GET',$url);
272: my $response=$ua->request($request);
273: unless ($response->is_error()) {
274: my $content = $response->content;
275: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
276: $loncaparev = $1;
277: }
278: }
279: } else {
280: $loncaparev = $loncaparevs{$lonhost};
281: }
282: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
283: $loncaparev = $1;
284: }
285: }
286: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
287: }
288: }
289:
290: sub get_server_homeID {
291: my ($hostname,$ignore_cache,$caller) = @_;
292: unless ($ignore_cache) {
293: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
294: if (defined($cached)) {
295: return $serverhomeID;
296: }
297: }
298: my $cachetime = 12*3600;
299: my $serverhomeID;
300: if ($caller eq 'loncron') {
301: my @machine_ids = &machine_ids($hostname);
302: foreach my $id (@machine_ids) {
303: my $response = &reply('serverhomeID',$id);
304: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
305: $serverhomeID = $response;
306: last;
307: }
308: }
309: if ($serverhomeID eq '') {
310: $serverhomeID = $machine_ids[-1];
311: }
312: } else {
313: $serverhomeID = $serverhomeIDs{$hostname};
314: }
315: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
316: }
317:
318: sub get_remote_globals {
319: my ($lonhost,$whathash,$ignore_cache) = @_;
320: my ($result,%returnhash,%whatneeded);
321: if (ref($whathash) eq 'HASH') {
322: foreach my $what (sort(keys(%{$whathash}))) {
323: my $hashid = $lonhost.'-'.$what;
324: my ($response,$cached);
325: unless ($ignore_cache) {
326: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
327: }
328: if (defined($cached)) {
329: $returnhash{$what} = $response;
330: } else {
331: $whatneeded{$what} = 1;
332: }
333: }
334: if (keys(%whatneeded) == 0) {
335: $result = 'ok';
336: } else {
337: my $requested = &freeze_escape(\%whatneeded);
338: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
339: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
340: ($rep eq 'unknown_cmd')) {
341: $result = $rep;
342: } else {
343: $result = 'ok';
344: my @pairs=split(/\&/,$rep);
345: foreach my $item (@pairs) {
346: my ($key,$value)=split(/=/,$item,2);
347: my $what = &unescape($key);
348: my $hashid = $lonhost.'-'.$what;
349: $returnhash{$what}=&thaw_unescape($value);
350: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
351: }
352: }
353: }
354: }
355: return ($result,\%returnhash);
356: }
357:
358: sub remote_devalidate_cache {
359: my ($lonhost,$cachekeys) = @_;
360: my $items;
361: return unless (ref($cachekeys) eq 'ARRAY');
362: my $cachestr = join('&',@{$cachekeys});
363: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
364: }
365:
366: # -------------------------------------------------- Non-critical communication
367: sub subreply {
368: my ($cmd,$server)=@_;
369: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
370: #
371: # With loncnew process trimming, there's a timing hole between lonc server
372: # process exit and the master server picking up the listen on the AF_UNIX
373: # socket. In that time interval, a lock file will exist:
374:
375: my $lockfile=$peerfile.".lock";
376: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
377: sleep(0.1);
378: }
379: # At this point, either a loncnew parent is listening or an old lonc
380: # or loncnew child is listening so we can connect or everything's dead.
381: #
382: # We'll give the connection a few tries before abandoning it. If
383: # connection is not possible, we'll con_lost back to the client.
384: #
385: my $client;
386: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
387: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
388: Type => SOCK_STREAM,
389: Timeout => 10);
390: if ($client) {
391: last; # Connected!
392: } else {
393: &create_connection(&hostname($server),$server);
394: }
395: sleep(0.1); # Try again later if failed connection.
396: }
397: my $answer;
398: if ($client) {
399: print $client "sethost:$server:$cmd\n";
400: $answer=<$client>;
401: if (!$answer) { $answer="con_lost"; }
402: chomp($answer);
403: } else {
404: $answer = 'con_lost'; # Failed connection.
405: }
406: return $answer;
407: }
408:
409: sub reply {
410: my ($cmd,$server)=@_;
411: unless (defined(&hostname($server))) { return 'no_such_host'; }
412: my $answer=subreply($cmd,$server);
413: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
414: my $logged = $cmd;
415: if ($cmd =~ /^encrypt:([^:]+):/) {
416: my $subcmd = $1;
417: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
418: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
419: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
420: (undef,undef,my @rest) = split(/:/,$cmd);
421: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
422: splice(@rest,2,1,'Hidden');
423: } elsif ($subcmd eq 'passwd') {
424: splice(@rest,2,2,('Hidden','Hidden'));
425: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
426: ($subcmd eq 'autoexportgrades')) {
427: splice(@rest,3,1,'Hidden');
428: }
429: $logged = join(':',('encrypt:'.$subcmd,@rest));
430: }
431: }
432: &logthis("<font color=\"blue\">WARNING:".
433: " $logged to $server returned $answer</font>");
434: }
435: return $answer;
436: }
437:
438: # ----------------------------------------------------------- Send USR1 to lonc
439:
440: sub reconlonc {
441: my ($lonid) = @_;
442: if ($lonid) {
443: my $hostname = &hostname($lonid);
444: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
445: if ($hostname && -e $peerfile) {
446: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
447: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
448: Type => SOCK_STREAM,
449: Timeout => 10);
450: if ($client) {
451: print $client ("reset_retries\n");
452: my $answer=<$client>;
453: #reset just this one.
454: }
455: }
456: return;
457: }
458:
459: &logthis("Trying to reconnect lonc");
460: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
461: if (open(my $fh,"<",$loncfile)) {
462: my $loncpid=<$fh>;
463: chomp($loncpid);
464: if (kill 0 => $loncpid) {
465: &logthis("lonc at pid $loncpid responding, sending USR1");
466: kill USR1 => $loncpid;
467: sleep 1;
468: } else {
469: &logthis(
470: "<font color=\"blue\">WARNING:".
471: " lonc at pid $loncpid not responding, giving up</font>");
472: }
473: } else {
474: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
475: }
476: }
477:
478: # ------------------------------------------------------ Critical communication
479:
480: sub critical {
481: my ($cmd,$server)=@_;
482: unless (&hostname($server)) {
483: &logthis("<font color=\"blue\">WARNING:".
484: " Critical message to unknown server ($server)</font>");
485: return 'no_such_host';
486: }
487: my $answer=reply($cmd,$server);
488: if ($answer eq 'con_lost') {
489: &reconlonc($server);
490: my $answer=reply($cmd,$server);
491: if ($answer eq 'con_lost') {
492: my $now=time;
493: my $middlename=$cmd;
494: $middlename=substr($middlename,0,16);
495: $middlename=~s/\W//g;
496: my $dfilename=
497: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
498: $dumpcount++;
499: {
500: my $dfh;
501: if (open($dfh,">",$dfilename)) {
502: print $dfh "$cmd\n";
503: close($dfh);
504: }
505: }
506: sleep 1;
507: my $wcmd='';
508: {
509: my $dfh;
510: if (open($dfh,"<",$dfilename)) {
511: $wcmd=<$dfh>;
512: close($dfh);
513: }
514: }
515: chomp($wcmd);
516: if ($wcmd eq $cmd) {
517: &logthis("<font color=\"blue\">WARNING: ".
518: "Connection buffer $dfilename: $cmd</font>");
519: &logperm("D:$server:$cmd");
520: return 'con_delayed';
521: } else {
522: &logthis("<font color=\"red\">CRITICAL:"
523: ." Critical connection failed: $server $cmd</font>");
524: &logperm("F:$server:$cmd");
525: return 'con_failed';
526: }
527: }
528: }
529: return $answer;
530: }
531:
532: # ------------------------------------------- check if return value is an error
533:
534: sub error {
535: my ($result) = @_;
536: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
537: if ($2 == 2) { return undef; }
538: return $1;
539: }
540: return undef;
541: }
542:
543: sub convert_and_load_session_env {
544: my ($lonidsdir,$handle)=@_;
545: my @profile;
546: {
547: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
548: if (!$opened) {
549: return 0;
550: }
551: flock($idf,LOCK_SH);
552: @profile=<$idf>;
553: close($idf);
554: }
555: my %temp_env;
556: foreach my $line (@profile) {
557: if ($line !~ m/=/) {
558: return 0;
559: }
560: chomp($line);
561: my ($envname,$envvalue)=split(/=/,$line,2);
562: $temp_env{&unescape($envname)} = &unescape($envvalue);
563: }
564: unlink("$lonidsdir/$handle.id");
565: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
566: 0640)) {
567: %disk_env = %temp_env;
568: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
569: untie(%disk_env);
570: }
571: return 1;
572: }
573:
574: # ------------------------------------------- Transfer profile into environment
575: my $env_loaded;
576: sub transfer_profile_to_env {
577: my ($lonidsdir,$handle,$force_transfer) = @_;
578: if (!$force_transfer && $env_loaded) { return; }
579:
580: if (!defined($lonidsdir)) {
581: $lonidsdir = $perlvar{'lonIDsDir'};
582: }
583: if (!defined($handle)) {
584: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
585: }
586:
587: my $convert;
588: {
589: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
590: if (!$opened) {
591: return;
592: }
593: flock($idf,LOCK_SH);
594: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
595: &GDBM_READER(),0640)) {
596: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
597: untie(%disk_env);
598: } else {
599: $convert = 1;
600: }
601: }
602: if ($convert) {
603: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
604: &logthis("Failed to load session, or convert session.");
605: }
606: }
607:
608: my %remove;
609: while ( my $envname = each(%env) ) {
610: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
611: if ($time < time-300) {
612: $remove{$key}++;
613: }
614: }
615: }
616:
617: $env{'user.environment'} = "$lonidsdir/$handle.id";
618: $env_loaded=1;
619: foreach my $expired_key (keys(%remove)) {
620: &delenv($expired_key);
621: }
622: }
623:
624: # ---------------------------------------------------- Check for valid session
625: sub check_for_valid_session {
626: my ($r,$name,$userhashref,$domref) = @_;
627: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
628: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
629: if ($name eq 'lonDAV') {
630: $lonidsdir=$r->dir_config('lonDAVsessDir');
631: } else {
632: $lonidsdir=$r->dir_config('lonIDsDir');
633: if ($name eq '') {
634: $name = 'lonID';
635: }
636: }
637: if ($name eq 'lonID') {
638: $secure = 'lonSID';
639: $linkname = 'lonLinkID';
640: $pubname = 'lonPubID';
641: if (exists($cookies{$secure})) {
642: $lonid=$cookies{$secure};
643: } elsif (exists($cookies{$name})) {
644: $lonid=$cookies{$name};
645: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
646: $lonid=$cookies{$linkname};
647: } elsif (exists($cookies{$pubname})) {
648: $lonid=$cookies{$pubname};
649: }
650: } else {
651: $lonid=$cookies{$name};
652: }
653: return undef if (!$lonid);
654:
655: my $handle=&LONCAPA::clean_handle($lonid->value);
656: if (-l "$lonidsdir/$handle.id") {
657: my $link = readlink("$lonidsdir/$handle.id");
658: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
659: $handle = $1;
660: }
661: }
662: if (!-e "$lonidsdir/$handle.id") {
663: if ((ref($domref)) && ($name eq 'lonID') &&
664: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
665: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
666: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
667: $$domref = $possudom;
668: }
669: }
670: return undef;
671: }
672:
673: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
674: return undef if (!$opened);
675:
676: flock($idf,LOCK_SH);
677: my %disk_env;
678: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
679: &GDBM_READER(),0640)) {
680: return undef;
681: }
682:
683: if (!defined($disk_env{'user.name'})
684: || !defined($disk_env{'user.domain'})) {
685: untie(%disk_env);
686: return undef;
687: }
688:
689: if (ref($userhashref) eq 'HASH') {
690: $userhashref->{'name'} = $disk_env{'user.name'};
691: $userhashref->{'domain'} = $disk_env{'user.domain'};
692: }
693: untie(%disk_env);
694:
695: return $handle;
696: }
697:
698: sub timed_flock {
699: my ($file,$lock_type) = @_;
700: my $failed=0;
701: eval {
702: local $SIG{__DIE__}='DEFAULT';
703: local $SIG{ALRM}=sub {
704: $failed=1;
705: die("failed lock");
706: };
707: alarm(13);
708: flock($file,$lock_type);
709: alarm(0);
710: };
711: if ($failed) {
712: return undef;
713: } else {
714: return 1;
715: }
716: }
717:
718: sub get_sessionfile_vars {
719: my ($handle,$lonidsdir,$storearr) = @_;
720: my %returnhash;
721: unless (ref($storearr) eq 'ARRAY') {
722: return %returnhash;
723: }
724: if (-l "$lonidsdir/$handle.id") {
725: my $link = readlink("$lonidsdir/$handle.id");
726: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
727: $handle = $1;
728: }
729: }
730: if ((-e "$lonidsdir/$handle.id") &&
731: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
732: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
733: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
734: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
735: flock($idf,LOCK_SH);
736: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
737: &GDBM_READER(),0640)) {
738: foreach my $item (@{$storearr}) {
739: $returnhash{$item} = $disk_env{$item};
740: }
741: untie(%disk_env);
742: }
743: }
744: }
745: }
746: return %returnhash;
747: }
748:
749: # ---------------------------------------------------------- Append Environment
750:
751: sub appenv {
752: my ($newenv,$roles) = @_;
753: if (ref($newenv) eq 'HASH') {
754: foreach my $key (keys(%{$newenv})) {
755: my $refused = 0;
756: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
757: $refused = 1;
758: if (ref($roles) eq 'ARRAY') {
759: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
760: if (grep(/^\Q$role\E$/,@{$roles})) {
761: $refused = 0;
762: }
763: }
764: }
765: if ($refused) {
766: &logthis("<font color=\"blue\">WARNING: ".
767: "Attempt to modify environment ".$key." to ".$newenv->{$key}
768: .'</font>');
769: delete($newenv->{$key});
770: } else {
771: $env{$key}=$newenv->{$key};
772: }
773: }
774: my $lonids = $perlvar{'lonIDsDir'};
775: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
776: my $opened = open(my $env_file,'+<',$env{'user.environment'});
777: if ($opened
778: && &timed_flock($env_file,LOCK_EX)
779: &&
780: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
781: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
782: while (my ($key,$value) = each(%{$newenv})) {
783: $disk_env{$key} = $value;
784: }
785: untie(%disk_env);
786: }
787: }
788: }
789: return 'ok';
790: }
791: # ----------------------------------------------------- Delete from Environment
792:
793: sub delenv {
794: my ($delthis,$regexp,$roles) = @_;
795: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
796: my $refused = 1;
797: if (ref($roles) eq 'ARRAY') {
798: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
799: if (grep(/^\Q$role\E$/,@{$roles})) {
800: $refused = 0;
801: }
802: }
803: if ($refused) {
804: &logthis("<font color=\"blue\">WARNING: ".
805: "Attempt to delete from environment ".$delthis);
806: return 'error';
807: }
808: }
809: my $opened = open(my $env_file,'+<',$env{'user.environment'});
810: if ($opened
811: && &timed_flock($env_file,LOCK_EX)
812: &&
813: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
814: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
815: foreach my $key (keys(%disk_env)) {
816: if ($regexp) {
817: if ($key=~/^$delthis/) {
818: delete($env{$key});
819: delete($disk_env{$key});
820: }
821: } else {
822: if ($key=~/^\Q$delthis\E/) {
823: delete($env{$key});
824: delete($disk_env{$key});
825: }
826: }
827: }
828: untie(%disk_env);
829: }
830: return 'ok';
831: }
832:
833: sub get_env_multiple {
834: my ($name) = @_;
835: my @values;
836: if (defined($env{$name})) {
837: # exists is it an array
838: if (ref($env{$name})) {
839: @values=@{ $env{$name} };
840: } else {
841: $values[0]=$env{$name};
842: }
843: }
844: return(@values);
845: }
846:
847: # ------------------------------------------------------------------- Locking
848:
849: sub set_lock {
850: my ($text)=@_;
851: $locknum++;
852: my $id=$$.'-'.$locknum;
853: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
854: 'session.lock.'.$id => $text});
855: return $id;
856: }
857:
858: sub get_locks {
859: my $num=0;
860: my %texts=();
861: foreach my $lock (split(/\,/,$env{'session.locks'})) {
862: if ($lock=~/\w/) {
863: $num++;
864: $texts{$lock}=$env{'session.lock.'.$lock};
865: }
866: }
867: return ($num,%texts);
868: }
869:
870: sub remove_lock {
871: my ($id)=@_;
872: my $newlocks='';
873: foreach my $lock (split(/\,/,$env{'session.locks'})) {
874: if (($lock=~/\w/) && ($lock ne $id)) {
875: $newlocks.=','.$lock;
876: }
877: }
878: &appenv({'session.locks' => $newlocks});
879: &delenv('session.lock.'.$id);
880: }
881:
882: sub remove_all_locks {
883: my $activelocks=$env{'session.locks'};
884: foreach my $lock (split(/\,/,$env{'session.locks'})) {
885: if ($lock=~/\w/) {
886: &remove_lock($lock);
887: }
888: }
889: }
890:
891:
892: # ------------------------------------------ Find out current server userload
893: sub userload {
894: my $numusers=0;
895: {
896: opendir(LONIDS,$perlvar{'lonIDsDir'});
897: my $filename;
898: my $curtime=time;
899: while ($filename=readdir(LONIDS)) {
900: next if ($filename eq '.' || $filename eq '..');
901: next if ($filename =~ /publicuser_\d+\.id/);
902: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
903: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
904: if ($curtime-$mtime < 1800) { $numusers++; }
905: }
906: closedir(LONIDS);
907: }
908: my $userloadpercent=0;
909: my $maxuserload=$perlvar{'lonUserLoadLim'};
910: if ($maxuserload) {
911: $userloadpercent=100*$numusers/$maxuserload;
912: }
913: $userloadpercent=sprintf("%.2f",$userloadpercent);
914: return $userloadpercent;
915: }
916:
917: # ------------------------------ Find server with least workload from spare.tab
918:
919: sub spareserver {
920: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
921: my $spare_server;
922: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
923: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
924: : $userloadpercent;
925: my ($uint_dom,$remotesessions);
926: if (($udom ne '') && (&domain($udom) ne '')) {
927: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
928: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
929: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
930: $remotesessions = $udomdefaults{'remotesessions'};
931: }
932: my $spareshash = &this_host_spares($udom);
933: if (ref($spareshash) eq 'HASH') {
934: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
935: foreach my $try_server (@{ $spareshash->{'primary'} }) {
936: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
937: $try_server));
938: ($spare_server, $lowest_load) =
939: &compare_server_load($try_server, $spare_server, $lowest_load);
940: }
941: }
942:
943: my $found_server = ($spare_server ne '' && $lowest_load < 100);
944:
945: if (!$found_server) {
946: if (ref($spareshash->{'default'}) eq 'ARRAY') {
947: foreach my $try_server (@{ $spareshash->{'default'} }) {
948: next unless (&spare_can_host($udom,$uint_dom,
949: $remotesessions,$try_server));
950: ($spare_server, $lowest_load) =
951: &compare_server_load($try_server, $spare_server, $lowest_load);
952: }
953: }
954: }
955: }
956:
957: if (!$want_server_name) {
958: if (defined($spare_server)) {
959: my $hostname = &hostname($spare_server);
960: if (defined($hostname)) {
961: my $protocol = 'http';
962: if ($protocol{$spare_server} eq 'https') {
963: $protocol = $protocol{$spare_server};
964: }
965: $spare_server = $protocol.'://'.$hostname;
966: }
967: }
968: }
969: return $spare_server;
970: }
971:
972: sub compare_server_load {
973: my ($try_server, $spare_server, $lowest_load, $required) = @_;
974:
975: if ($required) {
976: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
977: my $remoterev = &get_server_loncaparev(undef,$try_server);
978: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
979: if (($major eq '' && $minor eq '') ||
980: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
981: return ($spare_server,$lowest_load);
982: }
983: }
984:
985: my $loadans = &reply('load', $try_server);
986: my $userloadans = &reply('userload',$try_server);
987:
988: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
989: return ($spare_server, $lowest_load); #didn't get a number from the server
990: }
991:
992: my $load;
993: if ($loadans =~ /\d/) {
994: if ($userloadans =~ /\d/) {
995: #both are numbers, pick the bigger one
996: $load = ($loadans > $userloadans) ? $loadans
997: : $userloadans;
998: } else {
999: $load = $loadans;
1000: }
1001: } else {
1002: $load = $userloadans;
1003: }
1004:
1005: if (($load =~ /\d/) && ($load < $lowest_load)) {
1006: $spare_server = $try_server;
1007: $lowest_load = $load;
1008: }
1009: return ($spare_server,$lowest_load);
1010: }
1011:
1012: # --------------------------- ask offload servers if user already has a session
1013: sub find_existing_session {
1014: my ($udom,$uname) = @_;
1015: my $spareshash = &this_host_spares($udom);
1016: if (ref($spareshash) eq 'HASH') {
1017: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1018: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1019: return $try_server if (&has_user_session($try_server, $udom, $uname));
1020: }
1021: }
1022: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1023: foreach my $try_server (@{ $spareshash->{'default'} }) {
1024: return $try_server if (&has_user_session($try_server, $udom, $uname));
1025: }
1026: }
1027: }
1028: return;
1029: }
1030:
1031: # check if user's browser sent load balancer cookie and server still has session
1032: # and is not overloaded.
1033: sub check_for_balancer_cookie {
1034: my ($r,$update_mtime) = @_;
1035: my ($otherserver,$cookie);
1036: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1037: if (exists($cookies{'balanceID'})) {
1038: my $balid = $cookies{'balanceID'};
1039: $cookie=&LONCAPA::clean_handle($balid->value);
1040: my $balancedir=$r->dir_config('lonBalanceDir');
1041: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1042: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1043: my ($possudom,$possuname) = ($1,$2);
1044: my $has_session = 0;
1045: if ((&domain($possudom) ne '') &&
1046: (&homeserver($possuname,$possudom) ne 'no_host')) {
1047: my $try_server;
1048: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1049: if ($opened) {
1050: flock($idf,LOCK_SH);
1051: while (my $line = <$idf>) {
1052: chomp($line);
1053: if (&hostname($line) ne '') {
1054: $try_server = $line;
1055: last;
1056: }
1057: }
1058: close($idf);
1059: if (($try_server) &&
1060: (&has_user_session($try_server,$possudom,$possuname))) {
1061: my $lowest_load = 30000;
1062: ($otherserver,$lowest_load) =
1063: &compare_server_load($try_server,undef,$lowest_load);
1064: if ($otherserver ne '' && $lowest_load < 100) {
1065: $has_session = 1;
1066: } else {
1067: undef($otherserver);
1068: }
1069: }
1070: }
1071: }
1072: if ($has_session) {
1073: if ($update_mtime) {
1074: my $atime = my $mtime = time;
1075: utime($atime,$mtime,"$balancedir/$cookie.id");
1076: }
1077: } else {
1078: unlink("$balancedir/$cookie.id");
1079: }
1080: }
1081: }
1082: }
1083: return ($otherserver,$cookie);
1084: }
1085:
1086: sub updatebalcookie {
1087: my ($cookie,$balancer,$lastentry)=@_;
1088: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1089: my ($udom,$uname) = ($1,$2);
1090: my $uprimary_id = &domain($udom,'primary');
1091: my $uintdom = &internet_dom($uprimary_id);
1092: my $intdom = &internet_dom($balancer);
1093: my $serverhomedom = &host_domain($balancer);
1094: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1095: return &reply('updatebalcookie:'.&escape($cookie).':'.&escape($lastentry),$balancer);
1096: }
1097: }
1098: return;
1099: }
1100:
1101: sub delbalcookie {
1102: my ($cookie,$balancer) =@_;
1103: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1104: my ($udom,$uname) = ($1,$2);
1105: my $uprimary_id = &domain($udom,'primary');
1106: my $uintdom = &internet_dom($uprimary_id);
1107: my $intdom = &internet_dom($balancer);
1108: my $serverhomedom = &host_domain($balancer);
1109: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1110: return &reply('delbalcookie:'.&escape($cookie),$balancer);
1111: }
1112: }
1113: }
1114:
1115: # -------------------------------- ask if server already has a session for user
1116: sub has_user_session {
1117: my ($lonid,$udom,$uname) = @_;
1118: my $result = &reply(join(':','userhassession',
1119: map {&escape($_)} ($udom,$uname)),$lonid);
1120: return 1 if ($result eq 'ok');
1121:
1122: return 0;
1123: }
1124:
1125: # --------- determine least loaded server in a user's domain which allows login
1126:
1127: sub choose_server {
1128: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1129: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1130: my %servers = &get_servers($udom);
1131: my $lowest_load = 30000;
1132: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1133: if ($skiploadbal) {
1134: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1135: unless (defined($cached)) {
1136: my $cachetime = 60*60*24;
1137: my %domconfig =
1138: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1139: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1140: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1141: $cachetime);
1142: }
1143: }
1144: }
1145: foreach my $lonhost (keys(%servers)) {
1146: my $loginvia;
1147: if ($skiploadbal) {
1148: if (ref($balancers) eq 'HASH') {
1149: next if (exists($balancers->{$lonhost}));
1150: }
1151: }
1152: if ($checkloginvia) {
1153: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1154: if ($loginvia) {
1155: my ($server,$path) = split(/:/,$loginvia);
1156: ($login_host, $lowest_load) =
1157: &compare_server_load($server, $login_host, $lowest_load, $required);
1158: if ($login_host eq $server) {
1159: $portal_path = $path;
1160: $isredirect = 1;
1161: }
1162: } else {
1163: ($login_host, $lowest_load) =
1164: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1165: if ($login_host eq $lonhost) {
1166: $portal_path = '';
1167: $isredirect = '';
1168: }
1169: }
1170: } else {
1171: ($login_host, $lowest_load) =
1172: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1173: }
1174: }
1175: if ($login_host ne '') {
1176: $hostname = &hostname($login_host);
1177: }
1178: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1179: }
1180:
1181: sub get_course_sessions {
1182: my ($cnum,$cdom,$lastactivity) = @_;
1183: my %servers = &internet_dom_servers($cdom);
1184: my %returnhash;
1185: foreach my $server (sort(keys(%servers))) {
1186: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1187: my @pairs=split(/\&/,$rep);
1188: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1189: foreach my $item (@pairs) {
1190: my ($key,$value)=split(/=/,$item,2);
1191: $key = &unescape($key);
1192: next if ($key =~ /^error: 2 /);
1193: if (exists($returnhash{$key})) {
1194: next if ($value < $returnhash{$key});
1195: }
1196: $returnhash{$key}=$value;
1197: }
1198: }
1199: }
1200: return %returnhash;
1201: }
1202:
1203: # --------------------------------------------- Try to change a user's password
1204:
1205: sub changepass {
1206: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1207: $currentpass = &escape($currentpass);
1208: $newpass = &escape($newpass);
1209: my $lonhost = $perlvar{'lonHostID'};
1210: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1211: $server);
1212: if (! $answer) {
1213: &logthis("No reply on password change request to $server ".
1214: "by $uname in domain $udom.");
1215: } elsif ($answer =~ "^ok") {
1216: &logthis("$uname in $udom successfully changed their password ".
1217: "on $server.");
1218: } elsif ($answer =~ "^pwchange_failure") {
1219: &logthis("$uname in $udom was unable to change their password ".
1220: "on $server. The action was blocked by either lcpasswd ".
1221: "or pwchange");
1222: } elsif ($answer =~ "^non_authorized") {
1223: &logthis("$uname in $udom did not get their password correct when ".
1224: "attempting to change it on $server.");
1225: } elsif ($answer =~ "^auth_mode_error") {
1226: &logthis("$uname in $udom attempted to change their password despite ".
1227: "not being locally or internally authenticated on $server.");
1228: } elsif ($answer =~ "^unknown_user") {
1229: &logthis("$uname in $udom attempted to change their password ".
1230: "on $server but were unable to because $server is not ".
1231: "their home server.");
1232: } elsif ($answer =~ "^refused") {
1233: &logthis("$server refused to change $uname in $udom password because ".
1234: "it was sent an unencrypted request to change the password.");
1235: } elsif ($answer =~ "invalid_client") {
1236: &logthis("$server refused to change $uname in $udom password because ".
1237: "it was a reset by e-mail originating from an invalid server.");
1238: } elsif ($answer =~ "^prioruse") {
1239: &logthis("$server refused to change $uname in $udom password because ".
1240: "the password had been used before");
1241: }
1242: return $answer;
1243: }
1244:
1245: # ----------------------- Try to determine user's current authentication scheme
1246:
1247: sub queryauthenticate {
1248: my ($uname,$udom)=@_;
1249: my $uhome=&homeserver($uname,$udom);
1250: if (!$uhome) {
1251: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1252: return 'no_host';
1253: }
1254: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1255: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1256: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1257: }
1258: return $answer;
1259: }
1260:
1261: # --------- Try to authenticate user from domain's lib servers (first this one)
1262:
1263: sub authenticate {
1264: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1265: $upass=&escape($upass);
1266: $uname= &LONCAPA::clean_username($uname);
1267: my $uhome=&homeserver($uname,$udom,1);
1268: my $newhome;
1269: if ((!$uhome) || ($uhome eq 'no_host')) {
1270: # Maybe the machine was offline and only re-appeared again recently?
1271: &reconlonc();
1272: # One more
1273: $uhome=&homeserver($uname,$udom,1);
1274: if (($uhome eq 'no_host') && $checkdefauth) {
1275: if (defined(&domain($udom,'primary'))) {
1276: $newhome=&domain($udom,'primary');
1277: }
1278: if ($newhome ne '') {
1279: $uhome = $newhome;
1280: }
1281: }
1282: if ((!$uhome) || ($uhome eq 'no_host')) {
1283: &logthis("User $uname at $udom is unknown in authenticate");
1284: return 'no_host';
1285: }
1286: }
1287: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1288: if ($answer eq 'authorized') {
1289: if ($newhome) {
1290: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1291: return 'no_account_on_host';
1292: } else {
1293: &logthis("User $uname at $udom authorized by $uhome");
1294: return $uhome;
1295: }
1296: }
1297: if ($answer eq 'non_authorized') {
1298: &logthis("User $uname at $udom rejected by $uhome");
1299: return 'no_host';
1300: }
1301: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1302: return 'no_host';
1303: }
1304:
1305: sub can_host_session {
1306: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1307: my $canhost = 1;
1308: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1309: if (ref($remotesessions) eq 'HASH') {
1310: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1311: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1312: $canhost = 0;
1313: } else {
1314: $canhost = 1;
1315: }
1316: }
1317: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1318: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1319: $canhost = 1;
1320: } else {
1321: $canhost = 0;
1322: }
1323: }
1324: if ($canhost) {
1325: if ($remotesessions->{'version'} ne '') {
1326: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1327: if ($reqmajor ne '' && $reqminor ne '') {
1328: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1329: my $major = $1;
1330: my $minor = $2;
1331: if (($major < $reqmajor ) ||
1332: (($major == $reqmajor) && ($minor < $reqminor))) {
1333: $canhost = 0;
1334: }
1335: } else {
1336: $canhost = 0;
1337: }
1338: }
1339: }
1340: }
1341: }
1342: if ($canhost) {
1343: if (ref($hostedsessions) eq 'HASH') {
1344: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1345: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1346: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1347: if (($uint_dom ne '') &&
1348: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1349: $canhost = 0;
1350: } else {
1351: $canhost = 1;
1352: }
1353: }
1354: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1355: if (($uint_dom ne '') &&
1356: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1357: $canhost = 1;
1358: } else {
1359: $canhost = 0;
1360: }
1361: }
1362: }
1363: }
1364: return $canhost;
1365: }
1366:
1367: sub spare_can_host {
1368: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1369: my $canhost=1;
1370: my $try_server_hostname = &hostname($try_server);
1371: my $serverhomeID = &get_server_homeID($try_server_hostname);
1372: my $serverhomedom = &host_domain($serverhomeID);
1373: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1374: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1375: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1376: $canhost = 0;
1377: }
1378: }
1379: if ($canhost) {
1380: if (ref($defdomdefaults{'offloadoth'}) eq 'HASH') {
1381: if ($defdomdefaults{'offloadoth'}{$try_server}) {
1382: unless (&shared_institution($udom,$try_server)) {
1383: $canhost = 0;
1384: }
1385: }
1386: }
1387: }
1388: if (($canhost) && ($uint_dom)) {
1389: my @intdoms;
1390: my $internet_names = &get_internet_names($try_server);
1391: if (ref($internet_names) eq 'ARRAY') {
1392: @intdoms = @{$internet_names};
1393: }
1394: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1395: my $remoterev = &get_server_loncaparev(undef,$try_server);
1396: $canhost = &can_host_session($udom,$try_server,$remoterev,
1397: $remotesessions,
1398: $defdomdefaults{'hostedsessions'});
1399: }
1400: }
1401: return $canhost;
1402: }
1403:
1404: sub this_host_spares {
1405: my ($dom) = @_;
1406: my ($dom_in_use,$lonhost_in_use,$result);
1407: my @hosts = ¤t_machine_ids();
1408: foreach my $lonhost (@hosts) {
1409: if (&host_domain($lonhost) eq $dom) {
1410: $dom_in_use = $dom;
1411: $lonhost_in_use = $lonhost;
1412: last;
1413: }
1414: }
1415: if ($dom_in_use ne '') {
1416: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1417: }
1418: if (ref($result) ne 'HASH') {
1419: $lonhost_in_use = $perlvar{'lonHostID'};
1420: $dom_in_use = &host_domain($lonhost_in_use);
1421: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1422: if (ref($result) ne 'HASH') {
1423: $result = \%spareid;
1424: }
1425: }
1426: return $result;
1427: }
1428:
1429: sub spares_for_offload {
1430: my ($dom_in_use,$lonhost_in_use) = @_;
1431: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1432: if (defined($cached)) {
1433: return $result;
1434: } else {
1435: my $cachetime = 60*60*24;
1436: my %domconfig =
1437: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1438: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1439: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1440: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1441: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1442: }
1443: }
1444: }
1445: }
1446: return;
1447: }
1448:
1449: sub get_lonbalancer_config {
1450: my ($servers) = @_;
1451: my ($currbalancer,$currtargets);
1452: if (ref($servers) eq 'HASH') {
1453: foreach my $server (keys(%{$servers})) {
1454: my %what = (
1455: spareid => 1,
1456: perlvar => 1,
1457: );
1458: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1459: if ($result eq 'ok') {
1460: if (ref($returnhash) eq 'HASH') {
1461: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1462: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1463: $currbalancer = $server;
1464: $currtargets = {};
1465: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1466: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1467: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1468: }
1469: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1470: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1471: }
1472: }
1473: last;
1474: }
1475: }
1476: }
1477: }
1478: }
1479: }
1480: return ($currbalancer,$currtargets);
1481: }
1482:
1483: sub check_loadbalancing {
1484: my ($uname,$udom,$caller) = @_;
1485: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1486: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1487: my $lonhost = $perlvar{'lonHostID'};
1488: my @hosts = ¤t_machine_ids();
1489: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1490: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1491: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1492: my $serverhomedom = &host_domain($lonhost);
1493: my $domneedscache;
1494: my $cachetime = 60*60*24;
1495:
1496: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1497: $dom_in_use = $udom;
1498: $homeintdom = 1;
1499: } else {
1500: $dom_in_use = $serverhomedom;
1501: }
1502: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1503: unless (defined($cached)) {
1504: my %domconfig =
1505: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1506: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1507: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1508: } else {
1509: $domneedscache = $dom_in_use;
1510: }
1511: }
1512: if (ref($result) eq 'HASH') {
1513: ($is_balancer,$currtargets,$currrules,$setcookie) =
1514: &check_balancer_result($result,@hosts);
1515: if ($is_balancer) {
1516: if (ref($currrules) eq 'HASH') {
1517: if ($homeintdom) {
1518: if ($uname ne '') {
1519: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1520: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1521: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1522: $rule_in_effect = $currrules->{'_LC_author'};
1523: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1524: $rule_in_effect = $currrules->{'_LC_adv'}
1525: }
1526: }
1527: if ($rule_in_effect eq '') {
1528: my %userenv = &userenvironment($udom,$uname,'inststatus');
1529: if ($userenv{'inststatus'} ne '') {
1530: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1531: my ($othertitle,$usertypes,$types) =
1532: &Apache::loncommon::sorted_inst_types($udom);
1533: if (ref($types) eq 'ARRAY') {
1534: foreach my $type (@{$types}) {
1535: if (grep(/^\Q$type\E$/,@statuses)) {
1536: if (exists($currrules->{$type})) {
1537: $rule_in_effect = $currrules->{$type};
1538: }
1539: }
1540: }
1541: }
1542: } else {
1543: if (exists($currrules->{'default'})) {
1544: $rule_in_effect = $currrules->{'default'};
1545: }
1546: }
1547: }
1548: } else {
1549: if (exists($currrules->{'default'})) {
1550: $rule_in_effect = $currrules->{'default'};
1551: }
1552: }
1553: } else {
1554: if ($currrules->{'_LC_external'} ne '') {
1555: $rule_in_effect = $currrules->{'_LC_external'};
1556: }
1557: }
1558: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1559: $uname,$udom);
1560: }
1561: }
1562: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1563: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1564: unless (defined($cached)) {
1565: my %domconfig =
1566: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1567: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1568: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1569: } else {
1570: $domneedscache = $serverhomedom;
1571: }
1572: }
1573: if (ref($result) eq 'HASH') {
1574: ($is_balancer,$currtargets,$currrules,$setcookie) =
1575: &check_balancer_result($result,@hosts);
1576: if ($is_balancer) {
1577: if (ref($currrules) eq 'HASH') {
1578: if ($currrules->{'_LC_internetdom'} ne '') {
1579: $rule_in_effect = $currrules->{'_LC_internetdom'};
1580: }
1581: }
1582: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1583: $uname,$udom);
1584: }
1585: } else {
1586: if ($perlvar{'lonBalancer'} eq 'yes') {
1587: $is_balancer = 1;
1588: $offloadto = &this_host_spares($dom_in_use);
1589: }
1590: unless (defined($cached)) {
1591: $domneedscache = $serverhomedom;
1592: }
1593: }
1594: } else {
1595: if ($perlvar{'lonBalancer'} eq 'yes') {
1596: $is_balancer = 1;
1597: $offloadto = &this_host_spares($dom_in_use);
1598: }
1599: unless (defined($cached)) {
1600: $domneedscache = $serverhomedom;
1601: }
1602: }
1603: if ($domneedscache) {
1604: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1605: }
1606: if (($is_balancer) && ($caller ne 'switchserver')) {
1607: my $lowest_load = 30000;
1608: if (ref($offloadto) eq 'HASH') {
1609: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1610: foreach my $try_server (@{$offloadto->{'primary'}}) {
1611: ($otherserver,$lowest_load) =
1612: &compare_server_load($try_server,$otherserver,$lowest_load);
1613: }
1614: }
1615: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1616:
1617: if (!$found_server) {
1618: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1619: foreach my $try_server (@{$offloadto->{'default'}}) {
1620: ($otherserver,$lowest_load) =
1621: &compare_server_load($try_server,$otherserver,$lowest_load);
1622: }
1623: }
1624: }
1625: } elsif (ref($offloadto) eq 'ARRAY') {
1626: if (@{$offloadto} == 1) {
1627: $otherserver = $offloadto->[0];
1628: } elsif (@{$offloadto} > 1) {
1629: foreach my $try_server (@{$offloadto}) {
1630: ($otherserver,$lowest_load) =
1631: &compare_server_load($try_server,$otherserver,$lowest_load);
1632: }
1633: }
1634: }
1635: unless ($caller eq 'login') {
1636: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1637: $is_balancer = 0;
1638: if ($uname ne '' && $udom ne '') {
1639: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1640: &appenv({'user.loadbalexempt' => $lonhost,
1641: 'user.loadbalcheck.time' => time});
1642: }
1643: }
1644: }
1645: }
1646: }
1647: if (($is_balancer) && (!$homeintdom)) {
1648: undef($setcookie);
1649: }
1650: return ($is_balancer,$otherserver,$setcookie);
1651: }
1652:
1653: sub check_balancer_result {
1654: my ($result,@hosts) = @_;
1655: my ($is_balancer,$currtargets,$currrules,$setcookie);
1656: if (ref($result) eq 'HASH') {
1657: if ($result->{'lonhost'} ne '') {
1658: my $currbalancer = $result->{'lonhost'};
1659: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1660: $is_balancer = 1;
1661: $currtargets = $result->{'targets'};
1662: $currrules = $result->{'rules'};
1663: }
1664: } else {
1665: foreach my $key (keys(%{$result})) {
1666: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1667: (ref($result->{$key}) eq 'HASH')) {
1668: $is_balancer = 1;
1669: $currrules = $result->{$key}{'rules'};
1670: $currtargets = $result->{$key}{'targets'};
1671: $setcookie = $result->{$key}{'cookie'};
1672: last;
1673: }
1674: }
1675: }
1676: }
1677: return ($is_balancer,$currtargets,$currrules,$setcookie);
1678: }
1679:
1680: sub get_loadbalancer_targets {
1681: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1682: my $offloadto;
1683: if ($rule_in_effect eq 'none') {
1684: return [$perlvar{'lonHostID'}];
1685: } elsif ($rule_in_effect eq '') {
1686: $offloadto = $currtargets;
1687: } else {
1688: if ($rule_in_effect eq 'homeserver') {
1689: my $homeserver = &homeserver($uname,$udom);
1690: if ($homeserver ne 'no_host') {
1691: $offloadto = [$homeserver];
1692: }
1693: } elsif ($rule_in_effect eq 'externalbalancer') {
1694: my %domconfig =
1695: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1696: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1697: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1698: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1699: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1700: }
1701: }
1702: } else {
1703: my %servers = &internet_dom_servers($udom);
1704: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1705: if (&hostname($remotebalancer) ne '') {
1706: $offloadto = [$remotebalancer];
1707: }
1708: }
1709: } elsif (&hostname($rule_in_effect) ne '') {
1710: $offloadto = [$rule_in_effect];
1711: }
1712: }
1713: return $offloadto;
1714: }
1715:
1716: sub internet_dom_servers {
1717: my ($dom) = @_;
1718: my (%uniqservers,%servers);
1719: my $primaryserver = &hostname(&domain($dom,'primary'));
1720: my @machinedoms = &machine_domains($primaryserver);
1721: foreach my $mdom (@machinedoms) {
1722: my %currservers = %servers;
1723: my %server = &get_servers($mdom);
1724: %servers = (%currservers,%server);
1725: }
1726: my %by_hostname;
1727: foreach my $id (keys(%servers)) {
1728: push(@{$by_hostname{$servers{$id}}},$id);
1729: }
1730: foreach my $hostname (sort(keys(%by_hostname))) {
1731: if (@{$by_hostname{$hostname}} > 1) {
1732: my $match = 0;
1733: foreach my $id (@{$by_hostname{$hostname}}) {
1734: if (&host_domain($id) eq $dom) {
1735: $uniqservers{$id} = $hostname;
1736: $match = 1;
1737: }
1738: }
1739: unless ($match) {
1740: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1741: }
1742: } else {
1743: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1744: }
1745: }
1746: return %uniqservers;
1747: }
1748:
1749: # ---------------------- Find the homebase for a user from domain's lib servers
1750:
1751: my %homecache;
1752: sub homeserver {
1753: my ($uname,$udom,$ignoreBadCache)=@_;
1754: my $index="$uname:$udom";
1755:
1756: if (exists($homecache{$index})) { return $homecache{$index}; }
1757:
1758: my %servers = &get_servers($udom,'library');
1759: foreach my $tryserver (keys(%servers)) {
1760: next if ($ignoreBadCache ne 'true' &&
1761: exists($badServerCache{$tryserver}));
1762:
1763: my $answer=reply("home:$udom:$uname",$tryserver);
1764: if ($answer eq 'found') {
1765: delete($badServerCache{$tryserver});
1766: return $homecache{$index}=$tryserver;
1767: } elsif ($answer eq 'no_host') {
1768: $badServerCache{$tryserver}=1;
1769: }
1770: }
1771: return 'no_host';
1772: }
1773:
1774: # ------------------------------------- Find the usernames behind a list of IDs
1775:
1776: sub idget {
1777: my ($udom,@ids)=@_;
1778: my %returnhash=();
1779:
1780: my %servers = &get_servers($udom,'library');
1781: foreach my $tryserver (keys(%servers)) {
1782: my $idlist=join('&', map { &escape($_); } @ids);
1783: $idlist=~tr/A-Z/a-z/;
1784: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1785: my @answer=();
1786: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1787: @answer=split(/\&/,$reply);
1788: } ;
1789: my $i;
1790: for ($i=0;$i<=$#ids;$i++) {
1791: if ($answer[$i]) {
1792: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1793: }
1794: }
1795: }
1796: return %returnhash;
1797: }
1798:
1799: # ------------------------------------- Find the IDs behind a list of usernames
1800:
1801: sub idrget {
1802: my ($udom,@unames)=@_;
1803: my %returnhash=();
1804: foreach my $uname (@unames) {
1805: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1806: }
1807: return %returnhash;
1808: }
1809:
1810: # ------------------------------- Store away a list of names and associated IDs
1811:
1812: sub idput {
1813: my ($udom,%ids)=@_;
1814: my %servers=();
1815: foreach my $uname (keys(%ids)) {
1816: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1817: my $uhom=&homeserver($uname,$udom);
1818: if ($uhom ne 'no_host') {
1819: my $id=&escape($ids{$uname});
1820: $id=~tr/A-Z/a-z/;
1821: my $esc_unam=&escape($uname);
1822: if ($servers{$uhom}) {
1823: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1824: } else {
1825: $servers{$uhom}=$id.'='.$esc_unam;
1826: }
1827: }
1828: }
1829: foreach my $server (keys(%servers)) {
1830: &critical('idput:'.$udom.':'.$servers{$server},$server);
1831: }
1832: }
1833:
1834: # ---------------------------------------- Delete unwanted IDs from ids.db file
1835:
1836: sub iddel {
1837: my ($udom,$idshashref,$uhome)=@_;
1838: my %result=();
1839: unless (ref($idshashref) eq 'HASH') {
1840: return %result;
1841: }
1842: my %servers=();
1843: while (my ($id,$uname) = each(%{$idshashref})) {
1844: my $uhom;
1845: if ($uhome) {
1846: $uhom = $uhome;
1847: } else {
1848: $uhom=&homeserver($uname,$udom);
1849: }
1850: if ($uhom ne 'no_host') {
1851: if ($servers{$uhom}) {
1852: $servers{$uhom}.='&'.&escape($id);
1853: } else {
1854: $servers{$uhom}=&escape($id);
1855: }
1856: }
1857: }
1858: foreach my $server (keys(%servers)) {
1859: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1860: }
1861: return %result;
1862: }
1863:
1864: # ------------------------------dump from db file owned by domainconfig user
1865: sub dump_dom {
1866: my ($namespace, $udom, $regexp) = @_;
1867:
1868: $udom ||= $env{'user.domain'};
1869:
1870: return () unless $udom;
1871:
1872: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1873: }
1874:
1875: # ------------------------------------------ get items from domain db files
1876:
1877: sub get_dom {
1878: my ($namespace,$storearr,$udom,$uhome)=@_;
1879: return if ($udom eq 'public');
1880: my $items='';
1881: foreach my $item (@$storearr) {
1882: $items.=&escape($item).'&';
1883: }
1884: $items=~s/\&$//;
1885: if (!$udom) {
1886: $udom=$env{'user.domain'};
1887: return if ($udom eq 'public');
1888: if (defined(&domain($udom,'primary'))) {
1889: $uhome=&domain($udom,'primary');
1890: } else {
1891: undef($uhome);
1892: }
1893: } else {
1894: if (!$uhome) {
1895: if (defined(&domain($udom,'primary'))) {
1896: $uhome=&domain($udom,'primary');
1897: }
1898: }
1899: }
1900: if ($udom && $uhome && ($uhome ne 'no_host')) {
1901: my $rep;
1902: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
1903: # domain information is hosted on this machine
1904: $rep = &LONCAPA::Lond::get_dom("getdom:$udom:$namespace:$items");
1905: } else {
1906: $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1907: }
1908: my %returnhash;
1909: if ($rep eq '' || $rep =~ /^error: 2 /) {
1910: return %returnhash;
1911: }
1912: my @pairs=split(/\&/,$rep);
1913: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1914: return @pairs;
1915: }
1916: my $i=0;
1917: foreach my $item (@$storearr) {
1918: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1919: $i++;
1920: }
1921: return %returnhash;
1922: } else {
1923: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1924: }
1925: }
1926:
1927: # -------------------------------------------- put items in domain db files
1928:
1929: sub put_dom {
1930: my ($namespace,$storehash,$udom,$uhome)=@_;
1931: if (!$udom) {
1932: $udom=$env{'user.domain'};
1933: if (defined(&domain($udom,'primary'))) {
1934: $uhome=&domain($udom,'primary');
1935: } else {
1936: undef($uhome);
1937: }
1938: } else {
1939: if (!$uhome) {
1940: if (defined(&domain($udom,'primary'))) {
1941: $uhome=&domain($udom,'primary');
1942: }
1943: }
1944: }
1945: if ($udom && $uhome && ($uhome ne 'no_host')) {
1946: my $items='';
1947: foreach my $item (keys(%$storehash)) {
1948: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1949: }
1950: $items=~s/\&$//;
1951: return &reply("putdom:$udom:$namespace:$items",$uhome);
1952: } else {
1953: &logthis("put_dom failed - no homeserver and/or domain");
1954: }
1955: }
1956:
1957: # --------------------- newput for items in db file owned by domainconfig user
1958: sub newput_dom {
1959: my ($namespace,$storehash,$udom) = @_;
1960: my $result;
1961: if (!$udom) {
1962: $udom=$env{'user.domain'};
1963: }
1964: if ($udom) {
1965: my $uname = &get_domainconfiguser($udom);
1966: $result = &newput($namespace,$storehash,$udom,$uname);
1967: }
1968: return $result;
1969: }
1970:
1971: # --------------------- delete for items in db file owned by domainconfig user
1972: sub del_dom {
1973: my ($namespace,$storearr,$udom)=@_;
1974: if (ref($storearr) eq 'ARRAY') {
1975: if (!$udom) {
1976: $udom=$env{'user.domain'};
1977: }
1978: if ($udom) {
1979: my $uname = &get_domainconfiguser($udom);
1980: return &del($namespace,$storearr,$udom,$uname);
1981: }
1982: }
1983: }
1984:
1985: # ----------------------------------construct domainconfig user for a domain
1986: sub get_domainconfiguser {
1987: my ($udom) = @_;
1988: return $udom.'-domainconfig';
1989: }
1990:
1991: sub retrieve_inst_usertypes {
1992: my ($udom) = @_;
1993: my (%returnhash,@order);
1994: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1995: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1996: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1997: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1998: } else {
1999: if (defined(&domain($udom,'primary'))) {
2000: my $uhome=&domain($udom,'primary');
2001: my $rep=&reply("inst_usertypes:$udom",$uhome);
2002: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
2003: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
2004: return (\%returnhash,\@order);
2005: }
2006: my ($hashitems,$orderitems) = split(/:/,$rep);
2007: my @pairs=split(/\&/,$hashitems);
2008: foreach my $item (@pairs) {
2009: my ($key,$value)=split(/=/,$item,2);
2010: $key = &unescape($key);
2011: next if ($key =~ /^error: 2 /);
2012: $returnhash{$key}=&thaw_unescape($value);
2013: }
2014: my @esc_order = split(/\&/,$orderitems);
2015: foreach my $item (@esc_order) {
2016: push(@order,&unescape($item));
2017: }
2018: } else {
2019: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
2020: }
2021: return (\%returnhash,\@order);
2022: }
2023: }
2024:
2025: sub is_domainimage {
2026: my ($url) = @_;
2027: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
2028: if (&domain($1) ne '') {
2029: return '1';
2030: }
2031: }
2032: return;
2033: }
2034:
2035: sub inst_directory_query {
2036: my ($srch) = @_;
2037: my $udom = $srch->{'srchdomain'};
2038: my %results;
2039: my $homeserver = &domain($udom,'primary');
2040: my $outcome;
2041: if ($homeserver ne '') {
2042: unless ($homeserver eq $perlvar{'lonHostID'}) {
2043: if ($srch->{'srchby'} eq 'email') {
2044: my $lcrev = &get_server_loncaparev($udom,$homeserver);
2045: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2046: if (($major eq '' && $minor eq '') || ($major < 2) ||
2047: (($major == 2) && ($minor < 11)) ||
2048: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2049: return;
2050: }
2051: }
2052: }
2053: my $queryid=&reply("querysend:instdirsearch:".
2054: &escape($srch->{'srchby'}).':'.
2055: &escape($srch->{'srchterm'}).':'.
2056: &escape($srch->{'srchtype'}),$homeserver);
2057: my $host=&hostname($homeserver);
2058: if ($queryid !~/^\Q$host\E\_/) {
2059: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2060: return;
2061: }
2062: my $response = &get_query_reply($queryid);
2063: my $maxtries = 5;
2064: my $tries = 1;
2065: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2066: $response = &get_query_reply($queryid);
2067: $tries ++;
2068: }
2069:
2070: if (!&error($response) && $response ne 'refused') {
2071: if ($response eq 'unavailable') {
2072: $outcome = $response;
2073: } else {
2074: $outcome = 'ok';
2075: my @matches = split(/\n/,$response);
2076: foreach my $match (@matches) {
2077: my ($key,$value) = split(/=/,$match);
2078: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2079: }
2080: }
2081: }
2082: }
2083: return ($outcome,%results);
2084: }
2085:
2086: sub usersearch {
2087: my ($srch) = @_;
2088: my $dom = $srch->{'srchdomain'};
2089: my %results;
2090: my %libserv = &all_library();
2091: my $query = 'usersearch';
2092: foreach my $tryserver (keys(%libserv)) {
2093: if (&host_domain($tryserver) eq $dom) {
2094: unless ($tryserver eq $perlvar{'lonHostID'}) {
2095: if ($srch->{'srchby'} eq 'email') {
2096: my $lcrev = &get_server_loncaparev($dom,$tryserver);
2097: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2098: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2099: (($major == 2) && ($minor < 11)) ||
2100: (($major == 2) && ($minor == 11) && ($subver < 3)));
2101: }
2102: }
2103: my $host=&hostname($tryserver);
2104: my $queryid=
2105: &reply("querysend:".&escape($query).':'.
2106: &escape($srch->{'srchby'}).':'.
2107: &escape($srch->{'srchtype'}).':'.
2108: &escape($srch->{'srchterm'}),$tryserver);
2109: if ($queryid !~/^\Q$host\E\_/) {
2110: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2111: next;
2112: }
2113: my $reply = &get_query_reply($queryid);
2114: my $maxtries = 1;
2115: my $tries = 1;
2116: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2117: $reply = &get_query_reply($queryid);
2118: $tries ++;
2119: }
2120: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2121: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2122: } else {
2123: my @matches;
2124: if ($reply =~ /\n/) {
2125: @matches = split(/\n/,$reply);
2126: } else {
2127: @matches = split(/\&/,$reply);
2128: }
2129: foreach my $match (@matches) {
2130: my ($uname,$udom,%userhash);
2131: foreach my $entry (split(/:/,$match)) {
2132: my ($key,$value) =
2133: map {&unescape($_);} split(/=/,$entry);
2134: $userhash{$key} = $value;
2135: if ($key eq 'username') {
2136: $uname = $value;
2137: } elsif ($key eq 'domain') {
2138: $udom = $value;
2139: }
2140: }
2141: $results{$uname.':'.$udom} = \%userhash;
2142: }
2143: }
2144: }
2145: }
2146: return %results;
2147: }
2148:
2149: sub get_instuser {
2150: my ($udom,$uname,$id) = @_;
2151: my $homeserver = &domain($udom,'primary');
2152: my ($outcome,%results);
2153: if ($homeserver ne '') {
2154: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2155: &escape($id).':'.&escape($udom),$homeserver);
2156: my $host=&hostname($homeserver);
2157: if ($queryid !~/^\Q$host\E\_/) {
2158: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2159: return;
2160: }
2161: my $response = &get_query_reply($queryid);
2162: my $maxtries = 5;
2163: my $tries = 1;
2164: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2165: $response = &get_query_reply($queryid);
2166: $tries ++;
2167: }
2168: if (!&error($response) && $response ne 'refused') {
2169: if ($response eq 'unavailable') {
2170: $outcome = $response;
2171: } else {
2172: $outcome = 'ok';
2173: my @matches = split(/\n/,$response);
2174: foreach my $match (@matches) {
2175: my ($key,$value) = split(/=/,$match);
2176: $results{&unescape($key)} = &thaw_unescape($value);
2177: }
2178: }
2179: }
2180: }
2181: my %userinfo;
2182: if (ref($results{$uname}) eq 'HASH') {
2183: %userinfo = %{$results{$uname}};
2184: }
2185: return ($outcome,%userinfo);
2186: }
2187:
2188: sub get_multiple_instusers {
2189: my ($udom,$users,$caller) = @_;
2190: my ($outcome,$results);
2191: if (ref($users) eq 'HASH') {
2192: my $count = keys(%{$users});
2193: my $requested = &freeze_escape($users);
2194: my $homeserver = &domain($udom,'primary');
2195: if ($homeserver ne '') {
2196: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2197: my $host=&hostname($homeserver);
2198: if ($queryid !~/^\Q$host\E\_/) {
2199: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2200: ' for host: '.$homeserver.'in domain '.$udom);
2201: return ($outcome,$results);
2202: }
2203: my $response = &get_query_reply($queryid);
2204: my $maxtries = 5;
2205: if ($count > 100) {
2206: $maxtries = 1+int($count/20);
2207: }
2208: my $tries = 1;
2209: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2210: $response = &get_query_reply($queryid);
2211: $tries ++;
2212: }
2213: if ($response eq '') {
2214: $results = {};
2215: foreach my $key (keys(%{$users})) {
2216: my ($uname,$id);
2217: if ($caller eq 'id') {
2218: $id = $key;
2219: } else {
2220: $uname = $key;
2221: }
2222: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2223: $outcome = $resp;
2224: if ($resp eq 'ok') {
2225: %{$results} = (%{$results}, %info);
2226: } else {
2227: last;
2228: }
2229: }
2230: } elsif(!&error($response) && ($response ne 'refused')) {
2231: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2232: $outcome = $response;
2233: } else {
2234: ($outcome,my $userdata) = split(/=/,$response,2);
2235: if ($outcome eq 'ok') {
2236: $results = &thaw_unescape($userdata);
2237: }
2238: }
2239: }
2240: }
2241: }
2242: return ($outcome,$results);
2243: }
2244:
2245: sub inst_rulecheck {
2246: my ($udom,$uname,$id,$item,$rules) = @_;
2247: my %returnhash;
2248: if ($udom ne '') {
2249: if (ref($rules) eq 'ARRAY') {
2250: @{$rules} = map {&escape($_);} (@{$rules});
2251: my $rulestr = join(':',@{$rules});
2252: my $homeserver=&domain($udom,'primary');
2253: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2254: my $response;
2255: if ($item eq 'username') {
2256: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2257: ':'.&escape($uname).':'.$rulestr,
2258: $homeserver));
2259: } elsif ($item eq 'id') {
2260: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2261: ':'.&escape($id).':'.$rulestr,
2262: $homeserver));
2263: } elsif ($item eq 'selfcreate') {
2264: $response=&unescape(&reply('instselfcreatecheck:'.
2265: &escape($udom).':'.&escape($uname).
2266: ':'.$rulestr,$homeserver));
2267: }
2268: if ($response ne 'refused') {
2269: my @pairs=split(/\&/,$response);
2270: foreach my $item (@pairs) {
2271: my ($key,$value)=split(/=/,$item,2);
2272: $key = &unescape($key);
2273: next if ($key =~ /^error: 2 /);
2274: $returnhash{$key}=&thaw_unescape($value);
2275: }
2276: }
2277: }
2278: }
2279: }
2280: return %returnhash;
2281: }
2282:
2283: sub inst_userrules {
2284: my ($udom,$check) = @_;
2285: my (%ruleshash,@ruleorder);
2286: if ($udom ne '') {
2287: my $homeserver=&domain($udom,'primary');
2288: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2289: my $response;
2290: if ($check eq 'id') {
2291: $response=&reply('instidrules:'.&escape($udom),
2292: $homeserver);
2293: } elsif ($check eq 'email') {
2294: $response=&reply('instemailrules:'.&escape($udom),
2295: $homeserver);
2296: } else {
2297: $response=&reply('instuserrules:'.&escape($udom),
2298: $homeserver);
2299: }
2300: if (($response ne 'refused') && ($response ne 'error') &&
2301: ($response ne 'unknown_cmd') &&
2302: ($response ne 'no_such_host')) {
2303: my ($hashitems,$orderitems) = split(/:/,$response);
2304: my @pairs=split(/\&/,$hashitems);
2305: foreach my $item (@pairs) {
2306: my ($key,$value)=split(/=/,$item,2);
2307: $key = &unescape($key);
2308: next if ($key =~ /^error: 2 /);
2309: $ruleshash{$key}=&thaw_unescape($value);
2310: }
2311: my @esc_order = split(/\&/,$orderitems);
2312: foreach my $item (@esc_order) {
2313: push(@ruleorder,&unescape($item));
2314: }
2315: }
2316: }
2317: }
2318: return (\%ruleshash,\@ruleorder);
2319: }
2320:
2321: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2322:
2323: sub get_domain_defaults {
2324: my ($domain,$ignore_cache) = @_;
2325: return if (($domain eq '') || ($domain eq 'public'));
2326: my $cachetime = 60*60*24;
2327: unless ($ignore_cache) {
2328: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2329: if (defined($cached)) {
2330: if (ref($result) eq 'HASH') {
2331: return %{$result};
2332: }
2333: }
2334: }
2335: my %domdefaults;
2336: my %domconfig =
2337: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2338: 'requestcourses','inststatus',
2339: 'coursedefaults','usersessions',
2340: 'requestauthor','selfenrollment',
2341: 'coursecategories','autoenroll',
2342: 'helpsettings'],$domain);
2343: my @coursetypes = ('official','unofficial','community','textbook');
2344: if (ref($domconfig{'defaults'}) eq 'HASH') {
2345: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2346: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2347: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2348: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2349: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2350: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2351: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2352: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2353: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2354: } else {
2355: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2356: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2357: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2358: }
2359: if (ref($domconfig{'quotas'}) eq 'HASH') {
2360: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2361: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2362: } else {
2363: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2364: }
2365: my @usertools = ('aboutme','blog','webdav','portfolio');
2366: foreach my $item (@usertools) {
2367: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2368: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2369: }
2370: }
2371: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2372: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2373: }
2374: }
2375: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2376: foreach my $item ('official','unofficial','community','textbook') {
2377: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2378: }
2379: }
2380: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2381: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2382: }
2383: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2384: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2385: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2386: }
2387: }
2388: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2389: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2390: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2391: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2392: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2393: }
2394: foreach my $type (@coursetypes) {
2395: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2396: unless ($type eq 'community') {
2397: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2398: }
2399: }
2400: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2401: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2402: }
2403: if ($domdefaults{'postsubmit'} eq 'on') {
2404: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2405: $domdefaults{$type.'postsubtimeout'} =
2406: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2407: }
2408: }
2409: }
2410: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2411: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2412: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2413: if (@clonecodes) {
2414: $domdefaults{'canclone'} = join('+',@clonecodes);
2415: }
2416: }
2417: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2418: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2419: }
2420: if ($domconfig{'coursedefaults'}{'texengine'}) {
2421: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2422: }
2423: }
2424: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2425: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2426: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2427: }
2428: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2429: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2430: }
2431: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2432: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2433: }
2434: if (ref($domconfig{'usersessions'}{'offloadoth'}) eq 'HASH') {
2435: $domdefaults{'offloadoth'} = $domconfig{'usersessions'}{'offloadoth'};
2436: }
2437: }
2438: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2439: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2440: my @settings = ('types','registered','enroll_dates','access_dates','section',
2441: 'approval','limit');
2442: foreach my $type (@coursetypes) {
2443: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2444: my @mgrdc = ();
2445: foreach my $item (@settings) {
2446: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2447: push(@mgrdc,$item);
2448: }
2449: }
2450: if (@mgrdc) {
2451: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2452: }
2453: }
2454: }
2455: }
2456: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2457: foreach my $type (@coursetypes) {
2458: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2459: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2460: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2461: }
2462: }
2463: }
2464: }
2465: }
2466: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2467: $domdefaults{'catauth'} = 'std';
2468: $domdefaults{'catunauth'} = 'std';
2469: if ($domconfig{'coursecategories'}{'auth'}) {
2470: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2471: }
2472: if ($domconfig{'coursecategories'}{'unauth'}) {
2473: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2474: }
2475: }
2476: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2477: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2478: }
2479: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2480: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2481: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2482: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2483: }
2484: }
2485: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2486: return %domdefaults;
2487: }
2488:
2489: sub get_dom_cats {
2490: my ($dom) = @_;
2491: return unless (&domain($dom));
2492: my ($cats,$cached)=&is_cached_new('cats',$dom);
2493: unless (defined($cached)) {
2494: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2495: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2496: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2497: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2498: } else {
2499: $cats = {};
2500: }
2501: } else {
2502: $cats = {};
2503: }
2504: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2505: }
2506: return $cats;
2507: }
2508:
2509: sub get_dom_instcats {
2510: my ($dom) = @_;
2511: return unless (&domain($dom));
2512: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2513: unless (defined($cached)) {
2514: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2515: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2516: if ($totcodes > 0) {
2517: my $caller = 'global';
2518: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2519: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2520: $instcats = {
2521: codes => \%codes,
2522: codetitles => \@codetitles,
2523: cat_titles => \%cat_titles,
2524: cat_order => \%cat_order,
2525: };
2526: &do_cache_new('instcats',$dom,$instcats,3600);
2527: }
2528: }
2529: }
2530: return $instcats;
2531: }
2532:
2533: sub retrieve_instcodes {
2534: my ($coursecodes,$dom) = @_;
2535: my $totcodes;
2536: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2537: foreach my $course (keys(%courses)) {
2538: if (ref($courses{$course}) eq 'HASH') {
2539: if ($courses{$course}{'inst_code'} ne '') {
2540: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2541: $totcodes ++;
2542: }
2543: }
2544: }
2545: return $totcodes;
2546: }
2547:
2548: # --------------------------------------------- Get domain config for passwords
2549:
2550: sub get_passwdconf {
2551: my ($dom) = @_;
2552: my (%passwdconf,$gotconf,$lookup);
2553: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2554: if (defined($cached)) {
2555: if (ref($result) eq 'HASH') {
2556: %passwdconf = %{$result};
2557: $gotconf = 1;
2558: }
2559: }
2560: unless ($gotconf) {
2561: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2562: if (ref($domconfig{'passwords'}) eq 'HASH') {
2563: %passwdconf = %{$domconfig{'passwords'}};
2564: }
2565: my $cachetime = 24*60*60;
2566: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2567: }
2568: return %passwdconf;
2569: }
2570:
2571: # --------------------------------------------------- Assign a key to a student
2572:
2573: sub assign_access_key {
2574: #
2575: # a valid key looks like uname:udom#comments
2576: # comments are being appended
2577: #
2578: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2579: $kdom=
2580: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2581: $knum=
2582: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2583: $cdom=
2584: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2585: $cnum=
2586: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2587: $udom=$env{'user.name'} unless (defined($udom));
2588: $uname=$env{'user.domain'} unless (defined($uname));
2589: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2590: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2591: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2592: # assigned to this person
2593: # - this should not happen,
2594: # unless something went wrong
2595: # the first time around
2596: # ready to assign
2597: $logentry=$1.'; '.$logentry;
2598: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2599: $kdom,$knum) eq 'ok') {
2600: # key now belongs to user
2601: my $envkey='key.'.$cdom.'_'.$cnum;
2602: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2603: &appenv({'environment.'.$envkey => $ckey});
2604: return 'ok';
2605: } else {
2606: return
2607: 'error: Count not permanently assign key, will need to be re-entered later.';
2608: }
2609: } else {
2610: return 'error: Could not assign key, try again later.';
2611: }
2612: } elsif (!$existing{$ckey}) {
2613: # the key does not exist
2614: return 'error: The key does not exist';
2615: } else {
2616: # the key is somebody else's
2617: return 'error: The key is already in use';
2618: }
2619: }
2620:
2621: # ------------------------------------------ put an additional comment on a key
2622:
2623: sub comment_access_key {
2624: #
2625: # a valid key looks like uname:udom#comments
2626: # comments are being appended
2627: #
2628: my ($ckey,$cdom,$cnum,$logentry)=@_;
2629: $cdom=
2630: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2631: $cnum=
2632: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2633: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2634: if ($existing{$ckey}) {
2635: $existing{$ckey}.='; '.$logentry;
2636: # ready to assign
2637: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2638: $cdom,$cnum) eq 'ok') {
2639: return 'ok';
2640: } else {
2641: return 'error: Count not store comment.';
2642: }
2643: } else {
2644: # the key does not exist
2645: return 'error: The key does not exist';
2646: }
2647: }
2648:
2649: # ------------------------------------------------------ Generate a set of keys
2650:
2651: sub generate_access_keys {
2652: my ($number,$cdom,$cnum,$logentry)=@_;
2653: $cdom=
2654: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2655: $cnum=
2656: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2657: unless (&allowed('mky',$cdom)) { return 0; }
2658: unless (($cdom) && ($cnum)) { return 0; }
2659: if ($number>10000) { return 0; }
2660: sleep(2); # make sure don't get same seed twice
2661: srand(time()^($$+($$<<15))); # from "Programming Perl"
2662: my $total=0;
2663: for (my $i=1;$i<=$number;$i++) {
2664: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2665: sprintf("%lx",int(100000*rand)).'-'.
2666: sprintf("%lx",int(100000*rand));
2667: $newkey=~s/1/g/g; # folks mix up 1 and l
2668: $newkey=~s/0/h/g; # and also 0 and O
2669: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2670: if ($existing{$newkey}) {
2671: $i--;
2672: } else {
2673: if (&put('accesskeys',
2674: { $newkey => '# generated '.localtime().
2675: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2676: '; '.$logentry },
2677: $cdom,$cnum) eq 'ok') {
2678: $total++;
2679: }
2680: }
2681: }
2682: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2683: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2684: return $total;
2685: }
2686:
2687: # ------------------------------------------------------- Validate an accesskey
2688:
2689: sub validate_access_key {
2690: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2691: $cdom=
2692: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2693: $cnum=
2694: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2695: $udom=$env{'user.domain'} unless (defined($udom));
2696: $uname=$env{'user.name'} unless (defined($uname));
2697: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2698: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2699: }
2700:
2701: # ------------------------------------- Find the section of student in a course
2702: sub devalidate_getsection_cache {
2703: my ($udom,$unam,$courseid)=@_;
2704: my $hashid="$udom:$unam:$courseid";
2705: &devalidate_cache_new('getsection',$hashid);
2706: }
2707:
2708: sub courseid_to_courseurl {
2709: my ($courseid) = @_;
2710: #already url style courseid
2711: return $courseid if ($courseid =~ m{^/});
2712:
2713: if (exists($env{'course.'.$courseid.'.num'})) {
2714: my $cnum = $env{'course.'.$courseid.'.num'};
2715: my $cdom = $env{'course.'.$courseid.'.domain'};
2716: return "/$cdom/$cnum";
2717: }
2718:
2719: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2720: if (exists($courseinfo{'num'})) {
2721: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2722: }
2723:
2724: return undef;
2725: }
2726:
2727: sub getsection {
2728: my ($udom,$unam,$courseid)=@_;
2729: my $cachetime=1800;
2730:
2731: my $hashid="$udom:$unam:$courseid";
2732: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2733: if (defined($cached)) { return $result; }
2734:
2735: my %Pending;
2736: my %Expired;
2737: #
2738: # Each role can either have not started yet (pending), be active,
2739: # or have expired.
2740: #
2741: # If there is an active role, we are done.
2742: #
2743: # If there is more than one role which has not started yet,
2744: # choose the one which will start sooner
2745: # If there is one role which has not started yet, return it.
2746: #
2747: # If there is more than one expired role, choose the one which ended last.
2748: # If there is a role which has expired, return it.
2749: #
2750: $courseid = &courseid_to_courseurl($courseid);
2751: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2752: foreach my $key (keys(%roleshash)) {
2753: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2754: my $section=$1;
2755: if ($key eq $courseid.'_st') { $section=''; }
2756: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2757: my $now=time;
2758: if (defined($end) && $end && ($now > $end)) {
2759: $Expired{$end}=$section;
2760: next;
2761: }
2762: if (defined($start) && $start && ($now < $start)) {
2763: $Pending{$start}=$section;
2764: next;
2765: }
2766: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2767: }
2768: #
2769: # Presumedly there will be few matching roles from the above
2770: # loop and the sorting time will be negligible.
2771: if (scalar(keys(%Pending))) {
2772: my ($time) = sort {$a <=> $b} keys(%Pending);
2773: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2774: }
2775: if (scalar(keys(%Expired))) {
2776: my @sorted = sort {$a <=> $b} keys(%Expired);
2777: my $time = pop(@sorted);
2778: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2779: }
2780: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2781: }
2782:
2783: sub save_cache {
2784: &purge_remembered();
2785: #&Apache::loncommon::validate_page();
2786: undef(%env);
2787: undef($env_loaded);
2788: }
2789:
2790: my $to_remember=-1;
2791: my %remembered;
2792: my %accessed;
2793: my $kicks=0;
2794: my $hits=0;
2795: sub make_key {
2796: my ($name,$id) = @_;
2797: if (length($id) > 65
2798: && length(&escape($id)) > 200) {
2799: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2800: }
2801: return &escape($name.':'.$id);
2802: }
2803:
2804: sub devalidate_cache_new {
2805: my ($name,$id,$debug) = @_;
2806: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2807: my $remembered_id=$name.':'.$id;
2808: $id=&make_key($name,$id);
2809: $memcache->delete($id);
2810: delete($remembered{$remembered_id});
2811: delete($accessed{$remembered_id});
2812: }
2813:
2814: sub is_cached_new {
2815: my ($name,$id,$debug) = @_;
2816: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2817: # keys in %remembered hash, which persists for
2818: # duration of request (no restriction on key length).
2819: if (exists($remembered{$remembered_id})) {
2820: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2821: $accessed{$remembered_id}=[&gettimeofday()];
2822: $hits++;
2823: return ($remembered{$remembered_id},1);
2824: }
2825: $id=&make_key($name,$id);
2826: my $value = $memcache->get($id);
2827: if (!(defined($value))) {
2828: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2829: return (undef,undef);
2830: }
2831: if ($value eq '__undef__') {
2832: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2833: $value=undef;
2834: }
2835: &make_room($remembered_id,$value,$debug);
2836: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2837: return ($value,1);
2838: }
2839:
2840: sub do_cache_new {
2841: my ($name,$id,$value,$time,$debug) = @_;
2842: my $remembered_id=$name.':'.$id;
2843: $id=&make_key($name,$id);
2844: my $setvalue=$value;
2845: if (!defined($setvalue)) {
2846: $setvalue='__undef__';
2847: }
2848: if (!defined($time) ) {
2849: $time=600;
2850: }
2851: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2852: my $result = $memcache->set($id,$setvalue,$time);
2853: if (! $result) {
2854: &logthis("caching of id -> $id failed");
2855: $memcache->disconnect_all();
2856: }
2857: # need to make a copy of $value
2858: &make_room($remembered_id,$value,$debug);
2859: return $value;
2860: }
2861:
2862: sub make_room {
2863: my ($remembered_id,$value,$debug)=@_;
2864:
2865: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
2866: : $value;
2867: if ($to_remember<0) { return; }
2868: $accessed{$remembered_id}=[&gettimeofday()];
2869: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2870: my $to_kick;
2871: my $max_time=0;
2872: foreach my $other (keys(%accessed)) {
2873: if (&tv_interval($accessed{$other}) > $max_time) {
2874: $to_kick=$other;
2875: $max_time=&tv_interval($accessed{$other});
2876: }
2877: }
2878: delete($remembered{$to_kick});
2879: delete($accessed{$to_kick});
2880: $kicks++;
2881: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2882: return;
2883: }
2884:
2885: sub purge_remembered {
2886: #&logthis("Tossing ".scalar(keys(%remembered)));
2887: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2888: undef(%remembered);
2889: undef(%accessed);
2890: }
2891: # ------------------------------------- Read an entry from a user's environment
2892:
2893: sub userenvironment {
2894: my ($udom,$unam,@what)=@_;
2895: my $items;
2896: foreach my $item (@what) {
2897: $items.=&escape($item).'&';
2898: }
2899: $items=~s/\&$//;
2900: my %returnhash=();
2901: my $uhome = &homeserver($unam,$udom);
2902: unless ($uhome eq 'no_host') {
2903: my @answer=split(/\&/,
2904: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2905: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2906: return %returnhash;
2907: }
2908: my $i;
2909: for ($i=0;$i<=$#what;$i++) {
2910: $returnhash{$what[$i]}=&unescape($answer[$i]);
2911: }
2912: }
2913: return %returnhash;
2914: }
2915:
2916: # ---------------------------------------------------------- Get a studentphoto
2917: sub studentphoto {
2918: my ($udom,$unam,$ext) = @_;
2919: my $home=&Apache::lonnet::homeserver($unam,$udom);
2920: if (defined($env{'request.course.id'})) {
2921: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2922: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2923: return(&retrievestudentphoto($udom,$unam,$ext));
2924: } else {
2925: my ($result,$perm_reqd)=
2926: &Apache::lonnet::auto_photo_permission($unam,$udom);
2927: if ($result eq 'ok') {
2928: if (!($perm_reqd eq 'yes')) {
2929: return(&retrievestudentphoto($udom,$unam,$ext));
2930: }
2931: }
2932: }
2933: }
2934: } else {
2935: my ($result,$perm_reqd) =
2936: &Apache::lonnet::auto_photo_permission($unam,$udom);
2937: if ($result eq 'ok') {
2938: if (!($perm_reqd eq 'yes')) {
2939: return(&retrievestudentphoto($udom,$unam,$ext));
2940: }
2941: }
2942: }
2943: return '/adm/lonKaputt/lonlogo_broken.gif';
2944: }
2945:
2946: sub retrievestudentphoto {
2947: my ($udom,$unam,$ext,$type) = @_;
2948: my $home=&Apache::lonnet::homeserver($unam,$udom);
2949: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2950: if ($ret eq 'ok') {
2951: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2952: if ($type eq 'thumbnail') {
2953: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2954: }
2955: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2956: return $tokenurl;
2957: } else {
2958: if ($type eq 'thumbnail') {
2959: return '/adm/lonKaputt/genericstudent_tn.gif';
2960: } else {
2961: return '/adm/lonKaputt/lonlogo_broken.gif';
2962: }
2963: }
2964: }
2965:
2966: # -------------------------------------------------------------------- New chat
2967:
2968: sub chatsend {
2969: my ($newentry,$anon,$group)=@_;
2970: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2971: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2972: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2973: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2974: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2975: &escape($newentry)).':'.$group,$chome);
2976: }
2977:
2978: # ------------------------------------------ Find current version of a resource
2979:
2980: sub getversion {
2981: my $fname=&clutter(shift);
2982: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2983: return ¤tversion(&filelocation('',$fname));
2984: }
2985:
2986: sub currentversion {
2987: my $fname=shift;
2988: my $author=$fname;
2989: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2990: my ($udom,$uname)=split(/\//,$author);
2991: my $home=&homeserver($uname,$udom);
2992: if ($home eq 'no_host') {
2993: return -1;
2994: }
2995: my $answer=&reply("currentversion:$fname",$home);
2996: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2997: return -1;
2998: }
2999: return $answer;
3000: }
3001:
3002: #
3003: # Return special version number of resource if set by override, empty otherwise
3004: #
3005: sub usedversion {
3006: my $fname=shift;
3007: unless ($fname) { $fname=$env{'request.uri'}; }
3008: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
3009: if ($urlversion) { return $urlversion; }
3010: return '';
3011: }
3012:
3013: # ----------------------------- Subscribe to a resource, return URL if possible
3014:
3015: sub subscribe {
3016: my $fname=shift;
3017: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
3018: $fname=~s/[\n\r]//g;
3019: my $author=$fname;
3020: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3021: my ($udom,$uname)=split(/\//,$author);
3022: my $home=homeserver($uname,$udom);
3023: if ($home eq 'no_host') {
3024: return 'not_found';
3025: }
3026: my $answer=reply("sub:$fname",$home);
3027: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
3028: $answer.=' by '.$home;
3029: }
3030: return $answer;
3031: }
3032:
3033: # -------------------------------------------------------------- Replicate file
3034:
3035: sub repcopy {
3036: my $filename=shift;
3037: $filename=~s/\/+/\//g;
3038: my $londocroot = $perlvar{'lonDocRoot'};
3039: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3040: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3041: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3042: $filename=~m{^/*(uploaded|editupload)/}) {
3043: return &repcopy_userfile($filename);
3044: }
3045: $filename=~s/[\n\r]//g;
3046: my $transname="$filename.in.transfer";
3047: # FIXME: this should flock
3048: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3049: my $remoteurl=subscribe($filename);
3050: if ($remoteurl =~ /^con_lost by/) {
3051: &logthis("Subscribe returned $remoteurl: $filename");
3052: return 'unavailable';
3053: } elsif ($remoteurl eq 'not_found') {
3054: #&logthis("Subscribe returned not_found: $filename");
3055: return 'not_found';
3056: } elsif ($remoteurl =~ /^rejected by/) {
3057: &logthis("Subscribe returned $remoteurl: $filename");
3058: return 'forbidden';
3059: } elsif ($remoteurl eq 'directory') {
3060: return 'ok';
3061: } else {
3062: my $author=$filename;
3063: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3064: my ($udom,$uname)=split(/\//,$author);
3065: my $home=homeserver($uname,$udom);
3066: unless ($home eq $perlvar{'lonHostID'}) {
3067: my @parts=split(/\//,$filename);
3068: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3069: if ($path ne "$londocroot/res") {
3070: &logthis("Malconfiguration for replication: $filename");
3071: return 'bad_request';
3072: }
3073: my $count;
3074: for ($count=5;$count<$#parts;$count++) {
3075: $path.="/$parts[$count]";
3076: if ((-e $path)!=1) {
3077: mkdir($path,0777);
3078: }
3079: }
3080: my $ua=new LWP::UserAgent;
3081: my $request=new HTTP::Request('GET',"$remoteurl");
3082: my $response=$ua->request($request,$transname);
3083: if ($response->is_error()) {
3084: unlink($transname);
3085: my $message=$response->status_line;
3086: &logthis("<font color=\"blue\">WARNING:"
3087: ." LWP get: $message: $filename</font>");
3088: return 'unavailable';
3089: } else {
3090: if ($remoteurl!~/\.meta$/) {
3091: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3092: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3093: if ($mresponse->is_error()) {
3094: unlink($filename.'.meta');
3095: &logthis(
3096: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3097: }
3098: }
3099: rename($transname,$filename);
3100: return 'ok';
3101: }
3102: }
3103: }
3104: }
3105:
3106: # ------------------------------------------------- Unsubscribe from a resource
3107:
3108: sub unsubscribe {
3109: my ($fname) = @_;
3110: my $answer;
3111: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return $answer; }
3112: $fname=~s/[\n\r]//g;
3113: my $author=$fname;
3114: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3115: my ($udom,$uname)=split(/\//,$author);
3116: my $home=homeserver($uname,$udom);
3117: if ($home eq 'no_host') {
3118: $answer = 'no_host';
3119: } elsif (grep { $_ eq $home } ¤t_machine_ids()) {
3120: $answer = 'home';
3121: } else {
3122: $answer = reply("unsub:$fname",$home);
3123: }
3124: return $answer;
3125: }
3126:
3127: # ------------------------------------------------ Get server side include body
3128: sub ssi_body {
3129: my ($filelink,%form)=@_;
3130: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3131: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3132: }
3133: my $output='';
3134: my $response;
3135: if ($filelink=~/^https?\:/) {
3136: ($output,$response)=&externalssi($filelink);
3137: } else {
3138: $filelink .= $filelink=~/\?/ ? '&' : '?';
3139: $filelink .= 'inhibitmenu=yes';
3140: ($output,$response)=&ssi($filelink,%form);
3141: }
3142: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3143: $output=~s/^.*?\<body[^\>]*\>//si;
3144: $output=~s/\<\/body\s*\>.*?$//si;
3145: if (wantarray) {
3146: return ($output, $response);
3147: } else {
3148: return $output;
3149: }
3150: }
3151:
3152: # --------------------------------------------------------- Server Side Include
3153:
3154: sub absolute_url {
3155: my ($host_name) = @_;
3156: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3157: if ($host_name eq '') {
3158: $host_name = $ENV{'SERVER_NAME'};
3159: }
3160: return $protocol.$host_name;
3161: }
3162:
3163: #
3164: # Server side include.
3165: # Parameters:
3166: # fn Possibly encrypted resource name/id.
3167: # form Hash that describes how the rendering should be done
3168: # and other things.
3169: # Returns:
3170: # Scalar context: The content of the response.
3171: # Array context: 2 element list of the content and the full response object.
3172: #
3173: sub ssi {
3174:
3175: my ($fn,%form)=@_;
3176: my ($request,$response);
3177:
3178: $form{'no_update_last_known'}=1;
3179: &Apache::lonenc::check_encrypt(\$fn);
3180: if (%form) {
3181: $request=new HTTP::Request('POST',&absolute_url().$fn);
3182: $request->content(join('&',map {
3183: my $name = escape($_);
3184: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3185: ? join("&$name=", map {escape($_) } @{$form{$_}})
3186: : &escape($form{$_}) );
3187: } keys(%form)));
3188: } else {
3189: $request=new HTTP::Request('GET',&absolute_url().$fn);
3190: }
3191:
3192: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3193:
3194: if (($env{'request.course.id'}) &&
3195: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3196: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3197: ($form{'grade_symb'} ne '') &&
3198: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3199: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3200: if (LWP::UserAgent->VERSION >= 5.834) {
3201: my $ua=new LWP::UserAgent;
3202: $ua->local_address('127.0.0.1');
3203: $response = $ua->request($request);
3204: } else {
3205: {
3206: require LWP::Protocol::http;
3207: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3208: my $ua=new LWP::UserAgent;
3209: $response = $ua->request($request);
3210: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3211: }
3212: }
3213: } else {
3214: my $ua=new LWP::UserAgent;
3215: $response = $ua->request($request);
3216: }
3217: if (wantarray) {
3218: return ($response->content, $response);
3219: } else {
3220: return $response->content;
3221: }
3222: }
3223:
3224: sub externalssi {
3225: my ($url)=@_;
3226: my $ua=new LWP::UserAgent;
3227: my $request=new HTTP::Request('GET',$url);
3228: my $response=$ua->request($request);
3229: if (wantarray) {
3230: return ($response->content, $response);
3231: } else {
3232: return $response->content;
3233: }
3234: }
3235:
3236: # If the local copy of a replicated resource is outdated, trigger a
3237: # connection from the homeserver to flush the delayed queue. If no update
3238: # happens, remove local copies of outdated resource (and corresponding
3239: # metadata file).
3240:
3241: sub remove_stale_resfile {
3242: my ($url) = @_;
3243: my $removed;
3244: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3245: my $audom = $1;
3246: my $auname = $2;
3247: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3248: my $homeserver = &homeserver($auname,$audom);
3249: unless (($homeserver eq 'no_host') ||
3250: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3251: my $fname = &filelocation('',$url);
3252: if (-e $fname) {
3253: my $hostname = &hostname($homeserver);
3254: if ($hostname) {
3255: my $protocol = $protocol{$homeserver};
3256: $protocol = 'http' if ($protocol ne 'https');
3257: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
3258: my $ua=new LWP::UserAgent;
3259: $ua->timeout(5);
3260: my $request=new HTTP::Request('HEAD',$uri);
3261: my $response=$ua->request($request);
3262: if ($response->is_success()) {
3263: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3264: my $locmodtime = (stat($fname))[9];
3265: if ($locmodtime < $remmodtime) {
3266: my $stale;
3267: my $answer = &reply('pong',$homeserver);
3268: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3269: sleep(0.2);
3270: $locmodtime = (stat($fname))[9];
3271: if ($locmodtime < $remmodtime) {
3272: my $posstransfer = $fname.'.in.transfer';
3273: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3274: $removed = 1;
3275: } else {
3276: $stale = 1;
3277: }
3278: } else {
3279: $removed = 1;
3280: }
3281: } else {
3282: $stale = 1;
3283: }
3284: if ($stale) {
3285: if (unlink($fname)) {
3286: if ($uri!~/\.meta$/) {
3287: if (-e $fname.'.meta') {
3288: unlink($fname.'.meta');
3289: }
3290: }
3291: my $unsubresult = &unsubscribe($fname);
3292: unless ($unsubresult eq 'ok') {
3293: &logthis("no unsub of $fname from $homeserver, reason: $unsubresult");
3294: }
3295: $removed = 1;
3296: }
3297: }
3298: }
3299: }
3300: }
3301: }
3302: }
3303: }
3304: }
3305: return $removed;
3306: }
3307:
3308: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3309:
3310: sub allowuploaded {
3311: my ($srcurl,$url)=@_;
3312: $url=&clutter(&declutter($url));
3313: my $dir=$url;
3314: $dir=~s/\/[^\/]+$//;
3315: my %httpref=();
3316: my $httpurl=&hreflocation('',$url);
3317: $httpref{'httpref.'.$httpurl}=$srcurl;
3318: &Apache::lonnet::appenv(\%httpref);
3319: }
3320:
3321: #
3322: # Determine if the current user should be able to edit a particular resource,
3323: # when viewing in course context.
3324: # (a) When viewing resource used to determine if "Edit" item is included in
3325: # Functions.
3326: # (b) When displaying folder contents in course editor, used to determine if
3327: # "Edit" link will be displayed alongside resource.
3328: #
3329: # input: six args -- filename (decluttered), course number, course domain,
3330: # url, symb (if registered) and group (if this is a group
3331: # item -- e.g., bulletin board, group page etc.).
3332: # output: array of five scalars --
3333: # $cfile -- url for file editing if editable on current server
3334: # $home -- homeserver of resource (i.e., for author if published,
3335: # or course if uploaded.).
3336: # $switchserver -- 1 if server switch will be needed.
3337: # $forceedit -- 1 if icon/link should be to go to edit mode
3338: # $forceview -- 1 if icon/link should be to go to view mode
3339: #
3340:
3341: sub can_edit_resource {
3342: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3343: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3344: #
3345: # For aboutme pages user can only edit his/her own.
3346: #
3347: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3348: my ($sdom,$sname) = ($1,$2);
3349: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3350: $home = $env{'user.home'};
3351: $cfile = $resurl;
3352: if ($env{'form.forceedit'}) {
3353: $forceview = 1;
3354: } else {
3355: $forceedit = 1;
3356: }
3357: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3358: } else {
3359: return;
3360: }
3361: }
3362:
3363: if ($env{'request.course.id'}) {
3364: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3365: if ($group ne '') {
3366: # if this is a group homepage or group bulletin board, check group privs
3367: my $allowed = 0;
3368: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3369: if ((&allowed('mdg',$env{'request.course.id'}.
3370: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3371: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3372: $allowed = 1;
3373: }
3374: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3375: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3376: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3377: $allowed = 1;
3378: }
3379: }
3380: if ($allowed) {
3381: $home=&homeserver($cnum,$cdom);
3382: if ($env{'form.forceedit'}) {
3383: $forceview = 1;
3384: } else {
3385: $forceedit = 1;
3386: }
3387: $cfile = $resurl;
3388: } else {
3389: return;
3390: }
3391: } else {
3392: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3393: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3394: return;
3395: }
3396: } elsif (!$crsedit) {
3397: #
3398: # No edit allowed where CC has switched to student role.
3399: #
3400: return;
3401: }
3402: }
3403: }
3404:
3405: if ($file ne '') {
3406: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3407: if (&is_course_upload($file,$cnum,$cdom)) {
3408: $uploaded = 1;
3409: $incourse = 1;
3410: if ($file =~/\.(htm|html|css|js|txt)$/) {
3411: $cfile = &hreflocation('',$file);
3412: if ($env{'form.forceedit'}) {
3413: $forceview = 1;
3414: } else {
3415: $forceedit = 1;
3416: }
3417: }
3418: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3419: $incourse = 1;
3420: if ($env{'form.forceedit'}) {
3421: $forceview = 1;
3422: } else {
3423: $forceedit = 1;
3424: }
3425: $cfile = $resurl;
3426: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3427: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3428: $incourse = 1;
3429: if ($env{'form.forceedit'}) {
3430: $forceview = 1;
3431: } else {
3432: $forceedit = 1;
3433: }
3434: $cfile = $resurl;
3435: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3436: $incourse = 1;
3437: $cfile = $resurl.'/smpedit';
3438: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3439: $incourse = 1;
3440: if ($env{'form.forceedit'}) {
3441: $forceview = 1;
3442: } else {
3443: $forceedit = 1;
3444: }
3445: $cfile = $resurl;
3446: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3447: my ($map,$id,$res) = &decode_symb($symb);
3448: if ($map =~ /\.page$/) {
3449: $incourse = 1;
3450: if ($env{'form.forceedit'}) {
3451: $forceview = 1;
3452: $cfile = $map;
3453: } else {
3454: $forceedit = 1;
3455: $cfile = '/adm/wrapper'.$resurl;
3456: }
3457: }
3458: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3459: $incourse = 1;
3460: if ($env{'form.forceedit'}) {
3461: $forceview = 1;
3462: } else {
3463: $forceedit = 1;
3464: }
3465: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3466: }
3467: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3468: my $template = '/res/lib/templates/simpleproblem.problem';
3469: if (&is_on_map($template)) {
3470: $incourse = 1;
3471: $forceview = 1;
3472: $cfile = $template;
3473: }
3474: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3475: $incourse = 1;
3476: if ($env{'form.forceedit'}) {
3477: $forceview = 1;
3478: } else {
3479: $forceedit = 1;
3480: }
3481: $cfile = $resurl;
3482: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3483: $incourse = 1;
3484: $forceview = 1;
3485: if ($symb) {
3486: my ($map,$id,$res)=&decode_symb($symb);
3487: $env{'request.symb'} = $symb;
3488: $cfile = &clutter($res);
3489: } else {
3490: $cfile = $env{'form.suppurl'};
3491: $cfile =~ s{^http://}{};
3492: $cfile = '/adm/wrapper/ext/'.$cfile;
3493: }
3494: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3495: if ($env{'form.forceedit'}) {
3496: $forceview = 1;
3497: } else {
3498: $forceedit = 1;
3499: }
3500: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3501: }
3502: }
3503: if ($uploaded || $incourse) {
3504: $home=&homeserver($cnum,$cdom);
3505: } elsif ($file !~ m{/$}) {
3506: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3507: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3508: # Check that the user has permission to edit this resource
3509: my $setpriv = 1;
3510: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3511: if (defined($cfudom)) {
3512: $home=&homeserver($cfuname,$cfudom);
3513: $cfile=$file;
3514: }
3515: }
3516: if (($cfile ne '') && (!$incourse || $uploaded) &&
3517: (($home ne '') && ($home ne 'no_host'))) {
3518: my @ids=¤t_machine_ids();
3519: unless (grep(/^\Q$home\E$/,@ids)) {
3520: $switchserver=1;
3521: }
3522: }
3523: }
3524: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3525: }
3526:
3527: sub is_course_upload {
3528: my ($file,$cnum,$cdom) = @_;
3529: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3530: $uploadpath =~ s{^\/}{};
3531: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3532: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3533: return 1;
3534: }
3535: return;
3536: }
3537:
3538: sub in_course {
3539: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3540: if ($hideprivileged) {
3541: my $skipuser;
3542: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3543: my @possdoms = ($cdom);
3544: if ($coursehash{'checkforpriv'}) {
3545: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3546: }
3547: if (&privileged($uname,$udom,\@possdoms)) {
3548: $skipuser = 1;
3549: if ($coursehash{'nothideprivileged'}) {
3550: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3551: my $user;
3552: if ($item =~ /:/) {
3553: $user = $item;
3554: } else {
3555: $user = join(':',split(/[\@]/,$item));
3556: }
3557: if ($user eq $uname.':'.$udom) {
3558: undef($skipuser);
3559: last;
3560: }
3561: }
3562: }
3563: if ($skipuser) {
3564: return 0;
3565: }
3566: }
3567: }
3568: $type ||= 'any';
3569: if (!defined($cdom) || !defined($cnum)) {
3570: my $cid = $env{'request.course.id'};
3571: $cdom = $env{'course.'.$cid.'.domain'};
3572: $cnum = $env{'course.'.$cid.'.num'};
3573: }
3574: my $typesref;
3575: if (($type eq 'any') || ($type eq 'all')) {
3576: $typesref = ['active','previous','future'];
3577: } elsif ($type eq 'previous' || $type eq 'future') {
3578: $typesref = [$type];
3579: }
3580: my %roles = &get_my_roles($uname,$udom,'userroles',
3581: $typesref,undef,[$cdom]);
3582: my ($tmp) = keys(%roles);
3583: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3584: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3585: if (@course_roles > 0) {
3586: return 1;
3587: }
3588: return 0;
3589: }
3590:
3591: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3592: # input: action, courseID, current domain, intended
3593: # path to file, source of file, instruction to parse file for objects,
3594: # ref to hash for embedded objects,
3595: # ref to hash for codebase of java objects.
3596: # reference to scalar to accommodate mime type determined
3597: # from File::MMagic if $parser = parse.
3598: #
3599: # output: url to file (if action was uploaddoc),
3600: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3601: #
3602: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3603: # course.
3604: #
3605: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3606: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3607: # course's home server.
3608: #
3609: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3610: # be copied from $source (current location) to
3611: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3612: # and will then be copied to
3613: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3614: # course's home server.
3615: #
3616: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3617: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3618: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3619: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3620: # in course's home server.
3621: #
3622:
3623: sub process_coursefile {
3624: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3625: $mimetype)=@_;
3626: my $fetchresult;
3627: my $home=&homeserver($docuname,$docudom);
3628: if ($action eq 'propagate') {
3629: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3630: $home);
3631: } else {
3632: my $fpath = '';
3633: my $fname = $file;
3634: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3635: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3636: my $filepath = &build_filepath($fpath);
3637: if ($action eq 'copy') {
3638: if ($source eq '') {
3639: $fetchresult = 'no source file';
3640: return $fetchresult;
3641: } else {
3642: my $destination = $filepath.'/'.$fname;
3643: rename($source,$destination);
3644: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3645: $home);
3646: }
3647: } elsif ($action eq 'uploaddoc') {
3648: open(my $fh,'>',$filepath.'/'.$fname);
3649: print $fh $env{'form.'.$source};
3650: close($fh);
3651: if ($parser eq 'parse') {
3652: my $mm = new File::MMagic;
3653: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3654: if ($type eq 'text/html') {
3655: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3656: unless ($parse_result eq 'ok') {
3657: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3658: }
3659: }
3660: if (ref($mimetype)) {
3661: $$mimetype = $type;
3662: }
3663: }
3664: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3665: $home);
3666: if ($fetchresult eq 'ok') {
3667: return '/uploaded/'.$fpath.'/'.$fname;
3668: } else {
3669: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3670: ' to host '.$home.': '.$fetchresult);
3671: return '/adm/notfound.html';
3672: }
3673: }
3674: }
3675: unless ( $fetchresult eq 'ok') {
3676: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3677: ' to host '.$home.': '.$fetchresult);
3678: }
3679: return $fetchresult;
3680: }
3681:
3682: sub build_filepath {
3683: my ($fpath) = @_;
3684: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3685: unless ($fpath eq '') {
3686: my @parts=split('/',$fpath);
3687: foreach my $part (@parts) {
3688: $filepath.= '/'.$part;
3689: if ((-e $filepath)!=1) {
3690: mkdir($filepath,0777);
3691: }
3692: }
3693: }
3694: return $filepath;
3695: }
3696:
3697: sub store_edited_file {
3698: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3699: my $file = $primary_url;
3700: $file =~ s#^/uploaded/$docudom/$docuname/##;
3701: my $fpath = '';
3702: my $fname = $file;
3703: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3704: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3705: my $filepath = &build_filepath($fpath);
3706: open(my $fh,'>',$filepath.'/'.$fname);
3707: print $fh $content;
3708: close($fh);
3709: my $home=&homeserver($docuname,$docudom);
3710: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3711: $home);
3712: if ($$fetchresult eq 'ok') {
3713: return '/uploaded/'.$fpath.'/'.$fname;
3714: } else {
3715: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3716: ' to host '.$home.': '.$$fetchresult);
3717: return '/adm/notfound.html';
3718: }
3719: }
3720:
3721: sub clean_filename {
3722: my ($fname,$args)=@_;
3723: # Replace Windows backslashes by forward slashes
3724: $fname=~s/\\/\//g;
3725: if (!$args->{'keep_path'}) {
3726: # Get rid of everything but the actual filename
3727: $fname=~s/^.*\/([^\/]+)$/$1/;
3728: }
3729: # Replace spaces by underscores
3730: $fname=~s/\s+/\_/g;
3731: # Transliterate non-ascii text to ascii
3732: my $lang = &Apache::lonlocal::current_language();
3733: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
3734: # Replace all other weird characters by nothing
3735: $fname=~s{[^/\w\.\-]}{}g;
3736: # Replace all .\d. sequences with _\d. so they no longer look like version
3737: # numbers
3738: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3739: return $fname;
3740: }
3741:
3742: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3743: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3744: # image with the same aspect ratio as the original, but with dimensions which do
3745: # not exceed $resizewidth and $resizeheight.
3746:
3747: sub resizeImage {
3748: my ($img_path,$resizewidth,$resizeheight) = @_;
3749: my $ima = Image::Magick->new;
3750: my $resized;
3751: if (-e $img_path) {
3752: $ima->Read($img_path);
3753: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3754: my $width = $ima->Get('width');
3755: my $height = $ima->Get('height');
3756: if ($width > $resizewidth) {
3757: my $factor = $width/$resizewidth;
3758: my $newheight = $height/$factor;
3759: $ima->Scale(width=>$resizewidth,height=>$newheight);
3760: $resized = 1;
3761: }
3762: }
3763: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3764: my $width = $ima->Get('width');
3765: my $height = $ima->Get('height');
3766: if ($height > $resizeheight) {
3767: my $factor = $height/$resizeheight;
3768: my $newwidth = $width/$factor;
3769: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3770: $resized = 1;
3771: }
3772: }
3773: if ($resized) {
3774: $ima->Write($img_path);
3775: }
3776: }
3777: return;
3778: }
3779:
3780: # --------------- Take an uploaded file and put it into the userfiles directory
3781: # input: $formname - the contents of the file are in $env{"form.$formname"}
3782: # the desired filename is in $env{"form.$formname.filename"}
3783: # $context - possible values: coursedoc, existingfile, overwrite,
3784: # canceloverwrite, scantron or ''.
3785: # if 'coursedoc': upload to the current course
3786: # if 'existingfile': write file to tmp/overwrites directory
3787: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3788: # $context is passed as argument to &finishuserfileupload
3789: # $subdir - directory in userfile to store the file into
3790: # $parser - instruction to parse file for objects ($parser = parse) or
3791: # if context is 'scantron', $parser is hashref of csv column mapping
3792: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3793: # Section => 4, CODE => 5, FirstQuestion => 9 }).
3794: # $allfiles - reference to hash for embedded objects
3795: # $codebase - reference to hash for codebase of java objects
3796: # $desuname - username for permanent storage of uploaded file
3797: # $dsetudom - domain for permanaent storage of uploaded file
3798: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3799: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3800: # $resizewidth - width (pixels) to which to resize uploaded image
3801: # $resizeheight - height (pixels) to which to resize uploaded image
3802: # $mimetype - reference to scalar to accommodate mime type determined
3803: # from File::MMagic.
3804: #
3805: # output: url of file in userspace, or error: <message>
3806: # or /adm/notfound.html if failure to upload occurse
3807:
3808: sub userfileupload {
3809: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3810: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3811: if (!defined($subdir)) { $subdir='unknown'; }
3812: my $fname=$env{'form.'.$formname.'.filename'};
3813: $fname=&clean_filename($fname);
3814: # See if there is anything left
3815: unless ($fname) { return 'error: no uploaded file'; }
3816: # If filename now begins with a . prepend unix timestamp _ milliseconds
3817: if ($fname =~ /^\./) {
3818: my ($s,$usec) = &gettimeofday();
3819: while (length($usec) < 6) {
3820: $usec = '0'.$usec;
3821: }
3822: $fname = $s.'_'.substr($usec,0,3).$fname;
3823: }
3824: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3825: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3826: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3827: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3828: my $now = time;
3829: my $filepath;
3830: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3831: $filepath = 'tmp/helprequests/'.$now;
3832: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3833: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3834: '_'.$env{'user.domain'}.'/pending';
3835: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3836: my ($docuname,$docudom);
3837: if ($destudom =~ /^$match_domain$/) {
3838: $docudom = $destudom;
3839: } else {
3840: $docudom = $env{'user.domain'};
3841: }
3842: if ($destuname =~ /^$match_username$/) {
3843: $docuname = $destuname;
3844: } else {
3845: $docuname = $env{'user.name'};
3846: }
3847: if (exists($env{'form.group'})) {
3848: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3849: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3850: }
3851: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3852: if ($context eq 'canceloverwrite') {
3853: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3854: if (-e $tempfile) {
3855: my @info = stat($tempfile);
3856: if ($info[9] eq $env{'form.timestamp'}) {
3857: unlink($tempfile);
3858: }
3859: }
3860: return;
3861: }
3862: }
3863: # Create the directory if not present
3864: my @parts=split(/\//,$filepath);
3865: my $fullpath = $perlvar{'lonDaemons'};
3866: for (my $i=0;$i<@parts;$i++) {
3867: $fullpath .= '/'.$parts[$i];
3868: if ((-e $fullpath)!=1) {
3869: mkdir($fullpath,0777);
3870: }
3871: }
3872: open(my $fh,'>',$fullpath.'/'.$fname);
3873: print $fh $env{'form.'.$formname};
3874: close($fh);
3875: if ($context eq 'existingfile') {
3876: my @info = stat($fullpath.'/'.$fname);
3877: return ($fullpath.'/'.$fname,$info[9]);
3878: } else {
3879: return $fullpath.'/'.$fname;
3880: }
3881: }
3882: if ($subdir eq 'scantron') {
3883: $fname = 'scantron_orig_'.$fname;
3884: } else {
3885: $fname="$subdir/$fname";
3886: }
3887: if ($context eq 'coursedoc') {
3888: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3889: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3890: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3891: return &finishuserfileupload($docuname,$docudom,
3892: $formname,$fname,$parser,$allfiles,
3893: $codebase,$thumbwidth,$thumbheight,
3894: $resizewidth,$resizeheight,$context,$mimetype);
3895: } else {
3896: if ($env{'form.folder'}) {
3897: $fname=$env{'form.folder'}.'/'.$fname;
3898: }
3899: return &process_coursefile('uploaddoc',$docuname,$docudom,
3900: $fname,$formname,$parser,
3901: $allfiles,$codebase,$mimetype);
3902: }
3903: } elsif (defined($destuname)) {
3904: my $docuname=$destuname;
3905: my $docudom=$destudom;
3906: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3907: $parser,$allfiles,$codebase,
3908: $thumbwidth,$thumbheight,
3909: $resizewidth,$resizeheight,$context,$mimetype);
3910: } else {
3911: my $docuname=$env{'user.name'};
3912: my $docudom=$env{'user.domain'};
3913: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3914: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3915: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3916: }
3917: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3918: $parser,$allfiles,$codebase,
3919: $thumbwidth,$thumbheight,
3920: $resizewidth,$resizeheight,$context,$mimetype);
3921: }
3922: }
3923:
3924: sub finishuserfileupload {
3925: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3926: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3927: my $path=$docudom.'/'.$docuname.'/';
3928: my $filepath=$perlvar{'lonDocRoot'};
3929:
3930: my ($fnamepath,$file,$fetchthumb);
3931: $file=$fname;
3932: if ($fname=~m|/|) {
3933: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3934: $path.=$fnamepath.'/';
3935: }
3936: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3937: my $count;
3938: for ($count=4;$count<=$#parts;$count++) {
3939: $filepath.="/$parts[$count]";
3940: if ((-e $filepath)!=1) {
3941: mkdir($filepath,0777);
3942: }
3943: }
3944:
3945: # Save the file
3946: {
3947: if (!open(FH,'>',$filepath.'/'.$file)) {
3948: &logthis('Failed to create '.$filepath.'/'.$file);
3949: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3950: return '/adm/notfound.html';
3951: }
3952: if ($context eq 'overwrite') {
3953: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3954: my $target = $filepath.'/'.$file;
3955: if (-e $source) {
3956: my @info = stat($source);
3957: if ($info[9] eq $env{'form.timestamp'}) {
3958: unless (&File::Copy::move($source,$target)) {
3959: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3960: return "Moving from $source failed";
3961: }
3962: } else {
3963: return "Temporary file: $source had unexpected date/time for last modification";
3964: }
3965: } else {
3966: return "Temporary file: $source missing";
3967: }
3968: } elsif (!print FH ($env{'form.'.$formname})) {
3969: &logthis('Failed to write to '.$filepath.'/'.$file);
3970: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3971: return '/adm/notfound.html';
3972: }
3973: close(FH);
3974: if ($resizewidth && $resizeheight) {
3975: my $mm = new File::MMagic;
3976: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3977: if ($mime_type =~ m{^image/}) {
3978: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3979: }
3980: }
3981: }
3982: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3983: if (ref($mimetype)) {
3984: if ($$mimetype eq '') {
3985: my $mm = new File::MMagic;
3986: my $type = $mm->checktype_filename($filepath.'/'.$file);
3987: $$mimetype = $type;
3988: }
3989: }
3990: }
3991: if (($context ne 'scantron') && ($parser eq 'parse')) {
3992: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3993: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3994: $allfiles,$codebase);
3995: unless ($parse_result eq 'ok') {
3996: &logthis('Failed to parse '.$filepath.$file.
3997: ' for embedded media: '.$parse_result);
3998: }
3999: }
4000: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4001: my $format = $env{'form.scantron_format'};
4002: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
4003: }
4004: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4005: my $input = $filepath.'/'.$file;
4006: my $output = $filepath.'/'.'tn-'.$file;
4007: my $thumbsize = $thumbwidth.'x'.$thumbheight;
4008: my @args = ('convert','-sample',$thumbsize,$input,$output);
4009: system({$args[0]} @args);
4010: if (-e $filepath.'/'.'tn-'.$file) {
4011: $fetchthumb = 1;
4012: }
4013: }
4014:
4015: # Notify homeserver to grep it
4016: #
4017: my $docuhome=&homeserver($docuname,$docudom);
4018: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
4019: if ($fetchresult eq 'ok') {
4020: if ($fetchthumb) {
4021: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4022: if ($thumbresult ne 'ok') {
4023: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4024: $docuhome.': '.$thumbresult);
4025: }
4026: }
4027: #
4028: # Return the URL to it
4029: return '/uploaded/'.$path.$file;
4030: } else {
4031: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4032: ': '.$fetchresult);
4033: return '/adm/notfound.html';
4034: }
4035: }
4036:
4037: sub extract_embedded_items {
4038: my ($fullpath,$allfiles,$codebase,$content) = @_;
4039: my @state = ();
4040: my (%lastids,%related,%shockwave,%flashvars);
4041: my %javafiles = (
4042: codebase => '',
4043: code => '',
4044: archive => ''
4045: );
4046: my %mediafiles = (
4047: src => '',
4048: movie => '',
4049: );
4050: my $p;
4051: if ($content) {
4052: $p = HTML::LCParser->new($content);
4053: } else {
4054: $p = HTML::LCParser->new($fullpath);
4055: }
4056: while (my $t=$p->get_token()) {
4057: if ($t->[0] eq 'S') {
4058: my ($tagname, $attr) = ($t->[1],$t->[2]);
4059: push(@state, $tagname);
4060: if (lc($tagname) eq 'allow') {
4061: &add_filetype($allfiles,$attr->{'src'},'src');
4062: }
4063: if (lc($tagname) eq 'img') {
4064: &add_filetype($allfiles,$attr->{'src'},'src');
4065: }
4066: if (lc($tagname) eq 'a') {
4067: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4068: &add_filetype($allfiles,$attr->{'href'},'href');
4069: }
4070: }
4071: if (lc($tagname) eq 'script') {
4072: my $src;
4073: if ($attr->{'archive'} =~ /\.jar$/i) {
4074: &add_filetype($allfiles,$attr->{'archive'},'archive');
4075: } else {
4076: if ($attr->{'src'} ne '') {
4077: $src = $attr->{'src'};
4078: &add_filetype($allfiles,$src,'src');
4079: }
4080: }
4081: my $text = $p->get_trimmed_text();
4082: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4083: my @swfargs = split(/,/,$1);
4084: foreach my $item (@swfargs) {
4085: $item =~ s/["']//g;
4086: $item =~ s/^\s+//;
4087: $item =~ s/\s+$//;
4088: }
4089: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4090: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4091: push(@{$related{$swfargs[0]}},$swfargs[2]);
4092: } else {
4093: $related{$swfargs[0]} = [$swfargs[2]];
4094: }
4095: }
4096: }
4097: }
4098: if (lc($tagname) eq 'link') {
4099: if (lc($attr->{'rel'}) eq 'stylesheet') {
4100: &add_filetype($allfiles,$attr->{'href'},'href');
4101: }
4102: }
4103: if (lc($tagname) eq 'object' ||
4104: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4105: foreach my $item (keys(%javafiles)) {
4106: $javafiles{$item} = '';
4107: }
4108: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4109: $lastids{lc($tagname)} = $attr->{'id'};
4110: }
4111: }
4112: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4113: my $name = lc($attr->{'name'});
4114: foreach my $item (keys(%javafiles)) {
4115: if ($name eq $item) {
4116: $javafiles{$item} = $attr->{'value'};
4117: last;
4118: }
4119: }
4120: my $pathfrom;
4121: foreach my $item (keys(%mediafiles)) {
4122: if ($name eq $item) {
4123: $pathfrom = $attr->{'value'};
4124: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4125: &add_filetype($allfiles,$pathfrom,$name);
4126: last;
4127: }
4128: }
4129: if ($name eq 'flashvars') {
4130: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4131: }
4132: if ($pathfrom ne '') {
4133: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4134: $pathfrom);
4135: }
4136: }
4137: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4138: foreach my $item (keys(%javafiles)) {
4139: if ($attr->{$item}) {
4140: $javafiles{$item} = $attr->{$item};
4141: last;
4142: }
4143: }
4144: foreach my $item (keys(%mediafiles)) {
4145: if ($attr->{$item}) {
4146: &add_filetype($allfiles,$attr->{$item},$item);
4147: last;
4148: }
4149: }
4150: if (lc($tagname) eq 'embed') {
4151: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4152: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4153: $attr->{'src'});
4154: }
4155: }
4156: }
4157: if (lc($tagname) eq 'iframe') {
4158: my $src = $attr->{'src'} ;
4159: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4160: &add_filetype($allfiles,$src,'src');
4161: } elsif ($src =~ m{^/}) {
4162: if ($env{'request.course.id'}) {
4163: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4164: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4165: my $url = &hreflocation('',$fullpath);
4166: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4167: my $relpath = $1;
4168: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4169: &add_filetype($allfiles,$1,'src');
4170: }
4171: }
4172: }
4173: }
4174: }
4175: if ($t->[4] =~ m{/>$}) {
4176: pop(@state);
4177: }
4178: } elsif ($t->[0] eq 'E') {
4179: my ($tagname) = ($t->[1]);
4180: if ($javafiles{'codebase'} ne '') {
4181: $javafiles{'codebase'} .= '/';
4182: }
4183: if (lc($tagname) eq 'applet' ||
4184: lc($tagname) eq 'object' ||
4185: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4186: ) {
4187: foreach my $item (keys(%javafiles)) {
4188: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4189: my $file=$javafiles{'codebase'}.$javafiles{$item};
4190: &add_filetype($allfiles,$file,$item);
4191: }
4192: }
4193: }
4194: pop @state;
4195: }
4196: }
4197: foreach my $id (sort(keys(%flashvars))) {
4198: if ($shockwave{$id} ne '') {
4199: my @pairs = split(/\&/,$flashvars{$id});
4200: foreach my $pair (@pairs) {
4201: my ($key,$value) = split(/\=/,$pair);
4202: if ($key eq 'thumb') {
4203: &add_filetype($allfiles,$value,$key);
4204: } elsif ($key eq 'content') {
4205: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4206: my ($ext) = ($value =~ /\.([^.]+)$/);
4207: if ($ext ne '') {
4208: &add_filetype($allfiles,$path.$value,$ext);
4209: }
4210: }
4211: }
4212: }
4213: }
4214: return 'ok';
4215: }
4216:
4217: sub add_filetype {
4218: my ($allfiles,$file,$type)=@_;
4219: if (exists($allfiles->{$file})) {
4220: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4221: push(@{$allfiles->{$file}}, &escape($type));
4222: }
4223: } else {
4224: @{$allfiles->{$file}} = (&escape($type));
4225: }
4226: }
4227:
4228: sub embedded_dependency {
4229: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4230: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4231: if (($identifier ne '') &&
4232: (ref($related->{$identifier}) eq 'ARRAY') &&
4233: ($pathfrom ne '')) {
4234: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4235: foreach my $dep (@{$related->{$identifier}}) {
4236: &add_filetype($allfiles,$path.$dep,'object');
4237: }
4238: }
4239: }
4240: return;
4241: }
4242:
4243: sub bubblesheet_converter {
4244: my ($cdom,$fullpath,$config,$format) = @_;
4245: if ((&domain($cdom) ne '') &&
4246: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4247: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4248: my (%csvcols,%csvoptions);
4249: if (ref($config->{'fields'}) eq 'HASH') {
4250: %csvcols = %{$config->{'fields'}};
4251: }
4252: if (ref($config->{'options'}) eq 'HASH') {
4253: %csvoptions = %{$config->{'options'}};
4254: }
4255: my %csvbynum = reverse(%csvcols);
4256: my %scantronconf = &get_scantron_config($format,$cdom);
4257: if (keys(%scantronconf)) {
4258: my %bynum = (
4259: $scantronconf{CODEstart} => 'CODEstart',
4260: $scantronconf{IDstart} => 'IDstart',
4261: $scantronconf{PaperID} => 'PaperID',
4262: $scantronconf{FirstName} => 'FirstName',
4263: $scantronconf{LastName} => 'LastName',
4264: $scantronconf{Qstart} => 'Qstart',
4265: );
4266: my @ordered;
4267: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4268: push(@ordered,$bynum{$item});
4269: }
4270: my %mapstart = (
4271: CODEstart => 'CODE',
4272: IDstart => 'ID',
4273: PaperID => 'PaperID',
4274: FirstName => 'FirstName',
4275: LastName => 'LastName',
4276: Qstart => 'FirstQuestion',
4277: );
4278: my %maplength = (
4279: CODEstart => 'CODElength',
4280: IDstart => 'IDlength',
4281: PaperID => 'PaperIDlength',
4282: FirstName => 'FirstNamelength',
4283: LastName => 'LastNamelength',
4284: );
4285: if (open(my $fh,'<',$fullpath)) {
4286: my $output;
4287: my %lettdig = &letter_to_digits();
4288: my %diglett = reverse(%lettdig);
4289: my $numletts = scalar(keys(%lettdig));
4290: my $num = 0;
4291: while (my $line=<$fh>) {
4292: $num ++;
4293: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4294: $line =~ s{[\r\n]+$}{};
4295: my %found;
4296: my @values = split(/,/,$line);
4297: my ($qstart,$record);
4298: for (my $i=0; $i<@values; $i++) {
4299: if ((($qstart ne '') && ($i > $qstart)) ||
4300: ($csvbynum{$i} eq 'FirstQuestion')) {
4301: if ($values[$i] eq '') {
4302: $values[$i] = $scantronconf{'Qoff'};
4303: } elsif ($scantronconf{'Qon'} eq 'number') {
4304: if ($values[$i] =~ /^[A-Ja-j]$/) {
4305: $values[$i] = $lettdig{uc($values[$i])};
4306: }
4307: } elsif ($scantronconf{'Qon'} eq 'letter') {
4308: if ($values[$i] =~ /^[0-9]$/) {
4309: $values[$i] = $diglett{$values[$i]};
4310: }
4311: } else {
4312: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4313: my $digit;
4314: if ($values[$i] =~ /^[A-Ja-j]$/) {
4315: $digit = $lettdig{uc($values[$i])}-1;
4316: if ($values[$i] eq 'J') {
4317: $digit += $numletts;
4318: }
4319: } elsif ($values[$i] =~ /^[0-9]$/) {
4320: $digit = $values[$i]-1;
4321: if ($values[$i] eq '0') {
4322: $digit += $numletts;
4323: }
4324: }
4325: my $qval='';
4326: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4327: if ($j == $digit) {
4328: $qval .= $scantronconf{'Qon'};
4329: } else {
4330: $qval .= $scantronconf{'Qoff'};
4331: }
4332: }
4333: $values[$i] = $qval;
4334: }
4335: }
4336: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4337: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4338: }
4339: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4340: if ($numblank > 0) {
4341: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4342: }
4343: if ($csvbynum{$i} eq 'FirstQuestion') {
4344: $qstart = $i;
4345: $found{$csvbynum{$i}} = $values[$i];
4346: } else {
4347: $found{'FirstQuestion'} .= $values[$i];
4348: }
4349: } elsif (exists($csvbynum{$i})) {
4350: if ($csvoptions{'rem'}) {
4351: $values[$i] =~ s/^\s+//;
4352: }
4353: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4354: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4355: $values[$i] = '0'.$values[$i];
4356: }
4357: }
4358: $found{$csvbynum{$i}} = $values[$i];
4359: }
4360: }
4361: foreach my $item (@ordered) {
4362: my $currlength = 1+length($record);
4363: my $numspaces = $scantronconf{$item} - $currlength;
4364: if ($numspaces > 0) {
4365: $record .= (' ' x $numspaces);
4366: }
4367: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4368: unless ($item eq 'Qstart') {
4369: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4370: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4371: }
4372: }
4373: $record .= $found{$mapstart{$item}};
4374: }
4375: }
4376: $output .= "$record\n";
4377: }
4378: close($fh);
4379: if ($output) {
4380: if (open(my $fh,'>',$fullpath)) {
4381: print $fh $output;
4382: close($fh);
4383: }
4384: }
4385: }
4386: }
4387: return;
4388: }
4389: }
4390:
4391: sub letter_to_digits {
4392: my %lettdig = (
4393: A => 1,
4394: B => 2,
4395: C => 3,
4396: D => 4,
4397: E => 5,
4398: F => 6,
4399: G => 7,
4400: H => 8,
4401: I => 9,
4402: J => 0,
4403: );
4404: return %lettdig;
4405: }
4406:
4407: sub get_scantron_config {
4408: my ($which,$cdom) = @_;
4409: my @lines = &get_scantronformat_file($cdom);
4410: my %config;
4411: #FIXME probably should move to XML it has already gotten a bit much now
4412: foreach my $line (@lines) {
4413: my ($name,$descrip)=split(/:/,$line);
4414: if ($name ne $which ) { next; }
4415: chomp($line);
4416: my @config=split(/:/,$line);
4417: $config{'name'}=$config[0];
4418: $config{'description'}=$config[1];
4419: $config{'CODElocation'}=$config[2];
4420: $config{'CODEstart'}=$config[3];
4421: $config{'CODElength'}=$config[4];
4422: $config{'IDstart'}=$config[5];
4423: $config{'IDlength'}=$config[6];
4424: $config{'Qstart'}=$config[7];
4425: $config{'Qlength'}=$config[8];
4426: $config{'Qoff'}=$config[9];
4427: $config{'Qon'}=$config[10];
4428: $config{'PaperID'}=$config[11];
4429: $config{'PaperIDlength'}=$config[12];
4430: $config{'FirstName'}=$config[13];
4431: $config{'FirstNamelength'}=$config[14];
4432: $config{'LastName'}=$config[15];
4433: $config{'LastNamelength'}=$config[16];
4434: $config{'BubblesPerRow'}=$config[17];
4435: last;
4436: }
4437: return %config;
4438: }
4439:
4440: sub get_scantronformat_file {
4441: my ($cdom) = @_;
4442: if ($cdom eq '') {
4443: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4444: }
4445: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4446: my $gottab = 0;
4447: my @lines;
4448: if (ref($domconfig{'scantron'}) eq 'HASH') {
4449: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4450: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4451: if ($formatfile ne '-1') {
4452: @lines = split("\n",$formatfile,-1);
4453: $gottab = 1;
4454: }
4455: }
4456: }
4457: if (!$gottab) {
4458: my $confname = $cdom.'-domainconfig';
4459: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4460: my $formatfile = &getfile($default);
4461: if ($formatfile ne '-1') {
4462: @lines = split("\n",$formatfile,-1);
4463: $gottab = 1;
4464: }
4465: }
4466: if (!$gottab) {
4467: my @domains = ¤t_machine_domains();
4468: if (grep(/^\Q$cdom\E$/,@domains)) {
4469: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4470: @lines = <$fh>;
4471: close($fh);
4472: }
4473: } else {
4474: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4475: @lines = <$fh>;
4476: close($fh);
4477: }
4478: }
4479: }
4480: return @lines;
4481: }
4482:
4483: sub removeuploadedurl {
4484: my ($url)=@_;
4485: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4486: return &removeuserfile($uname,$udom,$fname);
4487: }
4488:
4489: sub removeuserfile {
4490: my ($docuname,$docudom,$fname)=@_;
4491: my $home=&homeserver($docuname,$docudom);
4492: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4493: if ($result eq 'ok') {
4494: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4495: my $metafile = $fname.'.meta';
4496: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4497: my $url = "/uploaded/$docudom/$docuname/$fname";
4498: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4499: my $sqlresult =
4500: &update_portfolio_table($docuname,$docudom,$file,
4501: 'portfolio_metadata',$group,
4502: 'delete');
4503: }
4504: }
4505: return $result;
4506: }
4507:
4508: sub mkdiruserfile {
4509: my ($docuname,$docudom,$dir)=@_;
4510: my $home=&homeserver($docuname,$docudom);
4511: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4512: }
4513:
4514: sub renameuserfile {
4515: my ($docuname,$docudom,$old,$new)=@_;
4516: my $home=&homeserver($docuname,$docudom);
4517: my $result = &reply("renameuserfile:$docudom:$docuname:".
4518: &escape("$old").':'.&escape("$new"),$home);
4519: if ($result eq 'ok') {
4520: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4521: my $oldmeta = $old.'.meta';
4522: my $newmeta = $new.'.meta';
4523: my $metaresult =
4524: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4525: my $url = "/uploaded/$docudom/$docuname/$old";
4526: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4527: my $sqlresult =
4528: &update_portfolio_table($docuname,$docudom,$file,
4529: 'portfolio_metadata',$group,
4530: 'delete');
4531: }
4532: }
4533: return $result;
4534: }
4535:
4536: # ------------------------------------------------------------------------- Log
4537:
4538: sub log {
4539: my ($dom,$nam,$hom,$what)=@_;
4540: return critical("log:$dom:$nam:$what",$hom);
4541: }
4542:
4543: # ------------------------------------------------------------------ Course Log
4544: #
4545: # This routine flushes several buffers of non-mission-critical nature
4546: #
4547:
4548: sub flushcourselogs {
4549: &logthis('Flushing log buffers');
4550: #
4551: # course logs
4552: # This is a log of all transactions in a course, which can be used
4553: # for data mining purposes
4554: #
4555: # It also collects the courseid database, which lists last transaction
4556: # times and course titles for all courseids
4557: #
4558: my %courseidbuffer=();
4559: foreach my $crsid (keys(%courselogs)) {
4560: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4561: &escape($courselogs{$crsid}),
4562: $coursehombuf{$crsid}) eq 'ok') {
4563: delete $courselogs{$crsid};
4564: } else {
4565: &logthis('Failed to flush log buffer for '.$crsid);
4566: if (length($courselogs{$crsid})>40000) {
4567: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4568: " exceeded maximum size, deleting.</font>");
4569: delete $courselogs{$crsid};
4570: }
4571: }
4572: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4573: 'description' => $coursedescrbuf{$crsid},
4574: 'inst_code' => $courseinstcodebuf{$crsid},
4575: 'type' => $coursetypebuf{$crsid},
4576: 'owner' => $courseownerbuf{$crsid},
4577: };
4578: }
4579: #
4580: # Write course id database (reverse lookup) to homeserver of courses
4581: # Is used in pickcourse
4582: #
4583: foreach my $crs_home (keys(%courseidbuffer)) {
4584: my $response = &courseidput(&host_domain($crs_home),
4585: $courseidbuffer{$crs_home},
4586: $crs_home,'timeonly');
4587: }
4588: #
4589: # File accesses
4590: # Writes to the dynamic metadata of resources to get hit counts, etc.
4591: #
4592: foreach my $entry (keys(%accesshash)) {
4593: if ($entry =~ /___count$/) {
4594: my ($dom,$name);
4595: ($dom,$name,undef)=
4596: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4597: if (! defined($dom) || $dom eq '' ||
4598: ! defined($name) || $name eq '') {
4599: my $cid = $env{'request.course.id'};
4600: $dom = $env{'request.'.$cid.'.domain'};
4601: $name = $env{'request.'.$cid.'.num'};
4602: }
4603: my $value = $accesshash{$entry};
4604: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4605: my %temphash=($url => $value);
4606: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4607: if ($result eq 'ok') {
4608: delete $accesshash{$entry};
4609: }
4610: } else {
4611: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4612: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4613: my %temphash=($entry => $accesshash{$entry});
4614: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4615: delete $accesshash{$entry};
4616: }
4617: }
4618: }
4619: #
4620: # Roles
4621: # Reverse lookup of user roles for course faculty/staff and co-authorship
4622: #
4623: foreach my $entry (keys(%userrolehash)) {
4624: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4625: split(/\:/,$entry);
4626: if (&Apache::lonnet::put('nohist_userroles',
4627: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4628: $rudom,$runame) eq 'ok') {
4629: delete $userrolehash{$entry};
4630: }
4631: }
4632: #
4633: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4634: #
4635: my %domrolebuffer = ();
4636: foreach my $entry (keys(%domainrolehash)) {
4637: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4638: if ($domrolebuffer{$rudom}) {
4639: $domrolebuffer{$rudom}.='&'.&escape($entry).
4640: '='.&escape($domainrolehash{$entry});
4641: } else {
4642: $domrolebuffer{$rudom}.=&escape($entry).
4643: '='.&escape($domainrolehash{$entry});
4644: }
4645: delete $domainrolehash{$entry};
4646: }
4647: foreach my $dom (keys(%domrolebuffer)) {
4648: my %servers;
4649: if (defined(&domain($dom,'primary'))) {
4650: my $primary=&domain($dom,'primary');
4651: my $hostname=&hostname($primary);
4652: $servers{$primary} = $hostname;
4653: } else {
4654: %servers = &get_servers($dom,'library');
4655: }
4656: foreach my $tryserver (keys(%servers)) {
4657: if (&reply('domroleput:'.$dom.':'.
4658: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4659: last;
4660: } else {
4661: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4662: }
4663: }
4664: }
4665: $dumpcount++;
4666: }
4667:
4668: sub courselog {
4669: my $what=shift;
4670: $what=time.':'.$what;
4671: unless ($env{'request.course.id'}) { return ''; }
4672: $coursedombuf{$env{'request.course.id'}}=
4673: $env{'course.'.$env{'request.course.id'}.'.domain'};
4674: $coursenumbuf{$env{'request.course.id'}}=
4675: $env{'course.'.$env{'request.course.id'}.'.num'};
4676: $coursehombuf{$env{'request.course.id'}}=
4677: $env{'course.'.$env{'request.course.id'}.'.home'};
4678: $coursedescrbuf{$env{'request.course.id'}}=
4679: $env{'course.'.$env{'request.course.id'}.'.description'};
4680: $courseinstcodebuf{$env{'request.course.id'}}=
4681: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4682: $courseownerbuf{$env{'request.course.id'}}=
4683: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
4684: $coursetypebuf{$env{'request.course.id'}}=
4685: $env{'course.'.$env{'request.course.id'}.'.type'};
4686: if (defined $courselogs{$env{'request.course.id'}}) {
4687: $courselogs{$env{'request.course.id'}}.='&'.$what;
4688: } else {
4689: $courselogs{$env{'request.course.id'}}.=$what;
4690: }
4691: if (length($courselogs{$env{'request.course.id'}})>4048) {
4692: &flushcourselogs();
4693: }
4694: }
4695:
4696: sub courseacclog {
4697: my $fnsymb=shift;
4698: unless ($env{'request.course.id'}) { return ''; }
4699: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
4700: if ($fnsymb=~/$LONCAPA::assess_re/) {
4701: $what.=':POST';
4702: # FIXME: Probably ought to escape things....
4703: foreach my $key (keys(%env)) {
4704: if ($key=~/^form\.(.*)/) {
4705: my $formitem = $1;
4706: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4707: $what.=':'.$formitem.'='.$env{$key};
4708: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4709: if ($formitem eq 'proctorpassword') {
4710: $what.=':'.$formitem.'=' . '*' x length($env{$key});
4711: } else {
4712: $what.=':'.$formitem.'='.$env{$key};
4713: }
4714: }
4715: }
4716: }
4717: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4718: # FIXME: We should not be depending on a form parameter that someone
4719: # editing lonsearchcat.pm might change in the future.
4720: if ($env{'form.phase'} eq 'course_search') {
4721: $what.= ':POST';
4722: # FIXME: Probably ought to escape things....
4723: foreach my $element ('courseexp','crsfulltext','crsrelated',
4724: 'crsdiscuss') {
4725: $what.=':'.$element.'='.$env{'form.'.$element};
4726: }
4727: }
4728: }
4729: &courselog($what);
4730: }
4731:
4732: sub countacc {
4733: my $url=&declutter(shift);
4734: return if (! defined($url) || $url eq '');
4735: unless ($env{'request.course.id'}) { return ''; }
4736: #
4737: # Mark that this url was used in this course
4738: #
4739: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
4740: #
4741: # Increase the access count for this resource in this child process
4742: #
4743: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
4744: $accesshash{$key}++;
4745: }
4746:
4747: sub linklog {
4748: my ($from,$to)=@_;
4749: $from=&declutter($from);
4750: $to=&declutter($to);
4751: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4752: $accesshash{$to.'___'.$from.'___goto'}=1;
4753: }
4754:
4755: sub statslog {
4756: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4757: if ($users<2) { return; }
4758: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4759: 'course' => $env{'request.course.id'},
4760: 'sections' => '"all"',
4761: 'num_students' => $users,
4762: 'part' => $part,
4763: 'symb' => $symb,
4764: 'mean_tries' => $av_attempts,
4765: 'deg_of_diff' => $degdiff});
4766: foreach my $key (keys(%dynstore)) {
4767: $accesshash{$key}=$dynstore{$key};
4768: }
4769: }
4770:
4771: sub userrolelog {
4772: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
4773: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
4774: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4775: $userrolehash
4776: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4777: =$tend.':'.$tstart;
4778: }
4779: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
4780: $userrolehash
4781: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4782: =$tend.':'.$tstart;
4783: }
4784: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
4785: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4786: $domainrolehash
4787: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4788: = $tend.':'.$tstart;
4789: }
4790: }
4791:
4792: sub courserolelog {
4793: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
4794: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4795: my $cdom = $1;
4796: my $cnum = $2;
4797: my $sec = $3;
4798: my $namespace = 'rolelog';
4799: my %storehash = (
4800: role => $trole,
4801: start => $tstart,
4802: end => $tend,
4803: selfenroll => $selfenroll,
4804: context => $context,
4805: );
4806: if ($trole eq 'gr') {
4807: $namespace = 'groupslog';
4808: $storehash{'group'} = $sec;
4809: } else {
4810: $storehash{'section'} = $sec;
4811: }
4812: &write_log('course',$namespace,\%storehash,$delflag,$username,
4813: $domain,$cnum,$cdom);
4814: if (($trole ne 'st') || ($sec ne '')) {
4815: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
4816: }
4817: }
4818: return;
4819: }
4820:
4821: sub domainrolelog {
4822: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4823: if ($area =~ m{^/($match_domain)/$}) {
4824: my $cdom = $1;
4825: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4826: my $namespace = 'rolelog';
4827: my %storehash = (
4828: role => $trole,
4829: start => $tstart,
4830: end => $tend,
4831: context => $context,
4832: );
4833: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4834: $domain,$domconfiguser,$cdom);
4835: }
4836: return;
4837:
4838: }
4839:
4840: sub coauthorrolelog {
4841: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4842: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4843: my $audom = $1;
4844: my $auname = $2;
4845: my $namespace = 'rolelog';
4846: my %storehash = (
4847: role => $trole,
4848: start => $tstart,
4849: end => $tend,
4850: context => $context,
4851: );
4852: &write_log('author',$namespace,\%storehash,$delflag,$username,
4853: $domain,$auname,$audom);
4854: }
4855: return;
4856: }
4857:
4858: sub get_course_adv_roles {
4859: my ($cid,$codes) = @_;
4860: $cid=$env{'request.course.id'} unless (defined($cid));
4861: my %coursehash=&coursedescription($cid);
4862: my $crstype = &Apache::loncommon::course_type($cid);
4863: my %nothide=();
4864: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4865: if ($user !~ /:/) {
4866: $nothide{join(':',split(/[\@]/,$user))}=1;
4867: } else {
4868: $nothide{$user}=1;
4869: }
4870: }
4871: my @possdoms = ($coursehash{'domain'});
4872: if ($coursehash{'checkforpriv'}) {
4873: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4874: }
4875: my %returnhash=();
4876: my %dumphash=
4877: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4878: my $now=time;
4879: my %privileged;
4880: foreach my $entry (keys(%dumphash)) {
4881: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4882: if (($tstart) && ($tstart<0)) { next; }
4883: if (($tend) && ($tend<$now)) { next; }
4884: if (($tstart) && ($now<$tstart)) { next; }
4885: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4886: if ($username eq '' || $domain eq '') { next; }
4887: if ((&privileged($username,$domain,\@possdoms)) &&
4888: (!$nothide{$username.':'.$domain})) { next; }
4889: if ($role eq 'cr') { next; }
4890: if ($codes) {
4891: if ($section) { $role .= ':'.$section; }
4892: if ($returnhash{$role}) {
4893: $returnhash{$role}.=','.$username.':'.$domain;
4894: } else {
4895: $returnhash{$role}=$username.':'.$domain;
4896: }
4897: } else {
4898: my $key=&plaintext($role,$crstype);
4899: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4900: if ($returnhash{$key}) {
4901: $returnhash{$key}.=','.$username.':'.$domain;
4902: } else {
4903: $returnhash{$key}=$username.':'.$domain;
4904: }
4905: }
4906: }
4907: return %returnhash;
4908: }
4909:
4910: sub get_my_roles {
4911: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4912: unless (defined($uname)) { $uname=$env{'user.name'}; }
4913: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4914: my (%dumphash,%nothide);
4915: if ($context eq 'userroles') {
4916: %dumphash = &dump('roles',$udom,$uname);
4917: } else {
4918: %dumphash = &dump('nohist_userroles',$udom,$uname);
4919: if ($hidepriv) {
4920: my %coursehash=&coursedescription($udom.'_'.$uname);
4921: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4922: if ($user !~ /:/) {
4923: $nothide{join(':',split(/[\@]/,$user))} = 1;
4924: } else {
4925: $nothide{$user} = 1;
4926: }
4927: }
4928: }
4929: }
4930: my %returnhash=();
4931: my $now=time;
4932: my %privileged;
4933: foreach my $entry (keys(%dumphash)) {
4934: my ($role,$tend,$tstart);
4935: if ($context eq 'userroles') {
4936: next if ($entry =~ /^rolesdef/);
4937: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4938: } else {
4939: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4940: }
4941: if (($tstart) && ($tstart<0)) { next; }
4942: my $status = 'active';
4943: if (($tend) && ($tend<=$now)) {
4944: $status = 'previous';
4945: }
4946: if (($tstart) && ($now<$tstart)) {
4947: $status = 'future';
4948: }
4949: if (ref($types) eq 'ARRAY') {
4950: if (!grep(/^\Q$status\E$/,@{$types})) {
4951: next;
4952: }
4953: } else {
4954: if ($status ne 'active') {
4955: next;
4956: }
4957: }
4958: my ($rolecode,$username,$domain,$section,$area);
4959: if ($context eq 'userroles') {
4960: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4961: (undef,$domain,$username,$section) = split(/\//,$area);
4962: } else {
4963: ($role,$username,$domain,$section) = split(/\:/,$entry);
4964: }
4965: if (ref($roledoms) eq 'ARRAY') {
4966: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4967: next;
4968: }
4969: }
4970: if (ref($roles) eq 'ARRAY') {
4971: if (!grep(/^\Q$role\E$/,@{$roles})) {
4972: if ($role =~ /^cr\//) {
4973: if (!grep(/^cr$/,@{$roles})) {
4974: next;
4975: }
4976: } elsif ($role =~ /^gr\//) {
4977: if (!grep(/^gr$/,@{$roles})) {
4978: next;
4979: }
4980: } else {
4981: next;
4982: }
4983: }
4984: }
4985: if ($hidepriv) {
4986: my @privroles = ('dc','su');
4987: if ($context eq 'userroles') {
4988: next if (grep(/^\Q$role\E$/,@privroles));
4989: } else {
4990: my $possdoms = [$domain];
4991: if (ref($roledoms) eq 'ARRAY') {
4992: push(@{$possdoms},@{$roledoms});
4993: }
4994: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4995: if (!$nothide{$username.':'.$domain}) {
4996: next;
4997: }
4998: }
4999: }
5000: }
5001: if ($withsec) {
5002: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5003: $tstart.':'.$tend;
5004: } else {
5005: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5006: }
5007: }
5008: return %returnhash;
5009: }
5010:
5011: sub get_all_adhocroles {
5012: my ($dom) = @_;
5013: my @roles_by_num = ();
5014: my %domdefaults = &get_domain_defaults($dom);
5015: my (%description,%access_in_dom,%access_info);
5016: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5017: my $count = 0;
5018: my %domcurrent = %{$domdefaults{'adhocroles'}};
5019: my %ordered;
5020: foreach my $role (sort(keys(%domcurrent))) {
5021: my ($order,$desc,$access_in_dom);
5022: if (ref($domcurrent{$role}) eq 'HASH') {
5023: $order = $domcurrent{$role}{'order'};
5024: $desc = $domcurrent{$role}{'desc'};
5025: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5026: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5027: }
5028: if ($order eq '') {
5029: $order = $count;
5030: }
5031: $ordered{$order} = $role;
5032: if ($desc ne '') {
5033: $description{$role} = $desc;
5034: } else {
5035: $description{$role}= $role;
5036: }
5037: $count++;
5038: }
5039: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5040: push(@roles_by_num,$ordered{$item});
5041: }
5042: }
5043: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5044: }
5045:
5046: sub get_my_adhocroles {
5047: my ($cid,$checkreg) = @_;
5048: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5049: if ($env{'request.course.id'} eq $cid) {
5050: $cdom = $env{'course.'.$cid.'.domain'};
5051: $cnum = $env{'course.'.$cid.'.num'};
5052: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5053: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5054: $cdom = $1;
5055: $cnum = $2;
5056: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5057: $cdom,$cnum);
5058: }
5059: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5060: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5061: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5062: if ($rosterhash{$user} ne '') {
5063: my $type = (split(/:/,$rosterhash{$user}))[5];
5064: return ([],{}) if ($type eq 'auto');
5065: }
5066: }
5067: if (($cdom ne '') && ($cnum ne '')) {
5068: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
5069: my $then=$env{'user.login.time'};
5070: my $update=$env{'user.update.time'};
5071: if (!$update) {
5072: $update = $then;
5073: }
5074: my @liveroles;
5075: foreach my $role ('dh','da') {
5076: if ($env{"user.role.$role./$cdom/"}) {
5077: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5078: my $limit = $update;
5079: if ($env{'request.role'} eq "$role./$cdom/") {
5080: $limit = $then;
5081: }
5082: my $activerole = 1;
5083: if ($tstart && $tstart>$limit) { $activerole = 0; }
5084: if ($tend && $tend <$limit) { $activerole = 0; }
5085: if ($activerole) {
5086: push(@liveroles,$role);
5087: }
5088: }
5089: }
5090: if (@liveroles) {
5091: if (&homeserver($cnum,$cdom) ne 'no_host') {
5092: my ($accessref,$accessinfo,%access_in_dom);
5093: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5094: if (ref($roles_by_num) eq 'ARRAY') {
5095: if (@{$roles_by_num}) {
5096: my %settings;
5097: if ($env{'request.course.id'} eq $cid) {
5098: foreach my $envkey (keys(%env)) {
5099: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5100: $settings{$1} = $env{$envkey};
5101: }
5102: }
5103: } else {
5104: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5105: }
5106: my %setincrs;
5107: if ($settings{'internal.adhocaccess'}) {
5108: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5109: }
5110: my @statuses;
5111: if ($env{'environment.inststatus'}) {
5112: @statuses = split(/,/,$env{'environment.inststatus'});
5113: }
5114: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5115: if (ref($accessref) eq 'HASH') {
5116: %access_in_dom = %{$accessref};
5117: }
5118: foreach my $role (@{$roles_by_num}) {
5119: my ($curraccess,@okstatus,@personnel);
5120: if ($setincrs{$role}) {
5121: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5122: if ($curraccess eq 'status') {
5123: @okstatus = split(/\&/,$rest);
5124: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5125: @personnel = split(/\&/,$rest);
5126: }
5127: } else {
5128: $curraccess = $access_in_dom{$role};
5129: if (ref($accessinfo) eq 'HASH') {
5130: if ($curraccess eq 'status') {
5131: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5132: @okstatus = @{$accessinfo->{$role}};
5133: }
5134: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5135: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5136: @personnel = @{$accessinfo->{$role}};
5137: }
5138: }
5139: }
5140: }
5141: if ($curraccess eq 'none') {
5142: next;
5143: } elsif ($curraccess eq 'all') {
5144: push(@possroles,$role);
5145: } elsif ($curraccess eq 'dh') {
5146: if (grep(/^dh$/,@liveroles)) {
5147: push(@possroles,$role);
5148: } else {
5149: next;
5150: }
5151: } elsif ($curraccess eq 'da') {
5152: if (grep(/^da$/,@liveroles)) {
5153: push(@possroles,$role);
5154: } else {
5155: next;
5156: }
5157: } elsif ($curraccess eq 'status') {
5158: if (@okstatus) {
5159: if (!@statuses) {
5160: if (grep(/^default$/,@okstatus)) {
5161: push(@possroles,$role);
5162: }
5163: } else {
5164: foreach my $status (@okstatus) {
5165: if (grep(/^\Q$status\E$/,@statuses)) {
5166: push(@possroles,$role);
5167: last;
5168: }
5169: }
5170: }
5171: }
5172: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5173: if (grep(/^\Q$user\E$/,@personnel)) {
5174: if ($curraccess eq 'exc') {
5175: push(@possroles,$role);
5176: }
5177: } elsif ($curraccess eq 'inc') {
5178: push(@possroles,$role);
5179: }
5180: }
5181: }
5182: }
5183: }
5184: }
5185: }
5186: }
5187: }
5188: unless (ref($description) eq 'HASH') {
5189: if (ref($roles_by_num) eq 'ARRAY') {
5190: my %desc;
5191: map { $desc{$_} = $_; } (@{$roles_by_num});
5192: $description = \%desc;
5193: } else {
5194: $description = {};
5195: }
5196: }
5197: return (\@possroles,$description);
5198: }
5199:
5200: # ----------------------------------------------------- Frontpage Announcements
5201: #
5202: #
5203:
5204: sub postannounce {
5205: my ($server,$text)=@_;
5206: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
5207: unless ($text=~/\w/) { $text=''; }
5208: return &reply('setannounce:'.&escape($text),$server);
5209: }
5210:
5211: sub getannounce {
5212:
5213: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
5214: my $announcement='';
5215: while (my $line = <$fh>) { $announcement .= $line; }
5216: close($fh);
5217: if ($announcement=~/\w/) {
5218: return
5219: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
5220: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
5221: } else {
5222: return '';
5223: }
5224: } else {
5225: return '';
5226: }
5227: }
5228:
5229: # ---------------------------------------------------------- Course ID routines
5230: # Deal with domain's nohist_courseid.db files
5231: #
5232:
5233: sub courseidput {
5234: my ($domain,$storehash,$coursehome,$caller) = @_;
5235: return unless (ref($storehash) eq 'HASH');
5236: my $outcome;
5237: if ($caller eq 'timeonly') {
5238: my $cids = '';
5239: foreach my $item (keys(%$storehash)) {
5240: $cids.=&escape($item).'&';
5241: }
5242: $cids=~s/\&$//;
5243: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5244: $coursehome);
5245: } else {
5246: my $items = '';
5247: foreach my $item (keys(%$storehash)) {
5248: $items.= &escape($item).'='.
5249: &freeze_escape($$storehash{$item}).'&';
5250: }
5251: $items=~s/\&$//;
5252: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5253: $coursehome);
5254: }
5255: if ($outcome eq 'unknown_cmd') {
5256: my $what;
5257: foreach my $cid (keys(%$storehash)) {
5258: $what .= &escape($cid).'=';
5259: foreach my $item ('description','inst_code','owner','type') {
5260: $what .= &escape($storehash->{$cid}{$item}).':';
5261: }
5262: $what =~ s/\:$/&/;
5263: }
5264: $what =~ s/\&$//;
5265: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5266: } else {
5267: return $outcome;
5268: }
5269: }
5270:
5271: sub courseiddump {
5272: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
5273: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
5274: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
5275: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
5276: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
5277: my $as_hash = 1;
5278: my %returnhash;
5279: if (!$domfilter) { $domfilter=''; }
5280: my %libserv = &all_library();
5281: foreach my $tryserver (keys(%libserv)) {
5282: if ( ( $hostidflag == 1
5283: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5284: || (!defined($hostidflag)) ) {
5285:
5286: if (($domfilter eq '') ||
5287: (&host_domain($tryserver) eq $domfilter)) {
5288: my $rep;
5289: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5290: $rep = &LONCAPA::Lond::dump_course_id_handler(
5291: join(":", (&host_domain($tryserver), $sincefilter,
5292: &escape($descfilter), &escape($instcodefilter),
5293: &escape($ownerfilter), &escape($coursefilter),
5294: &escape($typefilter), &escape($regexp_ok),
5295: $as_hash, &escape($selfenrollonly),
5296: &escape($catfilter), $showhidden, $caller,
5297: &escape($cloner), &escape($cc_clone), $cloneonly,
5298: &escape($createdbefore), &escape($createdafter),
5299: &escape($creationcontext),$domcloner,$hasuniquecode,
5300: $reqcrsdom,&escape($reqinstcode))));
5301: } else {
5302: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5303: $sincefilter.':'.&escape($descfilter).':'.
5304: &escape($instcodefilter).':'.&escape($ownerfilter).
5305: ':'.&escape($coursefilter).':'.&escape($typefilter).
5306: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5307: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5308: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5309: &escape($cc_clone).':'.$cloneonly.':'.
5310: &escape($createdbefore).':'.&escape($createdafter).':'.
5311: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5312: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5313: }
5314:
5315: my @pairs=split(/\&/,$rep);
5316: foreach my $item (@pairs) {
5317: my ($key,$value)=split(/\=/,$item,2);
5318: $key = &unescape($key);
5319: next if ($key =~ /^error: 2 /);
5320: my $result = &thaw_unescape($value);
5321: if (ref($result) eq 'HASH') {
5322: $returnhash{$key}=$result;
5323: } else {
5324: my @responses = split(/:/,$value);
5325: my @items = ('description','inst_code','owner','type');
5326: for (my $i=0; $i<@responses; $i++) {
5327: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5328: }
5329: }
5330: }
5331: }
5332: }
5333: }
5334: return %returnhash;
5335: }
5336:
5337: sub courselastaccess {
5338: my ($cdom,$cnum,$hostidref) = @_;
5339: my %returnhash;
5340: if ($cdom && $cnum) {
5341: my $chome = &homeserver($cnum,$cdom);
5342: if ($chome ne 'no_host') {
5343: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5344: &extract_lastaccess(\%returnhash,$rep);
5345: }
5346: } else {
5347: if (!$cdom) { $cdom=''; }
5348: my %libserv = &all_library();
5349: foreach my $tryserver (keys(%libserv)) {
5350: if (ref($hostidref) eq 'ARRAY') {
5351: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5352: }
5353: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5354: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5355: &extract_lastaccess(\%returnhash,$rep);
5356: }
5357: }
5358: }
5359: return %returnhash;
5360: }
5361:
5362: sub extract_lastaccess {
5363: my ($returnhash,$rep) = @_;
5364: if (ref($returnhash) eq 'HASH') {
5365: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5366: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5367: $rep eq '') {
5368: my @pairs=split(/\&/,$rep);
5369: foreach my $item (@pairs) {
5370: my ($key,$value)=split(/\=/,$item,2);
5371: $key = &unescape($key);
5372: next if ($key =~ /^error: 2 /);
5373: $returnhash->{$key} = &thaw_unescape($value);
5374: }
5375: }
5376: }
5377: return;
5378: }
5379:
5380: # ---------------------------------------------------------- DC e-mail
5381:
5382: sub dcmailput {
5383: my ($domain,$msgid,$message,$server)=@_;
5384: my $status = &Apache::lonnet::critical(
5385: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5386: &escape($message),$server);
5387: return $status;
5388: }
5389:
5390: sub dcmaildump {
5391: my ($dom,$startdate,$enddate,$senders) = @_;
5392: my %returnhash=();
5393:
5394: if (defined(&domain($dom,'primary'))) {
5395: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5396: &escape($enddate).':';
5397: my @esc_senders=map { &escape($_)} @$senders;
5398: $cmd.=&escape(join('&',@esc_senders));
5399: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5400: my ($key,$value) = split(/\=/,$line,2);
5401: if (($key) && ($value)) {
5402: $returnhash{&unescape($key)} = &unescape($value);
5403: }
5404: }
5405: }
5406: return %returnhash;
5407: }
5408: # ---------------------------------------------------------- Domain roles
5409:
5410: sub get_domain_roles {
5411: my ($dom,$roles,$startdate,$enddate)=@_;
5412: if ((!defined($startdate)) || ($startdate eq '')) {
5413: $startdate = '.';
5414: }
5415: if ((!defined($enddate)) || ($enddate eq '')) {
5416: $enddate = '.';
5417: }
5418: my $rolelist;
5419: if (ref($roles) eq 'ARRAY') {
5420: $rolelist = join('&',@{$roles});
5421: }
5422: my %personnel = ();
5423:
5424: my %servers = &get_servers($dom,'library');
5425: foreach my $tryserver (keys(%servers)) {
5426: %{$personnel{$tryserver}}=();
5427: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5428: &escape($startdate).':'.
5429: &escape($enddate).':'.
5430: &escape($rolelist), $tryserver))) {
5431: my ($key,$value) = split(/\=/,$line,2);
5432: if (($key) && ($value)) {
5433: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5434: }
5435: }
5436: }
5437: return %personnel;
5438: }
5439:
5440: sub get_active_domroles {
5441: my ($dom,$roles) = @_;
5442: return () unless (ref($roles) eq 'ARRAY');
5443: my $now = time;
5444: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5445: my %domroles;
5446: foreach my $server (keys(%dompersonnel)) {
5447: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5448: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5449: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5450: }
5451: }
5452: return %domroles;
5453: }
5454:
5455: # ----------------------------------------------------------- Interval timing
5456:
5457: {
5458: # Caches needed for speedup of navmaps
5459: # We don't want to cache this for very long at all (5 seconds at most)
5460: #
5461: # The user for whom we cache
5462: my $cachedkey='';
5463: # The cached times for this user
5464: my %cachedtimes=();
5465: # When this was last done
5466: my $cachedtime='';
5467:
5468: sub load_all_first_access {
5469: my ($uname,$udom)=@_;
5470: if (($cachedkey eq $uname.':'.$udom) &&
5471: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
5472: return;
5473: }
5474: $cachedtime=time;
5475: $cachedkey=$uname.':'.$udom;
5476: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5477: }
5478:
5479: sub get_first_access {
5480: my ($type,$argsymb,$argmap)=@_;
5481: my ($symb,$courseid,$udom,$uname)=&whichuser();
5482: if ($argsymb) { $symb=$argsymb; }
5483: my ($map,$id,$res)=&decode_symb($symb);
5484: if ($argmap) { $map = $argmap; }
5485: if ($type eq 'course') {
5486: $res='course';
5487: } elsif ($type eq 'map') {
5488: $res=&symbread($map);
5489: } else {
5490: $res=$symb;
5491: }
5492: &load_all_first_access($uname,$udom);
5493: return $cachedtimes{"$courseid\0$res"};
5494: }
5495:
5496: sub set_first_access {
5497: my ($type,$interval)=@_;
5498: my ($symb,$courseid,$udom,$uname)=&whichuser();
5499: my ($map,$id,$res)=&decode_symb($symb);
5500: if ($type eq 'course') {
5501: $res='course';
5502: } elsif ($type eq 'map') {
5503: $res=&symbread($map);
5504: } else {
5505: $res=$symb;
5506: }
5507: $cachedkey='';
5508: my $firstaccess=&get_first_access($type,$symb,$map);
5509: if ($firstaccess) {
5510: &logthis("First access time already set ($firstaccess) when attempting ".
5511: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5512: "in $courseid");
5513: return 'already_set';
5514: } else {
5515: my $start = time;
5516: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5517: $udom,$uname);
5518: if ($putres eq 'ok') {
5519: &put('timerinterval',{"$courseid\0$res"=>$interval},
5520: $udom,$uname);
5521: &appenv(
5522: {
5523: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5524: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5525: }
5526: );
5527: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5528: $cachedtimes{"$courseid\0$res"} = $start;
5529: }
5530: } elsif ($putres ne 'refused') {
5531: &logthis("Result: $putres when attempting to set first access time ".
5532: "(type: $type, extent: $res) for $uname:$udom in $courseid");
5533: }
5534: return $putres;
5535: }
5536: return 'already_set';
5537: }
5538: }
5539:
5540: sub checkout {
5541: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5542: my $now=time;
5543: my $lonhost=$perlvar{'lonHostID'};
5544: my $ip = &get_requestor_ip();
5545: my $infostr=&escape(
5546: 'CHECKOUTTOKEN&'.
5547: $tuname.'&'.
5548: $tudom.'&'.
5549: $tcrsid.'&'.
5550: $symb.'&'.
5551: $now.'&'.$ip);
5552: my $token=&reply('tmpput:'.$infostr,$lonhost);
5553: if ($token=~/^error\:/) {
5554: &logthis("<font color=\"blue\">WARNING: ".
5555: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5556: "</font>");
5557: return '';
5558: }
5559:
5560: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5561: $token=~tr/a-z/A-Z/;
5562:
5563: my %infohash=('resource.0.outtoken' => $token,
5564: 'resource.0.checkouttime' => $now,
5565: 'resource.0.outremote' => $ip);
5566:
5567: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5568: return '';
5569: } else {
5570: &logthis("<font color=\"blue\">WARNING: ".
5571: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5572: "</font>");
5573: }
5574:
5575: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5576: &escape('Checkout '.$infostr.' - '.
5577: $token)) ne 'ok') {
5578: return '';
5579: } else {
5580: &logthis("<font color=\"blue\">WARNING: ".
5581: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5582: "</font>");
5583: }
5584: return $token;
5585: }
5586:
5587: # ------------------------------------------------------------ Check in an item
5588:
5589: sub checkin {
5590: my $token=shift;
5591: my $now=time;
5592: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5593: $lonhost=~tr/A-Z/a-z/;
5594: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5595: $dtoken=~s/\W/\_/g;
5596: my $ip = &get_requestor_ip();
5597: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5598: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5599:
5600: unless (($tuname) && ($tudom)) {
5601: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5602: return '';
5603: }
5604:
5605: unless (&allowed('mgr',$tcrsid)) {
5606: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5607: $env{'user.name'}.' - '.$env{'user.domain'});
5608: return '';
5609: }
5610:
5611: my %infohash=('resource.0.intoken' => $token,
5612: 'resource.0.checkintime' => $now,
5613: 'resource.0.inremote' => $ip);
5614:
5615: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5616: return '';
5617: }
5618:
5619: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5620: &escape('Checkin - '.$token)) ne 'ok') {
5621: return '';
5622: }
5623:
5624: return ($symb,$tuname,$tudom,$tcrsid);
5625: }
5626:
5627: # --------------------------------------------- Set Expire Date for Spreadsheet
5628:
5629: sub expirespread {
5630: my ($uname,$udom,$stype,$usymb)=@_;
5631: my $cid=$env{'request.course.id'};
5632: if ($cid) {
5633: my $now=time;
5634: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5635: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5636: $env{'course.'.$cid.'.num'}.
5637: ':nohist_expirationdates:'.
5638: &escape($key).'='.$now,
5639: $env{'course.'.$cid.'.home'})
5640: }
5641: return 'ok';
5642: }
5643:
5644: # ----------------------------------------------------- Devalidate Spreadsheets
5645:
5646: sub devalidate {
5647: my ($symb,$uname,$udom)=@_;
5648: my $cid=$env{'request.course.id'};
5649: if ($cid) {
5650: # delete the stored spreadsheets for
5651: # - the student level sheet of this user in course's homespace
5652: # - the assessment level sheet for this resource
5653: # for this user in user's homespace
5654: # - current conditional state info
5655: my $key=$uname.':'.$udom.':';
5656: my $status=
5657: &del('nohist_calculatedsheets',
5658: [$key.'studentcalc:'],
5659: $env{'course.'.$cid.'.domain'},
5660: $env{'course.'.$cid.'.num'})
5661: .' '.
5662: &del('nohist_calculatedsheets_'.$cid,
5663: [$key.'assesscalc:'.$symb],$udom,$uname);
5664: unless ($status eq 'ok ok') {
5665: &logthis('Could not devalidate spreadsheet '.
5666: $uname.' at '.$udom.' for '.
5667: $symb.': '.$status);
5668: }
5669: &delenv('user.state.'.$cid);
5670: }
5671: }
5672:
5673: sub get_scalar {
5674: my ($string,$end) = @_;
5675: my $value;
5676: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5677: $value = $1;
5678: } elsif ($$string =~ s/^([^&]*?)&//) {
5679: $value = $1;
5680: }
5681: return &unescape($value);
5682: }
5683:
5684: sub array2str {
5685: my (@array) = @_;
5686: my $result=&arrayref2str(\@array);
5687: $result=~s/^__ARRAY_REF__//;
5688: $result=~s/__END_ARRAY_REF__$//;
5689: return $result;
5690: }
5691:
5692: sub arrayref2str {
5693: my ($arrayref) = @_;
5694: my $result='__ARRAY_REF__';
5695: foreach my $elem (@$arrayref) {
5696: if(ref($elem) eq 'ARRAY') {
5697: $result.=&arrayref2str($elem).'&';
5698: } elsif(ref($elem) eq 'HASH') {
5699: $result.=&hashref2str($elem).'&';
5700: } elsif(ref($elem)) {
5701: #print("Got a ref of ".(ref($elem))." skipping.");
5702: } else {
5703: $result.=&escape($elem).'&';
5704: }
5705: }
5706: $result=~s/\&$//;
5707: $result .= '__END_ARRAY_REF__';
5708: return $result;
5709: }
5710:
5711: sub hash2str {
5712: my (%hash) = @_;
5713: my $result=&hashref2str(\%hash);
5714: $result=~s/^__HASH_REF__//;
5715: $result=~s/__END_HASH_REF__$//;
5716: return $result;
5717: }
5718:
5719: sub hashref2str {
5720: my ($hashref)=@_;
5721: my $result='__HASH_REF__';
5722: foreach my $key (sort(keys(%$hashref))) {
5723: if (ref($key) eq 'ARRAY') {
5724: $result.=&arrayref2str($key).'=';
5725: } elsif (ref($key) eq 'HASH') {
5726: $result.=&hashref2str($key).'=';
5727: } elsif (ref($key)) {
5728: $result.='=';
5729: #print("Got a ref of ".(ref($key))." skipping.");
5730: } else {
5731: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5732: }
5733:
5734: if(ref($hashref->{$key}) eq 'ARRAY') {
5735: $result.=&arrayref2str($hashref->{$key}).'&';
5736: } elsif(ref($hashref->{$key}) eq 'HASH') {
5737: $result.=&hashref2str($hashref->{$key}).'&';
5738: } elsif(ref($hashref->{$key})) {
5739: $result.='&';
5740: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5741: } else {
5742: $result.=&escape($hashref->{$key}).'&';
5743: }
5744: }
5745: $result=~s/\&$//;
5746: $result .= '__END_HASH_REF__';
5747: return $result;
5748: }
5749:
5750: sub str2hash {
5751: my ($string)=@_;
5752: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5753: return %$hash;
5754: }
5755:
5756: sub str2hashref {
5757: my ($string) = @_;
5758:
5759: my %hash;
5760:
5761: if($string !~ /^__HASH_REF__/) {
5762: if (! ($string eq '' || !defined($string))) {
5763: $hash{'error'}='Not hash reference';
5764: }
5765: return (\%hash, $string);
5766: }
5767:
5768: $string =~ s/^__HASH_REF__//;
5769:
5770: while($string !~ /^__END_HASH_REF__/) {
5771: #key
5772: my $key='';
5773: if($string =~ /^__HASH_REF__/) {
5774: ($key, $string)=&str2hashref($string);
5775: if(defined($key->{'error'})) {
5776: $hash{'error'}='Bad data';
5777: return (\%hash, $string);
5778: }
5779: } elsif($string =~ /^__ARRAY_REF__/) {
5780: ($key, $string)=&str2arrayref($string);
5781: if($key->[0] eq 'Array reference error') {
5782: $hash{'error'}='Bad data';
5783: return (\%hash, $string);
5784: }
5785: } else {
5786: $string =~ s/^(.*?)=//;
5787: $key=&unescape($1);
5788: }
5789: $string =~ s/^=//;
5790:
5791: #value
5792: my $value='';
5793: if($string =~ /^__HASH_REF__/) {
5794: ($value, $string)=&str2hashref($string);
5795: if(defined($value->{'error'})) {
5796: $hash{'error'}='Bad data';
5797: return (\%hash, $string);
5798: }
5799: } elsif($string =~ /^__ARRAY_REF__/) {
5800: ($value, $string)=&str2arrayref($string);
5801: if($value->[0] eq 'Array reference error') {
5802: $hash{'error'}='Bad data';
5803: return (\%hash, $string);
5804: }
5805: } else {
5806: $value=&get_scalar(\$string,'__END_HASH_REF__');
5807: }
5808: $string =~ s/^&//;
5809:
5810: $hash{$key}=$value;
5811: }
5812:
5813: $string =~ s/^__END_HASH_REF__//;
5814:
5815: return (\%hash, $string);
5816: }
5817:
5818: sub str2array {
5819: my ($string)=@_;
5820: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5821: return @$array;
5822: }
5823:
5824: sub str2arrayref {
5825: my ($string) = @_;
5826: my @array;
5827:
5828: if($string !~ /^__ARRAY_REF__/) {
5829: if (! ($string eq '' || !defined($string))) {
5830: $array[0]='Array reference error';
5831: }
5832: return (\@array, $string);
5833: }
5834:
5835: $string =~ s/^__ARRAY_REF__//;
5836:
5837: while($string !~ /^__END_ARRAY_REF__/) {
5838: my $value='';
5839: if($string =~ /^__HASH_REF__/) {
5840: ($value, $string)=&str2hashref($string);
5841: if(defined($value->{'error'})) {
5842: $array[0] ='Array reference error';
5843: return (\@array, $string);
5844: }
5845: } elsif($string =~ /^__ARRAY_REF__/) {
5846: ($value, $string)=&str2arrayref($string);
5847: if($value->[0] eq 'Array reference error') {
5848: $array[0] ='Array reference error';
5849: return (\@array, $string);
5850: }
5851: } else {
5852: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5853: }
5854: $string =~ s/^&//;
5855:
5856: push(@array, $value);
5857: }
5858:
5859: $string =~ s/^__END_ARRAY_REF__//;
5860:
5861: return (\@array, $string);
5862: }
5863:
5864: # -------------------------------------------------------------------Temp Store
5865:
5866: sub tmpreset {
5867: my ($symb,$namespace,$domain,$stuname) = @_;
5868: if (!$symb) {
5869: $symb=&symbread();
5870: if (!$symb) { $symb= $env{'request.url'}; }
5871: }
5872: $symb=escape($symb);
5873:
5874: if (!$namespace) { $namespace=$env{'request.state'}; }
5875: $namespace=~s/\//\_/g;
5876: $namespace=~s/\W//g;
5877:
5878: if (!$domain) { $domain=$env{'user.domain'}; }
5879: if (!$stuname) { $stuname=$env{'user.name'}; }
5880: if ($domain eq 'public' && $stuname eq 'public') {
5881: $stuname=&get_requestor_ip();
5882: }
5883: my $path=LONCAPA::tempdir();
5884: my %hash;
5885: if (tie(%hash,'GDBM_File',
5886: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5887: &GDBM_WRCREAT(),0640)) {
5888: foreach my $key (keys(%hash)) {
5889: if ($key=~ /:$symb/) {
5890: delete($hash{$key});
5891: }
5892: }
5893: }
5894: }
5895:
5896: sub tmpstore {
5897: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5898:
5899: if (!$symb) {
5900: $symb=&symbread();
5901: if (!$symb) { $symb= $env{'request.url'}; }
5902: }
5903: $symb=escape($symb);
5904:
5905: if (!$namespace) {
5906: # I don't think we would ever want to store this for a course.
5907: # it seems this will only be used if we don't have a course.
5908: #$namespace=$env{'request.course.id'};
5909: #if (!$namespace) {
5910: $namespace=$env{'request.state'};
5911: #}
5912: }
5913: $namespace=~s/\//\_/g;
5914: $namespace=~s/\W//g;
5915: if (!$domain) { $domain=$env{'user.domain'}; }
5916: if (!$stuname) { $stuname=$env{'user.name'}; }
5917: if ($domain eq 'public' && $stuname eq 'public') {
5918: $stuname=&get_requestor_ip();
5919: }
5920: my $now=time;
5921: my %hash;
5922: my $path=LONCAPA::tempdir();
5923: if (tie(%hash,'GDBM_File',
5924: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5925: &GDBM_WRCREAT(),0640)) {
5926: $hash{"version:$symb"}++;
5927: my $version=$hash{"version:$symb"};
5928: my $allkeys='';
5929: foreach my $key (keys(%$storehash)) {
5930: $allkeys.=$key.':';
5931: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
5932: }
5933: $hash{"$version:$symb:timestamp"}=$now;
5934: $allkeys.='timestamp';
5935: $hash{"$version:keys:$symb"}=$allkeys;
5936: if (untie(%hash)) {
5937: return 'ok';
5938: } else {
5939: return "error:$!";
5940: }
5941: } else {
5942: return "error:$!";
5943: }
5944: }
5945:
5946: # -----------------------------------------------------------------Temp Restore
5947:
5948: sub tmprestore {
5949: my ($symb,$namespace,$domain,$stuname) = @_;
5950:
5951: if (!$symb) {
5952: $symb=&symbread();
5953: if (!$symb) { $symb= $env{'request.url'}; }
5954: }
5955: $symb=escape($symb);
5956:
5957: if (!$namespace) { $namespace=$env{'request.state'}; }
5958:
5959: if (!$domain) { $domain=$env{'user.domain'}; }
5960: if (!$stuname) { $stuname=$env{'user.name'}; }
5961: if ($domain eq 'public' && $stuname eq 'public') {
5962: $stuname=&get_requestor_ip();
5963: }
5964: my %returnhash;
5965: $namespace=~s/\//\_/g;
5966: $namespace=~s/\W//g;
5967: my %hash;
5968: my $path=LONCAPA::tempdir();
5969: if (tie(%hash,'GDBM_File',
5970: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5971: &GDBM_READER(),0640)) {
5972: my $version=$hash{"version:$symb"};
5973: $returnhash{'version'}=$version;
5974: my $scope;
5975: for ($scope=1;$scope<=$version;$scope++) {
5976: my $vkeys=$hash{"$scope:keys:$symb"};
5977: my @keys=split(/:/,$vkeys);
5978: my $key;
5979: $returnhash{"$scope:keys"}=$vkeys;
5980: foreach $key (@keys) {
5981: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5982: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5983: }
5984: }
5985: if (!(untie(%hash))) {
5986: return "error:$!";
5987: }
5988: } else {
5989: return "error:$!";
5990: }
5991: return %returnhash;
5992: }
5993:
5994: # ----------------------------------------------------------------------- Store
5995:
5996: sub store {
5997: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5998: my $home='';
5999:
6000: if ($stuname) { $home=&homeserver($stuname,$domain); }
6001:
6002: $symb=&symbclean($symb);
6003: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6004:
6005: if (!$domain) { $domain=$env{'user.domain'}; }
6006: if (!$stuname) { $stuname=$env{'user.name'}; }
6007:
6008: &devalidate($symb,$stuname,$domain);
6009:
6010: $symb=escape($symb);
6011: if (!$namespace) {
6012: unless ($namespace=$env{'request.course.id'}) {
6013: return '';
6014: }
6015: }
6016: if (!$home) { $home=$env{'user.home'}; }
6017:
6018: $$storehash{'ip'}=&get_requestor_ip();
6019: $$storehash{'host'}=$perlvar{'lonHostID'};
6020:
6021: my $namevalue='';
6022: foreach my $key (keys(%$storehash)) {
6023: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6024: }
6025: $namevalue=~s/\&$//;
6026: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
6027: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6028: }
6029:
6030: # -------------------------------------------------------------- Critical Store
6031:
6032: sub cstore {
6033: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6034: my $home='';
6035:
6036: if ($stuname) { $home=&homeserver($stuname,$domain); }
6037:
6038: $symb=&symbclean($symb);
6039: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6040:
6041: if (!$domain) { $domain=$env{'user.domain'}; }
6042: if (!$stuname) { $stuname=$env{'user.name'}; }
6043:
6044: &devalidate($symb,$stuname,$domain);
6045:
6046: $symb=escape($symb);
6047: if (!$namespace) {
6048: unless ($namespace=$env{'request.course.id'}) {
6049: return '';
6050: }
6051: }
6052: if (!$home) { $home=$env{'user.home'}; }
6053:
6054: $$storehash{'ip'}=&get_requestor_ip();
6055: $$storehash{'host'}=$perlvar{'lonHostID'};
6056:
6057: my $namevalue='';
6058: foreach my $key (keys(%$storehash)) {
6059: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6060: }
6061: $namevalue=~s/\&$//;
6062: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
6063: return critical
6064: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6065: }
6066:
6067: # --------------------------------------------------------------------- Restore
6068:
6069: sub restore {
6070: my ($symb,$namespace,$domain,$stuname) = @_;
6071: my $home='';
6072:
6073: if ($stuname) { $home=&homeserver($stuname,$domain); }
6074:
6075: if (!$symb) {
6076: return if ($namespace eq 'courserequests');
6077: unless ($symb=escape(&symbread())) { return ''; }
6078: } else {
6079: unless ($namespace eq 'courserequests') {
6080: $symb=&escape(&symbclean($symb));
6081: }
6082: }
6083: if (!$namespace) {
6084: unless ($namespace=$env{'request.course.id'}) {
6085: return '';
6086: }
6087: }
6088: if (!$domain) { $domain=$env{'user.domain'}; }
6089: if (!$stuname) { $stuname=$env{'user.name'}; }
6090: if (!$home) { $home=$env{'user.home'}; }
6091: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6092:
6093: my %returnhash=();
6094: foreach my $line (split(/\&/,$answer)) {
6095: my ($name,$value)=split(/\=/,$line);
6096: $returnhash{&unescape($name)}=&thaw_unescape($value);
6097: }
6098: my $version;
6099: for ($version=1;$version<=$returnhash{'version'};$version++) {
6100: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6101: $returnhash{$item}=$returnhash{$version.':'.$item};
6102: }
6103: }
6104: return %returnhash;
6105: }
6106:
6107: # ---------------------------------------------------------- Course Description
6108: #
6109: #
6110:
6111: sub coursedescription {
6112: my ($courseid,$args)=@_;
6113: $courseid=~s/^\///;
6114: $courseid=~s/\_/\//g;
6115: my ($cdomain,$cnum)=split(/\//,$courseid);
6116: my $chome=&homeserver($cnum,$cdomain);
6117: my $normalid=$cdomain.'_'.$cnum;
6118: # need to always cache even if we get errors otherwise we keep
6119: # trying and trying and trying to get the course description.
6120: my %envhash=();
6121: my %returnhash=();
6122:
6123: my $expiretime=600;
6124: if ($env{'request.course.id'} eq $normalid) {
6125: $expiretime=120;
6126: }
6127:
6128: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6129: if (!$args->{'freshen_cache'}
6130: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6131: foreach my $key (keys(%env)) {
6132: next if ($key !~ /^\Q$prefix\E(.*)/);
6133: my ($setting) = $1;
6134: $returnhash{$setting} = $env{$key};
6135: }
6136: return %returnhash;
6137: }
6138:
6139: # get the data again
6140:
6141: if (!$args->{'one_time'}) {
6142: $envhash{'course.'.$normalid.'.last_cache'}=time;
6143: }
6144:
6145: if ($chome ne 'no_host') {
6146: %returnhash=&dump('environment',$cdomain,$cnum);
6147: if (!exists($returnhash{'con_lost'})) {
6148: my $username = $env{'user.name'}; # Defult username
6149: if(defined $args->{'user'}) {
6150: $username = $args->{'user'};
6151: }
6152: $returnhash{'home'}= $chome;
6153: $returnhash{'domain'} = $cdomain;
6154: $returnhash{'num'} = $cnum;
6155: if (!defined($returnhash{'type'})) {
6156: $returnhash{'type'} = 'Course';
6157: }
6158: while (my ($name,$value) = each %returnhash) {
6159: $envhash{'course.'.$normalid.'.'.$name}=$value;
6160: }
6161: $returnhash{'url'}=&clutter($returnhash{'url'});
6162: $returnhash{'fn'}=LONCAPA::tempdir() .
6163: $username.'_'.$cdomain.'_'.$cnum;
6164: $envhash{'course.'.$normalid.'.home'}=$chome;
6165: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6166: $envhash{'course.'.$normalid.'.num'}=$cnum;
6167: }
6168: }
6169: if (!$args->{'one_time'}) {
6170: &appenv(\%envhash);
6171: }
6172: return %returnhash;
6173: }
6174:
6175: sub update_released_required {
6176: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6177: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6178: $cid = $env{'request.course.id'};
6179: $cdom = $env{'course.'.$cid.'.domain'};
6180: $cnum = $env{'course.'.$cid.'.num'};
6181: $chome = $env{'course.'.$cid.'.home'};
6182: }
6183: if ($needsrelease) {
6184: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6185: my $needsupdate;
6186: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6187: $needsupdate = 1;
6188: } else {
6189: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6190: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6191: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6192: $needsupdate = 1;
6193: }
6194: }
6195: if ($needsupdate) {
6196: my %needshash = (
6197: 'internal.releaserequired' => $needsrelease,
6198: );
6199: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6200: if ($putresult eq 'ok') {
6201: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6202: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6203: if (ref($crsinfo{$cid}) eq 'HASH') {
6204: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6205: &courseidput($cdom,\%crsinfo,$chome,'notime');
6206: }
6207: }
6208: }
6209: }
6210: return;
6211: }
6212:
6213: # -------------------------------------------------See if a user is privileged
6214:
6215: sub privileged {
6216: my ($username,$domain,$possdomains,$possroles)=@_;
6217: my $now = time;
6218: my $roles;
6219: if (ref($possroles) eq 'ARRAY') {
6220: $roles = $possroles;
6221: } else {
6222: $roles = ['dc','su'];
6223: }
6224: if (ref($possdomains) eq 'ARRAY') {
6225: my %privileged = &privileged_by_domain($possdomains,$roles);
6226: foreach my $dom (@{$possdomains}) {
6227: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6228: (ref($privileged{$dom}) eq 'HASH')) {
6229: foreach my $role (@{$roles}) {
6230: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6231: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6232: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6233: return 1 unless (($end && $end < $now) ||
6234: ($start && $start > $now));
6235: }
6236: }
6237: }
6238: }
6239: }
6240: } else {
6241: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6242: my $now = time;
6243:
6244: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
6245: my ($trole, $tend, $tstart) = split(/_/, $role);
6246: if (grep(/^\Q$trole\E$/,@{$roles})) {
6247: return 1 unless ($tend && $tend < $now)
6248: or ($tstart && $tstart > $now);
6249: }
6250: }
6251: }
6252: return 0;
6253: }
6254:
6255: sub privileged_by_domain {
6256: my ($domains,$roles) = @_;
6257: my %privileged = ();
6258: my $cachetime = 60*60*24;
6259: my $now = time;
6260: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6261: return %privileged;
6262: }
6263: foreach my $dom (@{$domains}) {
6264: next if (ref($privileged{$dom}) eq 'HASH');
6265: my $needroles;
6266: foreach my $role (@{$roles}) {
6267: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6268: if (defined($cached)) {
6269: if (ref($result) eq 'HASH') {
6270: $privileged{$dom}{$role} = $result;
6271: }
6272: } else {
6273: $needroles = 1;
6274: }
6275: }
6276: if ($needroles) {
6277: my %dompersonnel = &get_domain_roles($dom,$roles);
6278: $privileged{$dom} = {};
6279: foreach my $server (keys(%dompersonnel)) {
6280: if (ref($dompersonnel{$server}) eq 'HASH') {
6281: foreach my $item (keys(%{$dompersonnel{$server}})) {
6282: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6283: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6284: next if ($end && $end < $now);
6285: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6286: $dompersonnel{$server}{$item};
6287: }
6288: }
6289: }
6290: if (ref($privileged{$dom}) eq 'HASH') {
6291: foreach my $role (@{$roles}) {
6292: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6293: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6294: } else {
6295: my %hash = ();
6296: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6297: }
6298: }
6299: }
6300: }
6301: }
6302: return %privileged;
6303: }
6304:
6305: # -------------------------------------------------------- Get user privileges
6306:
6307: sub rolesinit {
6308: my ($domain, $username) = @_;
6309: my %userroles = ('user.login.time' => time);
6310: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6311:
6312: # firstaccess and timerinterval are related to timed maps/resources.
6313: # also, blocking can be triggered by an activating timer
6314: # it's saved in the user's %env.
6315: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6316: my %timerinterval = &dump('timerinterval', $domain, $username);
6317: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6318: %timerintchk, %timerintenv);
6319:
6320: foreach my $key (keys(%firstaccess)) {
6321: my ($cid, $rest) = split(/\0/, $key);
6322: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6323: }
6324:
6325: foreach my $key (keys(%timerinterval)) {
6326: my ($cid,$rest) = split(/\0/,$key);
6327: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6328: }
6329:
6330: my %allroles=();
6331: my %allgroups=();
6332:
6333: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
6334: my $role = $rolesdump{$area};
6335: $area =~ s/\_\w\w$//;
6336:
6337: my ($trole, $tend, $tstart, $group_privs);
6338:
6339: if ($role =~ /^cr/) {
6340: # Custom role, defined by a user
6341: # e.g., user.role.cr/msu/smith/mynewrole
6342: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6343: $trole = $1;
6344: ($tend, $tstart) = split('_', $2);
6345: } else {
6346: $trole = $role;
6347: }
6348: } elsif ($role =~ m|^gr/|) {
6349: # Role of member in a group, defined within a course/community
6350: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6351: ($trole, $tend, $tstart) = split(/_/, $role);
6352: next if $tstart eq '-1';
6353: ($trole, $group_privs) = split(/\//, $trole);
6354: $group_privs = &unescape($group_privs);
6355: } else {
6356: # Just a normal role, defined in roles.tab
6357: ($trole, $tend, $tstart) = split(/_/,$role);
6358: }
6359:
6360: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6361: $username);
6362: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6363:
6364: # role expired or not available yet?
6365: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6366: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6367:
6368: next if $area eq '' or $trole eq '';
6369:
6370: my $spec = "$trole.$area";
6371: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6372:
6373: if ($trole =~ /^cr\//) {
6374: # Custom role, defined by a user
6375: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6376: } elsif ($trole eq 'gr') {
6377: # Role of a member in a group, defined within a course/community
6378: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6379: next;
6380: } else {
6381: # Normal role, defined in roles.tab
6382: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6383: }
6384:
6385: my $cid = $tdomain.'_'.$trest;
6386: unless ($firstaccchk{$cid}) {
6387: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6388: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6389: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6390: $coursetimerstarts{$cid}{$item};
6391: }
6392: }
6393: $firstaccchk{$cid} = 1;
6394: }
6395: unless ($timerintchk{$cid}) {
6396: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6397: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6398: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6399: $coursetimerintervals{$cid}{$item};
6400: }
6401: }
6402: $timerintchk{$cid} = 1;
6403: }
6404: }
6405:
6406: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6407: \%allroles, \%allgroups);
6408: $env{'user.adv'} = $userroles{'user.adv'};
6409: $env{'user.rar'} = $userroles{'user.rar'};
6410:
6411: return (\%userroles,\%firstaccenv,\%timerintenv);
6412: }
6413:
6414: sub set_arearole {
6415: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6416: unless ($nolog) {
6417: # log the associated role with the area
6418: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6419: }
6420: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6421: }
6422:
6423: sub custom_roleprivs {
6424: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6425: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6426: my $homsvr = &homeserver($rauthor,$rdomain);
6427: if (&hostname($homsvr) ne '') {
6428: my ($rdummy,$roledef)=
6429: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6430: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6431: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6432: if (defined($syspriv)) {
6433: if ($trest =~ /^$match_community$/) {
6434: $syspriv =~ s/bre\&S//;
6435: }
6436: $$allroles{'cm./'}.=':'.$syspriv;
6437: $$allroles{$spec.'./'}.=':'.$syspriv;
6438: }
6439: if ($tdomain ne '') {
6440: if (defined($dompriv)) {
6441: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6442: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6443: }
6444: if (($trest ne '') && (defined($coursepriv))) {
6445: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6446: my $rolename = $1;
6447: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6448: }
6449: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6450: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6451: }
6452: }
6453: }
6454: }
6455: }
6456:
6457: sub course_adhocrole_privs {
6458: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6459: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6460: if ($overrides{"internal.adhocpriv.$rolename"}) {
6461: my (%currprivs,%storeprivs);
6462: foreach my $item (split(/:/,$coursepriv)) {
6463: my ($priv,$restrict) = split(/\&/,$item);
6464: $currprivs{$priv} = $restrict;
6465: }
6466: my (%possadd,%possremove,%full);
6467: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6468: my ($priv,$restrict)=split(/\&/,$item);
6469: $full{$priv} = $restrict;
6470: }
6471: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6472: next if ($item eq '');
6473: my ($rule,$rest) = split(/=/,$item);
6474: next unless (($rule eq 'off') || ($rule eq 'on'));
6475: foreach my $priv (split(/:/,$rest)) {
6476: if ($priv ne '') {
6477: if ($rule eq 'off') {
6478: $possremove{$priv} = 1;
6479: } else {
6480: $possadd{$priv} = 1;
6481: }
6482: }
6483: }
6484: }
6485: foreach my $priv (sort(keys(%full))) {
6486: if (exists($currprivs{$priv})) {
6487: unless (exists($possremove{$priv})) {
6488: $storeprivs{$priv} = $currprivs{$priv};
6489: }
6490: } elsif (exists($possadd{$priv})) {
6491: $storeprivs{$priv} = $full{$priv};
6492: }
6493: }
6494: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6495: }
6496: return $coursepriv;
6497: }
6498:
6499: sub group_roleprivs {
6500: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6501: my $access = 1;
6502: my $now = time;
6503: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6504: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6505: if ($access) {
6506: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6507: $$allgroups{$course}{$group} .=':'.$group_privs;
6508: }
6509: }
6510:
6511: sub standard_roleprivs {
6512: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6513: if (defined($pr{$trole.':s'})) {
6514: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6515: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6516: }
6517: if ($tdomain ne '') {
6518: if (defined($pr{$trole.':d'})) {
6519: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6520: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6521: }
6522: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6523: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6524: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6525: }
6526: }
6527: }
6528:
6529: sub set_userprivs {
6530: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6531: my $author=0;
6532: my $adv=0;
6533: my $rar=0;
6534: my %grouproles = ();
6535: if (keys(%{$allgroups}) > 0) {
6536: my @groupkeys;
6537: foreach my $role (keys(%{$allroles})) {
6538: push(@groupkeys,$role);
6539: }
6540: if (ref($groups_roles) eq 'HASH') {
6541: foreach my $key (keys(%{$groups_roles})) {
6542: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6543: push(@groupkeys,$key);
6544: }
6545: }
6546: }
6547: if (@groupkeys > 0) {
6548: foreach my $role (@groupkeys) {
6549: my ($trole,$area,$sec,$extendedarea);
6550: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6551: $trole = $1;
6552: $area = $2;
6553: $sec = $3;
6554: $extendedarea = $area.$sec;
6555: if (exists($$allgroups{$area})) {
6556: foreach my $group (keys(%{$$allgroups{$area}})) {
6557: my $spec = $trole.'.'.$extendedarea;
6558: $grouproles{$spec.'.'.$area.'/'.$group} =
6559: $$allgroups{$area}{$group};
6560: }
6561: }
6562: }
6563: }
6564: }
6565: }
6566: foreach my $group (keys(%grouproles)) {
6567: $$allroles{$group} = $grouproles{$group};
6568: }
6569: foreach my $role (keys(%{$allroles})) {
6570: my %thesepriv;
6571: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6572: foreach my $item (split(/:/,$$allroles{$role})) {
6573: if ($item ne '') {
6574: my ($privilege,$restrictions)=split(/&/,$item);
6575: if ($restrictions eq '') {
6576: $thesepriv{$privilege}='F';
6577: } elsif ($thesepriv{$privilege} ne 'F') {
6578: $thesepriv{$privilege}.=$restrictions;
6579: }
6580: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6581: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6582: }
6583: }
6584: my $thesestr='';
6585: foreach my $priv (sort(keys(%thesepriv))) {
6586: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6587: }
6588: $userroles->{'user.priv.'.$role} = $thesestr;
6589: }
6590: return ($author,$adv,$rar);
6591: }
6592:
6593: sub role_status {
6594: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6595: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6596: my ($one,$two) = split(m{\./},$rolekey,2);
6597: (undef,undef,$$role) = split(/\./,$one,3);
6598: unless (!defined($$role) || $$role eq '') {
6599: $$where = '/'.$two;
6600: $$trolecode=$$role.'.'.$$where;
6601: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6602: $$tstatus='is';
6603: if ($$tstart && $$tstart>$update) {
6604: $$tstatus='future';
6605: if ($$tstart<$now) {
6606: if ($$tstart && $$tstart>$refresh) {
6607: if (($$where ne '') && ($$role ne '')) {
6608: my (%allroles,%allgroups,$group_privs,
6609: %groups_roles,@rolecodes);
6610: my %userroles = (
6611: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6612: );
6613: @rolecodes = ('cm');
6614: my $spec=$$role.'.'.$$where;
6615: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6616: if ($$role =~ /^cr\//) {
6617: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6618: push(@rolecodes,'cr');
6619: } elsif ($$role eq 'gr') {
6620: push(@rolecodes,$$role);
6621: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6622: $env{'user.name'});
6623: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6624: (undef,my $group_privs) = split(/\//,$trole);
6625: $group_privs = &unescape($group_privs);
6626: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6627: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6628: &get_groups_roles($tdomain,$trest,
6629: \%course_roles,\@rolecodes,
6630: \%groups_roles);
6631: } else {
6632: push(@rolecodes,$$role);
6633: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6634: }
6635: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6636: \%groups_roles);
6637: &appenv(\%userroles,\@rolecodes);
6638: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6639: }
6640: }
6641: $$tstatus = 'is';
6642: }
6643: }
6644: if ($$tend) {
6645: if ($$tend<$update) {
6646: $$tstatus='expired';
6647: } elsif ($$tend<$now) {
6648: $$tstatus='will_not';
6649: }
6650: }
6651: }
6652: }
6653: }
6654:
6655: sub get_groups_roles {
6656: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6657: return unless((ref($cdom_courseroles) eq 'HASH') &&
6658: (ref($rolecodes) eq 'ARRAY') &&
6659: (ref($groups_roles) eq 'HASH'));
6660: if (keys(%{$cdom_courseroles}) > 0) {
6661: my ($cnum) = ($rest =~ /^($match_courseid)/);
6662: if ($cdom ne '' && $cnum ne '') {
6663: foreach my $key (keys(%{$cdom_courseroles})) {
6664: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6665: my $crsrole = $1;
6666: my $crssec = $2;
6667: if ($crsrole =~ /^cr/) {
6668: unless (grep(/^cr$/,@{$rolecodes})) {
6669: push(@{$rolecodes},'cr');
6670: }
6671: } else {
6672: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6673: push(@{$rolecodes},$crsrole);
6674: }
6675: }
6676: my $rolekey = "$crsrole./$cdom/$cnum";
6677: if ($crssec ne '') {
6678: $rolekey .= "/$crssec";
6679: }
6680: $rolekey .= './';
6681: $groups_roles->{$rolekey} = $rolecodes;
6682: }
6683: }
6684: }
6685: }
6686: return;
6687: }
6688:
6689: sub delete_env_groupprivs {
6690: my ($where,$courseroles,$possroles) = @_;
6691: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6692: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6693: unless (ref($courseroles->{$udom}) eq 'HASH') {
6694: %{$courseroles->{$udom}} =
6695: &get_my_roles('','','userroles',['active'],
6696: $possroles,[$udom],1);
6697: }
6698: if (ref($courseroles->{$udom}) eq 'HASH') {
6699: foreach my $item (keys(%{$courseroles->{$udom}})) {
6700: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6701: my $area = '/'.$cdom.'/'.$cnum;
6702: my $privkey = "user.priv.$crsrole.$area";
6703: if ($crssec ne '') {
6704: $privkey .= '/'.$crssec;
6705: }
6706: $privkey .= ".$area/$group";
6707: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6708: }
6709: }
6710: return;
6711: }
6712:
6713: sub check_adhoc_privs {
6714: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6715: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6716: if ($sec) {
6717: $cckey .= '/'.$sec;
6718: }
6719: my $setprivs;
6720: if ($env{$cckey}) {
6721: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6722: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6723: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6724: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6725: $setprivs = 1;
6726: }
6727: } else {
6728: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6729: $setprivs = 1;
6730: }
6731: return $setprivs;
6732: }
6733:
6734: sub set_adhoc_privileges {
6735: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6736: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6737: my $area = '/'.$dcdom.'/'.$pickedcourse;
6738: if ($sec ne '') {
6739: $area .= '/'.$sec;
6740: }
6741: my $spec = $role.'.'.$area;
6742: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6743: $env{'user.name'},1);
6744: my %rolehash = ();
6745: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6746: my $rolename = $1;
6747: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
6748: my %domdef = &get_domain_defaults($dcdom);
6749: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6750: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6751: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6752: }
6753: }
6754: } else {
6755: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6756: }
6757: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
6758: &appenv(\%userroles,[$role,'cm']);
6759: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6760: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6761: &appenv( {'request.role' => $spec,
6762: 'request.role.domain' => $dcdom,
6763: 'request.course.sec' => $sec,
6764: }
6765: );
6766: my $tadv=0;
6767: if (&allowed('adv') eq 'F') { $tadv=1; }
6768: &appenv({'request.role.adv' => $tadv});
6769: }
6770: }
6771:
6772: # --------------------------------------------------------------- get interface
6773:
6774: sub get {
6775: my ($namespace,$storearr,$udomain,$uname)=@_;
6776: my $items='';
6777: foreach my $item (@$storearr) {
6778: $items.=&escape($item).'&';
6779: }
6780: $items=~s/\&$//;
6781: if (!$udomain) { $udomain=$env{'user.domain'}; }
6782: if (!$uname) { $uname=$env{'user.name'}; }
6783: my $uhome=&homeserver($uname,$udomain);
6784:
6785: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
6786: my @pairs=split(/\&/,$rep);
6787: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6788: return @pairs;
6789: }
6790: my %returnhash=();
6791: my $i=0;
6792: foreach my $item (@$storearr) {
6793: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6794: $i++;
6795: }
6796: return %returnhash;
6797: }
6798:
6799: # --------------------------------------------------------------- del interface
6800:
6801: sub del {
6802: my ($namespace,$storearr,$udomain,$uname)=@_;
6803: my $items='';
6804: foreach my $item (@$storearr) {
6805: $items.=&escape($item).'&';
6806: }
6807:
6808: $items=~s/\&$//;
6809: if (!$udomain) { $udomain=$env{'user.domain'}; }
6810: if (!$uname) { $uname=$env{'user.name'}; }
6811: my $uhome=&homeserver($uname,$udomain);
6812: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
6813: }
6814:
6815: # -------------------------------------------------------------- dump interface
6816:
6817: sub unserialize {
6818: my ($rep, $escapedkeys) = @_;
6819:
6820: return {} if $rep =~ /^error/;
6821:
6822: my %returnhash=();
6823: foreach my $item (split(/\&/,$rep)) {
6824: my ($key, $value) = split(/=/, $item, 2);
6825: $key = unescape($key) unless $escapedkeys;
6826: next if $key =~ /^error: 2 /;
6827: $returnhash{$key} = &thaw_unescape($value);
6828: }
6829: return \%returnhash;
6830: }
6831:
6832: # see Lond::dump_with_regexp
6833: # if $escapedkeys hash keys won't get unescaped.
6834: sub dump {
6835: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
6836: if (!$udomain) { $udomain=$env{'user.domain'}; }
6837: if (!$uname) { $uname=$env{'user.name'}; }
6838: my $uhome=&homeserver($uname,$udomain);
6839:
6840: if ($regexp) {
6841: $regexp=&escape($regexp);
6842: } else {
6843: $regexp='.';
6844: }
6845: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6846: # user is hosted on this machine
6847: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
6848: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
6849: return %{&unserialize($reply, $escapedkeys)};
6850: }
6851: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
6852: my @pairs=split(/\&/,$rep);
6853: my %returnhash=();
6854: if (!($rep =~ /^error/ )) {
6855: foreach my $item (@pairs) {
6856: my ($key,$value)=split(/=/,$item,2);
6857: $key = &unescape($key) unless ($escapedkeys);
6858: next if ($key =~ /^error: 2 /);
6859: $returnhash{$key}=&thaw_unescape($value);
6860: }
6861: }
6862: return %returnhash;
6863: }
6864:
6865:
6866: # --------------------------------------------------------- dumpstore interface
6867:
6868: sub dumpstore {
6869: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
6870: # same as dump but keys must be escaped. They may contain colon separated
6871: # lists of values that may themself contain colons (e.g. symbs).
6872: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
6873: }
6874:
6875: # -------------------------------------------------------------- keys interface
6876:
6877: sub getkeys {
6878: my ($namespace,$udomain,$uname)=@_;
6879: if (!$udomain) { $udomain=$env{'user.domain'}; }
6880: if (!$uname) { $uname=$env{'user.name'}; }
6881: my $uhome=&homeserver($uname,$udomain);
6882: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6883: my @keyarray=();
6884: foreach my $key (split(/\&/,$rep)) {
6885: next if ($key =~ /^error: 2 /);
6886: push(@keyarray,&unescape($key));
6887: }
6888: return @keyarray;
6889: }
6890:
6891: # --------------------------------------------------------------- currentdump
6892: sub currentdump {
6893: my ($courseid,$sdom,$sname)=@_;
6894: $courseid = $env{'request.course.id'} if (! defined($courseid));
6895: $sdom = $env{'user.domain'} if (! defined($sdom));
6896: $sname = $env{'user.name'} if (! defined($sname));
6897: my $uhome = &homeserver($sname,$sdom);
6898: my $rep;
6899:
6900: if (grep { $_ eq $uhome } current_machine_ids()) {
6901: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6902: $courseid)));
6903: } else {
6904: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6905: }
6906:
6907: return if ($rep =~ /^(error:|no_such_host)/);
6908: #
6909: my %returnhash=();
6910: #
6911: if ($rep eq "unknown_cmd") {
6912: # an old lond will not know currentdump
6913: # Do a dump and make it look like a currentdump
6914: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
6915: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6916: my %hash = @tmp;
6917: @tmp=();
6918: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
6919: } else {
6920: my @pairs=split(/\&/,$rep);
6921: foreach my $pair (@pairs) {
6922: my ($key,$value)=split(/=/,$pair,2);
6923: my ($symb,$param) = split(/:/,$key);
6924: $returnhash{&unescape($symb)}->{&unescape($param)} =
6925: &thaw_unescape($value);
6926: }
6927: }
6928: return %returnhash;
6929: }
6930:
6931: sub convert_dump_to_currentdump{
6932: my %hash = %{shift()};
6933: my %returnhash;
6934: # Code ripped from lond, essentially. The only difference
6935: # here is the unescaping done by lonnet::dump(). Conceivably
6936: # we might run in to problems with parameter names =~ /^v\./
6937: while (my ($key,$value) = each(%hash)) {
6938: my ($v,$symb,$param) = split(/:/,$key);
6939: $symb = &unescape($symb);
6940: $param = &unescape($param);
6941: next if ($v eq 'version' || $symb eq 'keys');
6942: next if (exists($returnhash{$symb}) &&
6943: exists($returnhash{$symb}->{$param}) &&
6944: $returnhash{$symb}->{'v.'.$param} > $v);
6945: $returnhash{$symb}->{$param}=$value;
6946: $returnhash{$symb}->{'v.'.$param}=$v;
6947: }
6948: #
6949: # Remove all of the keys in the hashes which keep track of
6950: # the version of the parameter.
6951: while (my ($symb,$param_hash) = each(%returnhash)) {
6952: # use a foreach because we are going to delete from the hash.
6953: foreach my $key (keys(%$param_hash)) {
6954: delete($param_hash->{$key}) if ($key =~ /^v\./);
6955: }
6956: }
6957: return \%returnhash;
6958: }
6959:
6960: # ------------------------------------------------------ critical inc interface
6961:
6962: sub cinc {
6963: return &inc(@_,'critical');
6964: }
6965:
6966: # --------------------------------------------------------------- inc interface
6967:
6968: sub inc {
6969: my ($namespace,$store,$udomain,$uname,$critical) = @_;
6970: if (!$udomain) { $udomain=$env{'user.domain'}; }
6971: if (!$uname) { $uname=$env{'user.name'}; }
6972: my $uhome=&homeserver($uname,$udomain);
6973: my $items='';
6974: if (! ref($store)) {
6975: # got a single value, so use that instead
6976: $items = &escape($store).'=&';
6977: } elsif (ref($store) eq 'SCALAR') {
6978: $items = &escape($$store).'=&';
6979: } elsif (ref($store) eq 'ARRAY') {
6980: $items = join('=&',map {&escape($_);} @{$store});
6981: } elsif (ref($store) eq 'HASH') {
6982: while (my($key,$value) = each(%{$store})) {
6983: $items.= &escape($key).'='.&escape($value).'&';
6984: }
6985: }
6986: $items=~s/\&$//;
6987: if ($critical) {
6988: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6989: } else {
6990: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6991: }
6992: }
6993:
6994: # --------------------------------------------------------------- put interface
6995:
6996: sub put {
6997: my ($namespace,$storehash,$udomain,$uname)=@_;
6998: if (!$udomain) { $udomain=$env{'user.domain'}; }
6999: if (!$uname) { $uname=$env{'user.name'}; }
7000: my $uhome=&homeserver($uname,$udomain);
7001: my $items='';
7002: foreach my $item (keys(%$storehash)) {
7003: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7004: }
7005: $items=~s/\&$//;
7006: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7007: }
7008:
7009: # ------------------------------------------------------------ newput interface
7010:
7011: sub newput {
7012: my ($namespace,$storehash,$udomain,$uname)=@_;
7013: if (!$udomain) { $udomain=$env{'user.domain'}; }
7014: if (!$uname) { $uname=$env{'user.name'}; }
7015: my $uhome=&homeserver($uname,$udomain);
7016: my $items='';
7017: foreach my $key (keys(%$storehash)) {
7018: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7019: }
7020: $items=~s/\&$//;
7021: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7022: }
7023:
7024: # --------------------------------------------------------- putstore interface
7025:
7026: sub putstore {
7027: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
7028: if (!$udomain) { $udomain=$env{'user.domain'}; }
7029: if (!$uname) { $uname=$env{'user.name'}; }
7030: my $uhome=&homeserver($uname,$udomain);
7031: my $items='';
7032: foreach my $key (keys(%$storehash)) {
7033: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7034: }
7035: $items=~s/\&$//;
7036: my $esc_symb=&escape($symb);
7037: my $esc_v=&escape($version);
7038: my $reply =
7039: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
7040: $uhome);
7041: if (($tolog) && ($reply eq 'ok')) {
7042: my $namevalue='';
7043: foreach my $key (keys(%{$storehash})) {
7044: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7045: }
7046: my $ip = &get_requestor_ip();
7047: $namevalue .= 'ip='.&escape($ip).
7048: '&host='.&escape($perlvar{'lonHostID'}).
7049: '&version='.$esc_v.
7050: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7051: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7052: }
7053: if ($reply eq 'unknown_cmd') {
7054: # gfall back to way things use to be done
7055: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7056: $uname);
7057: }
7058: return $reply;
7059: }
7060:
7061: sub old_putstore {
7062: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7063: if (!$udomain) { $udomain=$env{'user.domain'}; }
7064: if (!$uname) { $uname=$env{'user.name'}; }
7065: my $uhome=&homeserver($uname,$udomain);
7066: my %newstorehash;
7067: foreach my $item (keys(%$storehash)) {
7068: my $key = $version.':'.&escape($symb).':'.$item;
7069: $newstorehash{$key} = $storehash->{$item};
7070: }
7071: my $items='';
7072: my %allitems = ();
7073: foreach my $item (keys(%newstorehash)) {
7074: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
7075: my $key = $1.':keys:'.$2;
7076: $allitems{$key} .= $3.':';
7077: }
7078: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
7079: }
7080: foreach my $item (keys(%allitems)) {
7081: $allitems{$item} =~ s/\:$//;
7082: $items.= $item.'='.$allitems{$item}.'&';
7083: }
7084: $items=~s/\&$//;
7085: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7086: }
7087:
7088: # ------------------------------------------------------ critical put interface
7089:
7090: sub cput {
7091: my ($namespace,$storehash,$udomain,$uname)=@_;
7092: if (!$udomain) { $udomain=$env{'user.domain'}; }
7093: if (!$uname) { $uname=$env{'user.name'}; }
7094: my $uhome=&homeserver($uname,$udomain);
7095: my $items='';
7096: foreach my $item (keys(%$storehash)) {
7097: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7098: }
7099: $items=~s/\&$//;
7100: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
7101: }
7102:
7103: # -------------------------------------------------------------- eget interface
7104:
7105: sub eget {
7106: my ($namespace,$storearr,$udomain,$uname)=@_;
7107: my $items='';
7108: foreach my $item (@$storearr) {
7109: $items.=&escape($item).'&';
7110: }
7111: $items=~s/\&$//;
7112: if (!$udomain) { $udomain=$env{'user.domain'}; }
7113: if (!$uname) { $uname=$env{'user.name'}; }
7114: my $uhome=&homeserver($uname,$udomain);
7115: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
7116: my @pairs=split(/\&/,$rep);
7117: my %returnhash=();
7118: my $i=0;
7119: foreach my $item (@$storearr) {
7120: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7121: $i++;
7122: }
7123: return %returnhash;
7124: }
7125:
7126: # ------------------------------------------------------------ tmpput interface
7127: sub tmpput {
7128: my ($storehash,$server,$context)=@_;
7129: my $items='';
7130: foreach my $item (keys(%$storehash)) {
7131: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7132: }
7133: $items=~s/\&$//;
7134: if (defined($context)) {
7135: $items .= ':'.&escape($context);
7136: }
7137: return &reply("tmpput:$items",$server);
7138: }
7139:
7140: # ------------------------------------------------------------ tmpget interface
7141: sub tmpget {
7142: my ($token,$server)=@_;
7143: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7144: my $rep=&reply("tmpget:$token",$server);
7145: my %returnhash;
7146: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7147: return %returnhash;
7148: }
7149: foreach my $item (split(/\&/,$rep)) {
7150: my ($key,$value)=split(/=/,$item);
7151: $returnhash{&unescape($key)}=&thaw_unescape($value);
7152: }
7153: return %returnhash;
7154: }
7155:
7156: # ------------------------------------------------------------ tmpdel interface
7157: sub tmpdel {
7158: my ($token,$server)=@_;
7159: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7160: return &reply("tmpdel:$token",$server);
7161: }
7162:
7163: # ------------------------------------------------------------ get_timebased_id
7164:
7165: sub get_timebased_id {
7166: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7167: $maxtries) = @_;
7168: my ($newid,$error,$dellock);
7169: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7170: return ('','ok','invalid call to get suffix');
7171: }
7172:
7173: # set defaults for any optional args for which values were not supplied
7174: if ($who eq '') {
7175: $who = $env{'user.name'}.':'.$env{'user.domain'};
7176: }
7177: if (!$locktries) {
7178: $locktries = 3;
7179: }
7180: if (!$maxtries) {
7181: $maxtries = 10;
7182: }
7183:
7184: if (($cdom eq '') || ($cnum eq '')) {
7185: if ($env{'request.course.id'}) {
7186: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7187: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7188: }
7189: if (($cdom eq '') || ($cnum eq '')) {
7190: return ('','ok','call to get suffix not in course context');
7191: }
7192: }
7193:
7194: # construct locking item
7195: my $lockhash = {
7196: $prefix."\0".'locked_'.$keyid => $who,
7197: };
7198: my $tries = 0;
7199:
7200: # attempt to get lock on nohist_$namespace file
7201: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7202: while (($gotlock ne 'ok') && $tries <$locktries) {
7203: $tries ++;
7204: sleep 1;
7205: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7206: }
7207:
7208: # attempt to get unique identifier, based on current timestamp
7209: if ($gotlock eq 'ok') {
7210: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7211: my $id = time;
7212: $newid = $id;
7213: if ($idtype eq 'addcode') {
7214: $newid .= &sixnum_code();
7215: }
7216: my $idtries = 0;
7217: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7218: if ($idtype eq 'concat') {
7219: $newid = $id.$idtries;
7220: } elsif ($idtype eq 'addcode') {
7221: $newid = $newid.&sixnum_code();
7222: } else {
7223: $newid ++;
7224: }
7225: $idtries ++;
7226: }
7227: if (!exists($inuse{$prefix."\0".$newid})) {
7228: my %new_item = (
7229: $prefix."\0".$newid => $who,
7230: );
7231: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7232: $cdom,$cnum);
7233: if ($putresult ne 'ok') {
7234: undef($newid);
7235: $error = 'error saving new item: '.$putresult;
7236: }
7237: } else {
7238: undef($newid);
7239: $error = ('error: no unique suffix available for the new item ');
7240: }
7241: # remove lock
7242: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7243: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7244: } else {
7245: $error = "error: could not obtain lockfile\n";
7246: $dellock = 'ok';
7247: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7248: $dellock = 'nolock';
7249: }
7250: }
7251: return ($newid,$dellock,$error);
7252: }
7253:
7254: sub sixnum_code {
7255: my $code;
7256: for (0..6) {
7257: $code .= int( rand(9) );
7258: }
7259: return $code;
7260: }
7261:
7262: # -------------------------------------------------- portfolio access checking
7263:
7264: sub portfolio_access {
7265: my ($requrl,$clientip) = @_;
7266: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
7267: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
7268: if ($result) {
7269: my %setters;
7270: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7271: my ($startblock,$endblock) =
7272: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7273: if ($startblock && $endblock) {
7274: return 'B';
7275: }
7276: } else {
7277: my ($startblock,$endblock) =
7278: &Apache::loncommon::blockcheck(\%setters,'port');
7279: if ($startblock && $endblock) {
7280: return 'B';
7281: }
7282: }
7283: }
7284: if ($result eq 'ok') {
7285: return 'F';
7286: } elsif ($result =~ /^[^:]+:guest_/) {
7287: return 'A';
7288: }
7289: return '';
7290: }
7291:
7292: sub get_portfolio_access {
7293: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
7294:
7295: if (!ref($access_hash)) {
7296: my $current_perms = &get_portfile_permissions($udom,$unum);
7297: my %access_controls = &get_access_controls($current_perms,$group,
7298: $file_name);
7299: $access_hash = $access_controls{$file_name};
7300: }
7301:
7302: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
7303: my $now = time;
7304: if (ref($access_hash) eq 'HASH') {
7305: foreach my $key (keys(%{$access_hash})) {
7306: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7307: if ($start > $now) {
7308: next;
7309: }
7310: if ($end && $end<$now) {
7311: next;
7312: }
7313: if ($scope eq 'public') {
7314: $public = $key;
7315: last;
7316: } elsif ($scope eq 'guest') {
7317: $guest = $key;
7318: } elsif ($scope eq 'domains') {
7319: push(@domains,$key);
7320: } elsif ($scope eq 'users') {
7321: push(@users,$key);
7322: } elsif ($scope eq 'course') {
7323: push(@courses,$key);
7324: } elsif ($scope eq 'group') {
7325: push(@groups,$key);
7326: } elsif ($scope eq 'ip') {
7327: push(@ips,$key);
7328: }
7329: }
7330: if ($public) {
7331: return 'ok';
7332: } elsif (@ips > 0) {
7333: my $allowed;
7334: foreach my $ipkey (@ips) {
7335: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7336: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7337: $allowed = 1;
7338: last;
7339: }
7340: }
7341: }
7342: if ($allowed) {
7343: return 'ok';
7344: }
7345: }
7346: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7347: if ($guest) {
7348: return $guest;
7349: }
7350: } else {
7351: if (@domains > 0) {
7352: foreach my $domkey (@domains) {
7353: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7354: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7355: return 'ok';
7356: }
7357: }
7358: }
7359: }
7360: if (@users > 0) {
7361: foreach my $userkey (@users) {
7362: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7363: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7364: if (ref($item) eq 'HASH') {
7365: if (($item->{'uname'} eq $env{'user.name'}) &&
7366: ($item->{'udom'} eq $env{'user.domain'})) {
7367: return 'ok';
7368: }
7369: }
7370: }
7371: }
7372: }
7373: }
7374: my %roleshash;
7375: my @courses_and_groups = @courses;
7376: push(@courses_and_groups,@groups);
7377: if (@courses_and_groups > 0) {
7378: my (%allgroups,%allroles);
7379: my ($start,$end,$role,$sec,$group);
7380: foreach my $envkey (%env) {
7381: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
7382: my $cid = $2.'_'.$3;
7383: if ($1 eq 'gr') {
7384: $group = $4;
7385: $allgroups{$cid}{$group} = $env{$envkey};
7386: } else {
7387: if ($4 eq '') {
7388: $sec = 'none';
7389: } else {
7390: $sec = $4;
7391: }
7392: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7393: }
7394: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7395: my $cid = $2.'_'.$3;
7396: if ($4 eq '') {
7397: $sec = 'none';
7398: } else {
7399: $sec = $4;
7400: }
7401: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7402: }
7403: }
7404: if (keys(%allroles) == 0) {
7405: return;
7406: }
7407: foreach my $key (@courses_and_groups) {
7408: my %content = %{$$access_hash{$key}};
7409: my $cnum = $content{'number'};
7410: my $cdom = $content{'domain'};
7411: my $cid = $cdom.'_'.$cnum;
7412: if (!exists($allroles{$cid})) {
7413: next;
7414: }
7415: foreach my $role_id (keys(%{$content{'roles'}})) {
7416: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7417: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7418: my @status = @{$content{'roles'}{$role_id}{'access'}};
7419: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7420: foreach my $role (keys(%{$allroles{$cid}})) {
7421: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7422: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7423: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7424: if (grep/^all$/,@sections) {
7425: return 'ok';
7426: } else {
7427: if (grep/^$sec$/,@sections) {
7428: return 'ok';
7429: }
7430: }
7431: }
7432: }
7433: if (keys(%{$allgroups{$cid}}) == 0) {
7434: if (grep/^none$/,@groups) {
7435: return 'ok';
7436: }
7437: } else {
7438: if (grep/^all$/,@groups) {
7439: return 'ok';
7440: }
7441: foreach my $group (keys(%{$allgroups{$cid}})) {
7442: if (grep/^$group$/,@groups) {
7443: return 'ok';
7444: }
7445: }
7446: }
7447: }
7448: }
7449: }
7450: }
7451: }
7452: if ($guest) {
7453: return $guest;
7454: }
7455: }
7456: }
7457: return;
7458: }
7459:
7460: sub course_group_datechecker {
7461: my ($dates,$now,$status) = @_;
7462: my ($start,$end) = split(/\./,$dates);
7463: if (!$start && !$end) {
7464: return 'ok';
7465: }
7466: if (grep/^active$/,@{$status}) {
7467: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7468: return 'ok';
7469: }
7470: }
7471: if (grep/^previous$/,@{$status}) {
7472: if ($end > $now ) {
7473: return 'ok';
7474: }
7475: }
7476: if (grep/^future$/,@{$status}) {
7477: if ($start > $now) {
7478: return 'ok';
7479: }
7480: }
7481: return;
7482: }
7483:
7484: sub parse_portfolio_url {
7485: my ($url) = @_;
7486:
7487: my ($type,$udom,$unum,$group,$file_name);
7488:
7489: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7490: $type = 1;
7491: $udom = $1;
7492: $unum = $2;
7493: $file_name = $3;
7494: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7495: $type = 2;
7496: $udom = $1;
7497: $unum = $2;
7498: $group = $3;
7499: $file_name = $3.'/'.$4;
7500: }
7501: if (wantarray) {
7502: return ($type,$udom,$unum,$file_name,$group);
7503: }
7504: return $type;
7505: }
7506:
7507: sub is_portfolio_url {
7508: my ($url) = @_;
7509: return scalar(&parse_portfolio_url($url));
7510: }
7511:
7512: sub is_portfolio_file {
7513: my ($file) = @_;
7514: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7515: return 1;
7516: }
7517: return;
7518: }
7519:
7520: sub usertools_access {
7521: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7522: my ($access,%tools);
7523: if ($context eq '') {
7524: $context = 'tools';
7525: }
7526: if ($context eq 'requestcourses') {
7527: %tools = (
7528: official => 1,
7529: unofficial => 1,
7530: community => 1,
7531: textbook => 1,
7532: );
7533: } elsif ($context eq 'requestauthor') {
7534: %tools = (
7535: requestauthor => 1,
7536: );
7537: } else {
7538: %tools = (
7539: aboutme => 1,
7540: blog => 1,
7541: webdav => 1,
7542: portfolio => 1,
7543: );
7544: }
7545: return if (!defined($tools{$tool}));
7546:
7547: if (($udom eq '') || ($uname eq '')) {
7548: $udom = $env{'user.domain'};
7549: $uname = $env{'user.name'};
7550: }
7551:
7552: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7553: if ($action ne 'reload') {
7554: if ($context eq 'requestcourses') {
7555: return $env{'environment.canrequest.'.$tool};
7556: } elsif ($context eq 'requestauthor') {
7557: return $env{'environment.canrequest.author'};
7558: } else {
7559: return $env{'environment.availabletools.'.$tool};
7560: }
7561: }
7562: }
7563:
7564: my ($toolstatus,$inststatus,$envkey);
7565: if ($context eq 'requestauthor') {
7566: $envkey = $context;
7567: } else {
7568: $envkey = $context.'.'.$tool;
7569: }
7570:
7571: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7572: ($action ne 'reload')) {
7573: $toolstatus = $env{'environment.'.$envkey};
7574: $inststatus = $env{'environment.inststatus'};
7575: } else {
7576: if (ref($userenvref) eq 'HASH') {
7577: $toolstatus = $userenvref->{$envkey};
7578: $inststatus = $userenvref->{'inststatus'};
7579: } else {
7580: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7581: $toolstatus = $userenv{$envkey};
7582: $inststatus = $userenv{'inststatus'};
7583: }
7584: }
7585:
7586: if ($toolstatus ne '') {
7587: if ($toolstatus) {
7588: $access = 1;
7589: } else {
7590: $access = 0;
7591: }
7592: return $access;
7593: }
7594:
7595: my ($is_adv,%domdef);
7596: if (ref($is_advref) eq 'HASH') {
7597: $is_adv = $is_advref->{'is_adv'};
7598: } else {
7599: $is_adv = &is_advanced_user($udom,$uname);
7600: }
7601: if (ref($domdefref) eq 'HASH') {
7602: %domdef = %{$domdefref};
7603: } else {
7604: %domdef = &get_domain_defaults($udom);
7605: }
7606: if (ref($domdef{$tool}) eq 'HASH') {
7607: if ($is_adv) {
7608: if ($domdef{$tool}{'_LC_adv'} ne '') {
7609: if ($domdef{$tool}{'_LC_adv'}) {
7610: $access = 1;
7611: } else {
7612: $access = 0;
7613: }
7614: return $access;
7615: }
7616: }
7617: if ($inststatus ne '') {
7618: my ($hasaccess,$hasnoaccess);
7619: foreach my $affiliation (split(/:/,$inststatus)) {
7620: if ($domdef{$tool}{$affiliation} ne '') {
7621: if ($domdef{$tool}{$affiliation}) {
7622: $hasaccess = 1;
7623: } else {
7624: $hasnoaccess = 1;
7625: }
7626: }
7627: }
7628: if ($hasaccess || $hasnoaccess) {
7629: if ($hasaccess) {
7630: $access = 1;
7631: } elsif ($hasnoaccess) {
7632: $access = 0;
7633: }
7634: return $access;
7635: }
7636: } else {
7637: if ($domdef{$tool}{'default'} ne '') {
7638: if ($domdef{$tool}{'default'}) {
7639: $access = 1;
7640: } elsif ($domdef{$tool}{'default'} == 0) {
7641: $access = 0;
7642: }
7643: return $access;
7644: }
7645: }
7646: } else {
7647: if (($context eq 'tools') && ($tool ne 'webdav')) {
7648: $access = 1;
7649: } else {
7650: $access = 0;
7651: }
7652: return $access;
7653: }
7654: }
7655:
7656: sub is_course_owner {
7657: my ($cdom,$cnum,$udom,$uname) = @_;
7658: if (($udom eq '') || ($uname eq '')) {
7659: $udom = $env{'user.domain'};
7660: $uname = $env{'user.name'};
7661: }
7662: unless (($udom eq '') || ($uname eq '')) {
7663: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7664: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7665: return 1;
7666: } else {
7667: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7668: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7669: return 1;
7670: }
7671: }
7672: }
7673: }
7674: return;
7675: }
7676:
7677: sub is_advanced_user {
7678: my ($udom,$uname) = @_;
7679: if ($udom ne '' && $uname ne '') {
7680: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7681: if (wantarray) {
7682: return ($env{'user.adv'},$env{'user.author'});
7683: } else {
7684: return $env{'user.adv'};
7685: }
7686: }
7687: }
7688: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7689: my %allroles;
7690: my ($is_adv,$is_author);
7691: foreach my $role (keys(%roleshash)) {
7692: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7693: my $area = '/'.$tdomain.'/'.$trest;
7694: if ($sec ne '') {
7695: $area .= '/'.$sec;
7696: }
7697: if (($area ne '') && ($trole ne '')) {
7698: my $spec=$trole.'.'.$area;
7699: if ($trole =~ /^cr\//) {
7700: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7701: } elsif ($trole ne 'gr') {
7702: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7703: }
7704: if ($trole eq 'au') {
7705: $is_author = 1;
7706: }
7707: }
7708: }
7709: foreach my $role (keys(%allroles)) {
7710: last if ($is_adv);
7711: foreach my $item (split(/:/,$allroles{$role})) {
7712: if ($item ne '') {
7713: my ($privilege,$restrictions)=split(/&/,$item);
7714: if ($privilege eq 'adv') {
7715: $is_adv = 1;
7716: last;
7717: }
7718: }
7719: }
7720: }
7721: if (wantarray) {
7722: return ($is_adv,$is_author);
7723: }
7724: return $is_adv;
7725: }
7726:
7727: sub check_can_request {
7728: my ($dom,$can_request,$request_domains) = @_;
7729: my $canreq = 0;
7730: my ($types,$typename) = &Apache::loncommon::course_types();
7731: my @options = ('approval','validate','autolimit');
7732: my $optregex = join('|',@options);
7733: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7734: foreach my $type (@{$types}) {
7735: if (&usertools_access($env{'user.name'},
7736: $env{'user.domain'},
7737: $type,undef,'requestcourses')) {
7738: $canreq ++;
7739: if (ref($request_domains) eq 'HASH') {
7740: push(@{$request_domains->{$type}},$env{'user.domain'});
7741: }
7742: if ($dom eq $env{'user.domain'}) {
7743: $can_request->{$type} = 1;
7744: }
7745: }
7746: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7747: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7748: if (@curr > 0) {
7749: foreach my $item (@curr) {
7750: if (ref($request_domains) eq 'HASH') {
7751: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7752: if ($otherdom ne '') {
7753: if (ref($request_domains->{$type}) eq 'ARRAY') {
7754: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7755: push(@{$request_domains->{$type}},$otherdom);
7756: }
7757: } else {
7758: push(@{$request_domains->{$type}},$otherdom);
7759: }
7760: }
7761: }
7762: }
7763: unless($dom eq $env{'user.domain'}) {
7764: $canreq ++;
7765: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7766: $can_request->{$type} = 1;
7767: }
7768: }
7769: }
7770: }
7771: }
7772: }
7773: return $canreq;
7774: }
7775:
7776: # ---------------------------------------------- Custom access rule evaluation
7777:
7778: sub customaccess {
7779: my ($priv,$uri)=@_;
7780: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
7781: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
7782: $udom = &LONCAPA::clean_domain($udom);
7783: $ucrs = &LONCAPA::clean_username($ucrs);
7784: my $access=0;
7785: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
7786: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7787: if ($type eq 'user') {
7788: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7789: my ($tdom,$tuname)=split(m{/},$scope);
7790: if ($tdom) {
7791: if ($tdom ne $env{'user.domain'}) { next; }
7792: }
7793: if ($tuname) {
7794: if ($tuname ne $env{'user.name'}) { next; }
7795: }
7796: $access=($effect eq 'allow');
7797: last;
7798: }
7799: } else {
7800: if ($role) {
7801: if ($role ne $urole) { next; }
7802: }
7803: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7804: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7805: if ($tdom) {
7806: if ($tdom ne $udom) { next; }
7807: }
7808: if ($tcrs) {
7809: if ($tcrs ne $ucrs) { next; }
7810: }
7811: if ($tsec) {
7812: if ($tsec ne $usec) { next; }
7813: }
7814: $access=($effect eq 'allow');
7815: last;
7816: }
7817: if ($realm eq '' && $role eq '') {
7818: $access=($effect eq 'allow');
7819: }
7820: }
7821: }
7822: return $access;
7823: }
7824:
7825: # ------------------------------------------------- Check for a user privilege
7826:
7827: sub allowed {
7828: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
7829: my $ver_orguri=$uri;
7830: $uri=&deversion($uri);
7831: my $orguri=$uri;
7832: $uri=&declutter($uri);
7833:
7834: if ($priv eq 'evb') {
7835: # Evade communication block restrictions for specified role in a course
7836: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7837: return $1;
7838: } else {
7839: return;
7840: }
7841: }
7842:
7843: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
7844: # Free bre access to adm and meta resources
7845: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
7846: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7847: && ($priv eq 'bre')) {
7848: return 'F';
7849: }
7850:
7851: # Free bre access to user's own portfolio contents
7852: my ($space,$domain,$name,@dir)=split('/',$uri);
7853: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
7854: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
7855: my %setters;
7856: my ($startblock,$endblock) =
7857: &Apache::loncommon::blockcheck(\%setters,'port');
7858: if ($startblock && $endblock) {
7859: return 'B';
7860: } else {
7861: return 'F';
7862: }
7863: }
7864:
7865: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
7866: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7867: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7868: if (exists($env{'request.course.id'})) {
7869: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7870: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7871: if (($domain eq $cdom) && ($name eq $cnum)) {
7872: my $courseprivid=$env{'request.course.id'};
7873: $courseprivid=~s/\_/\//;
7874: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7875: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7876: return $1;
7877: } else {
7878: if ($env{'request.course.sec'}) {
7879: $courseprivid.='/'.$env{'request.course.sec'};
7880: }
7881: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7882: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7883: return $2;
7884: }
7885: }
7886: }
7887: }
7888: }
7889:
7890: # Free bre to public access
7891:
7892: if ($priv eq 'bre') {
7893: my $copyright=&metadata($uri,'copyright');
7894: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
7895: return 'F';
7896: }
7897: if ($copyright eq 'priv') {
7898: $uri=~/([^\/]+)\/([^\/]+)\//;
7899: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
7900: return '';
7901: }
7902: }
7903: if ($copyright eq 'domain') {
7904: $uri=~/([^\/]+)\/([^\/]+)\//;
7905: unless (($env{'user.domain'} eq $1) ||
7906: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
7907: return '';
7908: }
7909: }
7910: if ($env{'request.role'}=~ /li\.\//) {
7911: # Library role, so allow browsing of resources in this domain.
7912: return 'F';
7913: }
7914: if ($copyright eq 'custom') {
7915: unless (&customaccess($priv,$uri)) { return ''; }
7916: }
7917: }
7918: # Domain coordinator is trying to create a course
7919: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
7920: # uri is the requested domain in this case.
7921: # comparison to 'request.role.domain' shows if the user has selected
7922: # a role of dc for the domain in question.
7923: return 'F' if ($uri eq $env{'request.role.domain'});
7924: }
7925:
7926: my $thisallowed='';
7927: my $statecond=0;
7928: my $courseprivid='';
7929:
7930: my $ownaccess;
7931: # Community Coordinator or Assistant Co-author browsing resource space.
7932: if (($priv eq 'bro') && ($env{'user.author'})) {
7933: if ($uri eq '') {
7934: $ownaccess = 1;
7935: } else {
7936: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7937: my $udom = $env{'user.domain'};
7938: my $uname = $env{'user.name'};
7939: if ($uri =~ m{^\Q$udom\E/?$}) {
7940: $ownaccess = 1;
7941: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
7942: unless ($uri =~ m{\.\./}) {
7943: $ownaccess = 1;
7944: }
7945: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7946: my $now = time;
7947: if ($uri =~ m{^([^/]+)/?$}) {
7948: my $adom = $1;
7949: foreach my $key (keys(%env)) {
7950: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
7951: my ($start,$end) = split('.',$env{$key});
7952: if (($now >= $start) && (!$end || $end < $now)) {
7953: $ownaccess = 1;
7954: last;
7955: }
7956: }
7957: }
7958: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7959: my $adom = $1;
7960: my $aname = $2;
7961: foreach my $role ('ca','aa') {
7962: if ($env{"user.role.$role./$adom/$aname"}) {
7963: my ($start,$end) =
7964: split('.',$env{"user.role.$role./$adom/$aname"});
7965: if (($now >= $start) && (!$end || $end < $now)) {
7966: $ownaccess = 1;
7967: last;
7968: }
7969: }
7970: }
7971: }
7972: }
7973: }
7974: }
7975: }
7976:
7977: # Course
7978:
7979: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
7980: unless (($priv eq 'bro') && (!$ownaccess)) {
7981: $thisallowed.=$1;
7982: }
7983: }
7984:
7985: # Domain
7986:
7987: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
7988: =~/\Q$priv\E\&([^\:]*)/) {
7989: unless (($priv eq 'bro') && (!$ownaccess)) {
7990: $thisallowed.=$1;
7991: }
7992: }
7993:
7994: # User who is not author or co-author might still be able to edit
7995: # resource of an author in the domain (e.g., if Domain Coordinator).
7996: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7997: (&allowed('mdc',$env{'request.course.id'}))) {
7998: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7999: $thisallowed.=$1;
8000: }
8001: }
8002:
8003: # Course: uri itself is a course
8004: my $courseuri=$uri;
8005: $courseuri=~s/\_(\d)/\/$1/;
8006: $courseuri=~s/^([^\/])/\/$1/;
8007:
8008: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
8009: =~/\Q$priv\E\&([^\:]*)/) {
8010: if ($priv eq 'mip') {
8011: my $rem = $1;
8012: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8013: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8014: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8015: if ($cdom ne '') {
8016: my %passwdconf = &get_passwdconf($cdom);
8017: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8018: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8019: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8020: my @inststatuses = split(':',$env{'environment.inststatus'});
8021: unless (@inststatuses) {
8022: @inststatuses = ('default');
8023: }
8024: foreach my $status (@inststatuses) {
8025: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8026: $thisallowed.=$rem;
8027: }
8028: }
8029: }
8030: }
8031: }
8032: }
8033: }
8034: } else {
8035: unless (($priv eq 'bro') && (!$ownaccess)) {
8036: $thisallowed.=$1;
8037: }
8038: }
8039: }
8040:
8041: # URI is an uploaded document for this course, default permissions don't matter
8042: # not allowing 'edit' access (editupload) to uploaded course docs
8043: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
8044: $thisallowed='';
8045: my ($match)=&is_on_map($uri);
8046: if ($match) {
8047: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8048: =~/\Q$priv\E\&([^\:]*)/) {
8049: my $value = $1;
8050: if ($noblockcheck) {
8051: $thisallowed.=$value;
8052: } else {
8053: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8054: if (@blockers > 0) {
8055: $thisallowed = 'B';
8056: } else {
8057: $thisallowed.=$value;
8058: }
8059: }
8060: }
8061: } else {
8062: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
8063: if ($refuri) {
8064: if ($refuri =~ m|^/adm/|) {
8065: $thisallowed='F';
8066: } else {
8067: $refuri=&declutter($refuri);
8068: my ($match) = &is_on_map($refuri);
8069: if ($match) {
8070: if ($noblockcheck) {
8071: $thisallowed='F';
8072: } else {
8073: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8074: if (@blockers > 0) {
8075: $thisallowed = 'B';
8076: } else {
8077: $thisallowed='F';
8078: }
8079: }
8080: }
8081: }
8082: }
8083: }
8084: }
8085:
8086: if ($priv eq 'bre'
8087: && $thisallowed ne 'F'
8088: && $thisallowed ne '2'
8089: && &is_portfolio_url($uri)) {
8090: $thisallowed = &portfolio_access($uri,$clientip);
8091: }
8092:
8093: # Full access at system, domain or course-wide level? Exit.
8094: if ($thisallowed=~/F/) {
8095: return 'F';
8096: }
8097:
8098: # If this is generating or modifying users, exit with special codes
8099:
8100: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8101: if (($priv eq 'cca') || ($priv eq 'caa')) {
8102: my ($audom,$auname)=split('/',$uri);
8103: # no author name given, so this just checks on the general right to make a co-author in this domain
8104: unless ($auname) { return $thisallowed; }
8105: # an author name is given, so we are about to actually make a co-author for a certain account
8106: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8107: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8108: ($audom ne $env{'request.role.domain'}))) { return ''; }
8109: }
8110: return $thisallowed;
8111: }
8112: #
8113: # Gathered so far: system, domain and course wide privileges
8114: #
8115: # Course: See if uri or referer is an individual resource that is part of
8116: # the course
8117:
8118: if ($env{'request.course.id'}) {
8119:
8120: # If this is modifying password (internal auth) domains must match for user and user's role.
8121:
8122: if ($priv eq 'mip') {
8123: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8124: return $thisallowed;
8125: } else {
8126: return '';
8127: }
8128: }
8129:
8130: $courseprivid=$env{'request.course.id'};
8131: if ($env{'request.course.sec'}) {
8132: $courseprivid.='/'.$env{'request.course.sec'};
8133: }
8134: $courseprivid=~s/\_/\//;
8135: my $checkreferer=1;
8136: my ($match,$cond)=&is_on_map($uri);
8137: if ($match) {
8138: $statecond=$cond;
8139: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8140: =~/\Q$priv\E\&([^\:]*)/) {
8141: my $value = $1;
8142: if ($priv eq 'bre') {
8143: if ($noblockcheck) {
8144: $thisallowed.=$value;
8145: } else {
8146: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8147: if (@blockers > 0) {
8148: $thisallowed = 'B';
8149: } else {
8150: $thisallowed.=$value;
8151: }
8152: }
8153: } else {
8154: $thisallowed.=$value;
8155: }
8156: $checkreferer=0;
8157: }
8158: }
8159:
8160: if ($checkreferer) {
8161: my $refuri=$env{'httpref.'.$orguri};
8162: unless ($refuri) {
8163: foreach my $key (keys(%env)) {
8164: if ($key=~/^httpref\..*\*/) {
8165: my $pattern=$key;
8166: $pattern=~s/^httpref\.\/res\///;
8167: $pattern=~s/\*/\[\^\/\]\+/g;
8168: $pattern=~s/\//\\\//g;
8169: if ($orguri=~/$pattern/) {
8170: $refuri=$env{$key};
8171: }
8172: }
8173: }
8174: }
8175:
8176: if ($refuri) {
8177: $refuri=&declutter($refuri);
8178: my ($match,$cond)=&is_on_map($refuri);
8179: if ($match) {
8180: my $refstatecond=$cond;
8181: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8182: =~/\Q$priv\E\&([^\:]*)/) {
8183: my $value = $1;
8184: if ($priv eq 'bre') {
8185: if ($noblockcheck) {
8186: $thisallowed.=$value;
8187: } else {
8188: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8189: if (@blockers > 0) {
8190: $thisallowed = 'B';
8191: } else {
8192: $thisallowed.=$value;
8193: }
8194: }
8195: } else {
8196: $thisallowed.=$value;
8197: }
8198: $uri=$refuri;
8199: $statecond=$refstatecond;
8200: }
8201: }
8202: }
8203: }
8204: }
8205:
8206: #
8207: # Gathered now: all privileges that could apply, and condition number
8208: #
8209: #
8210: # Full or no access?
8211: #
8212:
8213: if ($thisallowed=~/F/) {
8214: return 'F';
8215: }
8216:
8217: unless ($thisallowed) {
8218: return '';
8219: }
8220:
8221: # Restrictions exist, deal with them
8222: #
8223: # C:according to course preferences
8224: # R:according to resource settings
8225: # L:unless locked
8226: # X:according to user session state
8227: #
8228:
8229: # Possibly locked functionality, check all courses
8230: # Locks might take effect only after 10 minutes cache expiration for other
8231: # courses, and 2 minutes for current course
8232:
8233: my $envkey;
8234: if ($thisallowed=~/L/) {
8235: foreach $envkey (keys(%env)) {
8236: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8237: my $courseid=$2;
8238: my $roleid=$1.'.'.$2;
8239: $courseid=~s/^\///;
8240: my $expiretime=600;
8241: if ($env{'request.role'} eq $roleid) {
8242: $expiretime=120;
8243: }
8244: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8245: my $prefix='course.'.$cdom.'_'.$cnum.'.';
8246: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
8247: &coursedescription($courseid,{'freshen_cache' => 1});
8248: }
8249: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8250: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8251: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8252: &log($env{'user.domain'},$env{'user.name'},
8253: $env{'user.home'},
8254: 'Locked by res: '.$priv.' for '.$uri.' due to '.
8255: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8256: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8257: return '';
8258: }
8259: }
8260: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8261: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8262: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8263: &log($env{'user.domain'},$env{'user.name'},
8264: $env{'user.home'},
8265: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
8266: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8267: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8268: return '';
8269: }
8270: }
8271: }
8272: }
8273: }
8274:
8275: #
8276: # Rest of the restrictions depend on selected course
8277: #
8278:
8279: unless ($env{'request.course.id'}) {
8280: if ($thisallowed eq 'A') {
8281: return 'A';
8282: } elsif ($thisallowed eq 'B') {
8283: return 'B';
8284: } else {
8285: return '1';
8286: }
8287: }
8288:
8289: #
8290: # Now user is definitely in a course
8291: #
8292:
8293:
8294: # Course preferences
8295:
8296: if ($thisallowed=~/C/) {
8297: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8298: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8299: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
8300: =~/\Q$rolecode\E/) {
8301: if (($priv ne 'pch') && ($priv ne 'plc')) {
8302: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8303: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8304: $env{'request.course.id'});
8305: }
8306: return '';
8307: }
8308:
8309: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
8310: =~/\Q$unamedom\E/) {
8311: if (($priv ne 'pch') && ($priv ne 'plc')) {
8312: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8313: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8314: $env{'request.course.id'});
8315: }
8316: return '';
8317: }
8318: }
8319:
8320: # Resource preferences
8321:
8322: if ($thisallowed=~/R/) {
8323: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8324: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
8325: if (($priv ne 'pch') && ($priv ne 'plc')) {
8326: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8327: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8328: }
8329: return '';
8330: }
8331: }
8332:
8333: # Restricted by state or randomout?
8334:
8335: if ($thisallowed=~/X/) {
8336: if ($env{'acc.randomout'}) {
8337: if (!$symb) { $symb=&symbread($uri,1); }
8338: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
8339: return '';
8340: }
8341: }
8342: if (&condval($statecond)) {
8343: return '2';
8344: } else {
8345: return '';
8346: }
8347: }
8348:
8349: if ($thisallowed eq 'A') {
8350: return 'A';
8351: } elsif ($thisallowed eq 'B') {
8352: return 'B';
8353: }
8354: return 'F';
8355: }
8356:
8357: # ------------------------------------------- Check construction space access
8358:
8359: sub constructaccess {
8360: my ($url,$setpriv)=@_;
8361:
8362: # We do not allow editing of previous versions of files
8363: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8364:
8365: # Get username and domain from URL
8366: my ($ownername,$ownerdomain,$ownerhome);
8367:
8368: ($ownerdomain,$ownername) =
8369: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
8370:
8371: # The URL does not really point to any authorspace, forget it
8372: unless (($ownername) && ($ownerdomain)) { return ''; }
8373:
8374: # Now we need to see if the user has access to the authorspace of
8375: # $ownername at $ownerdomain
8376:
8377: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8378: # Real author for this?
8379: $ownerhome = $env{'user.home'};
8380: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8381: return ($ownername,$ownerdomain,$ownerhome);
8382: }
8383: } else {
8384: # Co-author for this?
8385: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8386: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8387: $ownerhome = &homeserver($ownername,$ownerdomain);
8388: return ($ownername,$ownerdomain,$ownerhome);
8389: }
8390: }
8391:
8392: # We don't have any access right now. If we are not possibly going to do anything about this,
8393: # we might as well leave
8394: unless ($setpriv) { return ''; }
8395:
8396: # Backdoor access?
8397: my $allowed=&allowed('eco',$ownerdomain);
8398: # Nope
8399: unless ($allowed) { return ''; }
8400: # Looks like we may have access, but could be locked by the owner of the construction space
8401: if ($allowed eq 'U') {
8402: my %blocked=&get('environment',['domcoord.author'],
8403: $ownerdomain,$ownername);
8404: # Is blocked by owner
8405: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8406: }
8407: if (($allowed eq 'F') || ($allowed eq 'U')) {
8408: # Grant temporary access
8409: my $then=$env{'user.login.time'};
8410: my $update=$env{'user.update.time'};
8411: if (!$update) { $update = $then; }
8412: my $refresh=$env{'user.refresh.time'};
8413: if (!$refresh) { $refresh = $update; }
8414: my $now = time;
8415: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8416: $now,'ca','constructaccess');
8417: $ownerhome = &homeserver($ownername,$ownerdomain);
8418: return($ownername,$ownerdomain,$ownerhome);
8419: }
8420: # No business here
8421: return '';
8422: }
8423:
8424: # ----------------------------------------------------------- Content Blocking
8425:
8426: {
8427: # Caches for faster Course Contents display where content blocking
8428: # is in operation (i.e., interval param set) for timed quiz.
8429: #
8430: # User for whom data are being temporarily cached.
8431: my $cacheduser='';
8432: # Course for which data are being temporarily cached.
8433: my $cachedcid='';
8434: # Cached blockers for this user (a hash of blocking items).
8435: my %cachedblockers=();
8436: # When the data were last cached.
8437: my $cachedlast='';
8438:
8439: sub load_all_blockers {
8440: my ($uname,$udom)=@_;
8441: if (($uname ne '') && ($udom ne '')) {
8442: if (($cacheduser eq $uname.':'.$udom) &&
8443: ($cachedcid eq $env{'request.course.id'}) &&
8444: (abs($cachedlast-time)<5)) {
8445: return;
8446: }
8447: }
8448: $cachedlast=time;
8449: $cacheduser=$uname.':'.$udom;
8450: $cachedcid=$env{'request.course.id'};
8451: %cachedblockers = &get_commblock_resources();
8452: return;
8453: }
8454:
8455: sub get_comm_blocks {
8456: my ($cdom,$cnum) = @_;
8457: if ($cdom eq '' || $cnum eq '') {
8458: return unless ($env{'request.course.id'});
8459: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8460: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8461: }
8462: my %commblocks;
8463: my $hashid=$cdom.'_'.$cnum;
8464: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8465: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8466: %commblocks = %{$blocksref};
8467: } else {
8468: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8469: my $cachetime = 600;
8470: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8471: }
8472: return %commblocks;
8473: }
8474:
8475: sub get_commblock_resources {
8476: my ($blocks) = @_;
8477: my %blockers = ();
8478: return %blockers unless ($env{'request.course.id'});
8479: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8480: my %commblocks;
8481: if (ref($blocks) eq 'HASH') {
8482: %commblocks = %{$blocks};
8483: } else {
8484: %commblocks = &get_comm_blocks();
8485: }
8486: return %blockers unless (keys(%commblocks) > 0);
8487: my $navmap = Apache::lonnavmaps::navmap->new();
8488: return %blockers unless (ref($navmap));
8489: my $now = time;
8490: foreach my $block (keys(%commblocks)) {
8491: if ($block =~ /^(\d+)____(\d+)$/) {
8492: my ($start,$end) = ($1,$2);
8493: if ($start <= $now && $end >= $now) {
8494: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8495: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8496: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8497: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8498: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8499: }
8500: }
8501: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8502: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8503: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8504: }
8505: }
8506: }
8507: }
8508: }
8509: } elsif ($block =~ /^firstaccess____(.+)$/) {
8510: my $item = $1;
8511: my @to_test;
8512: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8513: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8514: my @interval;
8515: my $type = 'map';
8516: if ($item eq 'course') {
8517: $type = 'course';
8518: @interval=&EXT("resource.0.interval");
8519: } else {
8520: if ($item =~ /___\d+___/) {
8521: $type = 'resource';
8522: @interval=&EXT("resource.0.interval",$item);
8523: if (ref($navmap)) {
8524: my $res = $navmap->getBySymb($item);
8525: push(@to_test,$res);
8526: }
8527: } else {
8528: my $mapsymb = &symbread($item,1);
8529: if ($mapsymb) {
8530: if (ref($navmap)) {
8531: my $mapres = $navmap->getBySymb($mapsymb);
8532: if (ref($mapres)) {
8533: my $first = $mapres->map_start();
8534: my $finish = $mapres->map_finish();
8535: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8536: if (ref($it)) {
8537: my $res;
8538: while ($res = $it->next(undef,1)) {
8539: next unless (ref($res));
8540: my $symb = $res->symb();
8541: next if (($symb eq $mapsymb) || ($symb eq ''));
8542: @interval=&EXT("resource.0.interval",$symb);
8543: if ($interval[1] eq 'map') {
8544: if ($res->answerable()) {
8545: push(@to_test,$res);
8546: last;
8547: }
8548: }
8549: }
8550: }
8551: }
8552: }
8553: }
8554: }
8555: }
8556: if ($interval[0] =~ /^\d+$/) {
8557: my $first_access;
8558: if ($type eq 'resource') {
8559: $first_access=&get_first_access($interval[1],$item);
8560: } elsif ($type eq 'map') {
8561: $first_access=&get_first_access($interval[1],undef,$item);
8562: } else {
8563: $first_access=&get_first_access($interval[1]);
8564: }
8565: if ($first_access) {
8566: my $timesup = $first_access+$interval[0];
8567: if ($timesup > $now) {
8568: my $activeblock;
8569: foreach my $res (@to_test) {
8570: if ($res->answerable()) {
8571: $activeblock = 1;
8572: last;
8573: }
8574: }
8575: if ($activeblock) {
8576: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8577: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8578: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8579: }
8580: }
8581: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8582: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8583: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8584: }
8585: }
8586: }
8587: }
8588: }
8589: }
8590: }
8591: }
8592: }
8593: }
8594: return %blockers;
8595: }
8596:
8597: sub has_comm_blocking {
8598: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
8599: my @blockers;
8600: return unless ($env{'request.course.id'});
8601: return unless ($priv eq 'bre');
8602: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8603: return if ($env{'request.state'} eq 'construct');
8604: my %blockinfo;
8605: if (ref($blocks) eq 'HASH') {
8606: %blockinfo = &get_commblock_resources($blocks);
8607: } else {
8608: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8609: %blockinfo = %cachedblockers;
8610: }
8611: return unless (keys(%blockinfo) > 0);
8612: my (%possibles,@symbs);
8613: if (!$symb) {
8614: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
8615: }
8616: if ($symb) {
8617: @symbs = ($symb);
8618: } elsif (keys(%possibles)) {
8619: @symbs = keys(%possibles);
8620: }
8621: my $noblock;
8622: foreach my $symb (@symbs) {
8623: last if ($noblock);
8624: my ($map,$resid,$resurl)=&decode_symb($symb);
8625: foreach my $block (keys(%blockinfo)) {
8626: if ($block =~ /^firstaccess____(.+)$/) {
8627: my $item = $1;
8628: unless ($blocked) {
8629: if (($item eq $map) || ($item eq $symb)) {
8630: $noblock = 1;
8631: last;
8632: }
8633: }
8634: }
8635: if (ref($blockinfo{$block}) eq 'HASH') {
8636: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8637: if ($blockinfo{$block}{'resources'}{$symb}) {
8638: unless (grep(/^\Q$block\E$/,@blockers)) {
8639: push(@blockers,$block);
8640: }
8641: }
8642: }
8643: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8644: if ($blockinfo{$block}{'maps'}{$map}) {
8645: unless (grep(/^\Q$block\E$/,@blockers)) {
8646: push(@blockers,$block);
8647: }
8648: }
8649: }
8650: }
8651: }
8652: }
8653: unless ($noblock) {
8654: return @blockers;
8655: }
8656: return;
8657: }
8658: }
8659:
8660: # -------------------------------- Deversion and split uri into path an filename
8661:
8662: #
8663: # Removes the version from a URI and
8664: # splits it in to its filename and path to the filename.
8665: # Seems like File::Basename could have done this more clearly.
8666: # Parameters:
8667: # $uri - input URI
8668: # Returns:
8669: # Two element list consisting of
8670: # $pathname - the URI up to and excluding the trailing /
8671: # $filename - The part of the URI following the last /
8672: # NOTE:
8673: # Another realization of this is simply:
8674: # use File::Basename;
8675: # ...
8676: # $uri = shift;
8677: # $filename = basename($uri);
8678: # $path = dirname($uri);
8679: # return ($filename, $path);
8680: #
8681: # The implementation below is probably faster however.
8682: #
8683: sub split_uri_for_cond {
8684: my $uri=&deversion(&declutter(shift));
8685: my @uriparts=split(/\//,$uri);
8686: my $filename=pop(@uriparts);
8687: my $pathname=join('/',@uriparts);
8688: return ($pathname,$filename);
8689: }
8690: # --------------------------------------------------- Is a resource on the map?
8691:
8692: sub is_on_map {
8693: my ($pathname,$filename) = &split_uri_for_cond(shift);
8694: #Trying to find the conditional for the file
8695: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
8696: /\&\Q$filename\E\:([\d\|]+)\&/);
8697: if ($match) {
8698: return (1,$1);
8699: } else {
8700: return (0,0);
8701: }
8702: }
8703:
8704: # --------------------------------------------------------- Get symb from alias
8705:
8706: sub get_symb_from_alias {
8707: my $symb=shift;
8708: my ($map,$resid,$url)=&decode_symb($symb);
8709: # Already is a symb
8710: if ($url) { return $symb; }
8711: # Must be an alias
8712: my $aliassymb='';
8713: my %bighash;
8714: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8715: &GDBM_READER(),0640)) {
8716: my $rid=$bighash{'mapalias_'.$symb};
8717: if ($rid) {
8718: my ($mapid,$resid)=split(/\./,$rid);
8719: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8720: $resid,$bighash{'src_'.$rid});
8721: }
8722: untie %bighash;
8723: }
8724: return $aliassymb;
8725: }
8726:
8727: # ----------------------------------------------------------------- Define Role
8728:
8729: sub definerole {
8730: if (allowed('mcr','/')) {
8731: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
8732: foreach my $role (split(':',$sysrole)) {
8733: my ($crole,$cqual)=split(/\&/,$role);
8734: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8735: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8736: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8737: return "refused:s:$crole&$cqual";
8738: }
8739: }
8740: }
8741: foreach my $role (split(':',$domrole)) {
8742: my ($crole,$cqual)=split(/\&/,$role);
8743: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8744: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8745: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
8746: return "refused:d:$crole&$cqual";
8747: }
8748: }
8749: }
8750: foreach my $role (split(':',$courole)) {
8751: my ($crole,$cqual)=split(/\&/,$role);
8752: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8753: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8754: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8755: return "refused:c:$crole&$cqual";
8756: }
8757: }
8758: }
8759: my $uhome;
8760: if (($uname ne '') && ($udom ne '')) {
8761: $uhome = &homeserver($uname,$udom);
8762: return $uhome if ($uhome eq 'no_host');
8763: } else {
8764: $uname = $env{'user.name'};
8765: $udom = $env{'user.domain'};
8766: $uhome = $env{'user.home'};
8767: }
8768: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8769: "$udom:$uname:rolesdef_$rolename=".
8770: escape($sysrole.'_'.$domrole.'_'.$courole);
8771: return reply($command,$uhome);
8772: } else {
8773: return 'refused';
8774: }
8775: }
8776:
8777: # ---------------- Make a metadata query against the network of library servers
8778:
8779: sub metadata_query {
8780: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
8781: my %rhash;
8782: my %libserv = &all_library();
8783: my @server_list = (defined($server_array) ? @$server_array
8784: : keys(%libserv) );
8785: for my $server (@server_list) {
8786: my $domains = '';
8787: if (ref($domains_hash) eq 'HASH') {
8788: $domains = $domains_hash->{$server};
8789: }
8790: unless ($custom or $customshow) {
8791: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
8792: $rhash{$server}=$reply;
8793: }
8794: else {
8795: my $reply=&reply("querysend:".&escape($query).':'.
8796: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
8797: $server);
8798: $rhash{$server}=$reply;
8799: }
8800: }
8801: return \%rhash;
8802: }
8803:
8804: # ----------------------------------------- Send log queries and wait for reply
8805:
8806: sub log_query {
8807: my ($uname,$udom,$query,%filters)=@_;
8808: my $uhome=&homeserver($uname,$udom);
8809: if ($uhome eq 'no_host') { return 'error: no_host'; }
8810: my $uhost=&hostname($uhome);
8811: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
8812: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8813: $uhome);
8814: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
8815: return get_query_reply($queryid);
8816: }
8817:
8818: # -------------------------- Update MySQL table for portfolio file
8819:
8820: sub update_portfolio_table {
8821: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
8822: if ($group ne '') {
8823: $file_name =~s /^\Q$group\E//;
8824: }
8825: my $homeserver = &homeserver($uname,$udom);
8826: my $queryid=
8827: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8828: ':'.&escape($file_name).':'.$action,$homeserver);
8829: my $reply = &get_query_reply($queryid);
8830: return $reply;
8831: }
8832:
8833: # -------------------------- Update MySQL allusers table
8834:
8835: sub update_allusers_table {
8836: my ($uname,$udom,$names) = @_;
8837: my $homeserver = &homeserver($uname,$udom);
8838: my $queryid=
8839: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8840: 'lastname='.&escape($names->{'lastname'}).'%%'.
8841: 'firstname='.&escape($names->{'firstname'}).'%%'.
8842: 'middlename='.&escape($names->{'middlename'}).'%%'.
8843: 'generation='.&escape($names->{'generation'}).'%%'.
8844: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8845: 'id='.&escape($names->{'id'}),$homeserver);
8846: return;
8847: }
8848:
8849: # ------- Request retrieval of institutional classlists for course(s)
8850:
8851: sub fetch_enrollment_query {
8852: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
8853: my ($homeserver,$sleep,$loopmax);
8854: my $maxtries = 1;
8855: if ($context eq 'automated') {
8856: $homeserver = $perlvar{'lonHostID'};
8857: $sleep = 2;
8858: $loopmax = 100;
8859: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
8860: } else {
8861: $homeserver = &homeserver($cnum,$dom);
8862: }
8863: my $host=&hostname($homeserver);
8864: my $cmd = '';
8865: foreach my $affiliate (keys(%{$affiliatesref})) {
8866: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8867: }
8868: $cmd =~ s/%%$//;
8869: $cmd = &escape($cmd);
8870: my $query = 'fetchenrollment';
8871: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
8872: unless ($queryid=~/^\Q$host\E\_/) {
8873: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8874: return 'error: '.$queryid;
8875: }
8876: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
8877: my $tries = 1;
8878: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8879: $reply = &get_query_reply($queryid,$sleep,$loopmax);
8880: $tries ++;
8881: }
8882: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8883: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8884: } else {
8885: my @responses = split(/:/,$reply);
8886: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
8887: foreach my $line (@responses) {
8888: my ($key,$value) = split(/=/,$line,2);
8889: $$replyref{$key} = $value;
8890: }
8891: } else {
8892: my $pathname = LONCAPA::tempdir();
8893: foreach my $line (@responses) {
8894: my ($key,$value) = split(/=/,$line);
8895: $$replyref{$key} = $value;
8896: if ($value > 0) {
8897: foreach my $item (@{$$affiliatesref{$key}}) {
8898: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
8899: my $destname = $pathname.'/'.$filename;
8900: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
8901: if ($xml_classlist =~ /^error/) {
8902: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8903: } else {
8904: if ( open(FILE,">",$destname) ) {
8905: print FILE &unescape($xml_classlist);
8906: close(FILE);
8907: } else {
8908: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
8909: }
8910: }
8911: }
8912: }
8913: }
8914: }
8915: return 'ok';
8916: }
8917: return 'error';
8918: }
8919:
8920: sub get_query_reply {
8921: my ($queryid,$sleep,$loopmax) = @_;
8922: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8923: $sleep = 0.2;
8924: }
8925: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8926: $loopmax = 100;
8927: }
8928: my $replyfile=LONCAPA::tempdir().$queryid;
8929: my $reply='';
8930: for (1..$loopmax) {
8931: sleep($sleep);
8932: if (-e $replyfile.'.end') {
8933: if (open(my $fh,"<",$replyfile)) {
8934: $reply = join('',<$fh>);
8935: close($fh);
8936: } else { return 'error: reply_file_error'; }
8937: return &unescape($reply);
8938: }
8939: }
8940: return 'timeout:'.$queryid;
8941: }
8942:
8943: sub courselog_query {
8944: #
8945: # possible filters:
8946: # url: url or symb
8947: # username
8948: # domain
8949: # action: view, submit, grade
8950: # start: timestamp
8951: # end: timestamp
8952: #
8953: my (%filters)=@_;
8954: unless ($env{'request.course.id'}) { return 'no_course'; }
8955: if ($filters{'url'}) {
8956: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8957: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8958: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8959: }
8960: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8961: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8962: return &log_query($cname,$cdom,'courselog',%filters);
8963: }
8964:
8965: sub userlog_query {
8966: #
8967: # possible filters:
8968: # action: log check role
8969: # start: timestamp
8970: # end: timestamp
8971: #
8972: my ($uname,$udom,%filters)=@_;
8973: return &log_query($uname,$udom,'userlog',%filters);
8974: }
8975:
8976: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8977:
8978: sub auto_run {
8979: my ($cnum,$cdom) = @_;
8980: my $response = 0;
8981: my $settings;
8982: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8983: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8984: $settings = $domconfig{'autoenroll'};
8985: if ($settings->{'run'} eq '1') {
8986: $response = 1;
8987: }
8988: } else {
8989: my $homeserver;
8990: if (&is_course($cdom,$cnum)) {
8991: $homeserver = &homeserver($cnum,$cdom);
8992: } else {
8993: $homeserver = &domain($cdom,'primary');
8994: }
8995: if ($homeserver ne 'no_host') {
8996: $response = &reply('autorun:'.$cdom,$homeserver);
8997: }
8998: }
8999: return $response;
9000: }
9001:
9002: sub auto_get_sections {
9003: my ($cnum,$cdom,$inst_coursecode) = @_;
9004: my $homeserver;
9005: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9006: $homeserver = &homeserver($cnum,$cdom);
9007: }
9008: if (!defined($homeserver)) {
9009: if ($cdom =~ /^$match_domain$/) {
9010: $homeserver = &domain($cdom,'primary');
9011: }
9012: }
9013: my @secs;
9014: if (defined($homeserver)) {
9015: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9016: unless ($response eq 'refused') {
9017: @secs = split(/:/,$response);
9018: }
9019: }
9020: return @secs;
9021: }
9022:
9023: sub auto_new_course {
9024: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
9025: my $homeserver = &homeserver($cnum,$cdom);
9026: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
9027: return $response;
9028: }
9029:
9030: sub auto_validate_courseID {
9031: my ($cnum,$cdom,$inst_course_id) = @_;
9032: my $homeserver = &homeserver($cnum,$cdom);
9033: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
9034: return $response;
9035: }
9036:
9037: sub auto_validate_instcode {
9038: my ($cnum,$cdom,$instcode,$owner) = @_;
9039: my ($homeserver,$response);
9040: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9041: $homeserver = &homeserver($cnum,$cdom);
9042: }
9043: if (!defined($homeserver)) {
9044: if ($cdom =~ /^$match_domain$/) {
9045: $homeserver = &domain($cdom,'primary');
9046: }
9047: }
9048: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9049: &escape($instcode).':'.&escape($owner),$homeserver));
9050: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9051: return ($outcome,$description,$defaultcredits);
9052: }
9053:
9054: sub auto_create_password {
9055: my ($cnum,$cdom,$authparam,$udom) = @_;
9056: my ($homeserver,$response);
9057: my $create_passwd = 0;
9058: my $authchk = '';
9059: if ($udom =~ /^$match_domain$/) {
9060: $homeserver = &domain($udom,'primary');
9061: }
9062: if ($homeserver eq '') {
9063: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9064: $homeserver = &homeserver($cnum,$cdom);
9065: }
9066: }
9067: if ($homeserver eq '') {
9068: $authchk = 'nodomain';
9069: } else {
9070: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9071: if ($response eq 'refused') {
9072: $authchk = 'refused';
9073: } else {
9074: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
9075: }
9076: }
9077: return ($authparam,$create_passwd,$authchk);
9078: }
9079:
9080: sub auto_photo_permission {
9081: my ($cnum,$cdom,$students) = @_;
9082: my $homeserver = &homeserver($cnum,$cdom);
9083: my ($outcome,$perm_reqd,$conditions) =
9084: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
9085: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9086: return (undef,undef);
9087: }
9088: return ($outcome,$perm_reqd,$conditions);
9089: }
9090:
9091: sub auto_checkphotos {
9092: my ($uname,$udom,$pid) = @_;
9093: my $homeserver = &homeserver($uname,$udom);
9094: my ($result,$resulttype);
9095: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
9096: &escape($uname).':'.&escape($pid),
9097: $homeserver));
9098: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9099: return (undef,undef);
9100: }
9101: if ($outcome) {
9102: ($result,$resulttype) = split(/:/,$outcome);
9103: }
9104: return ($result,$resulttype);
9105: }
9106:
9107: sub auto_photochoice {
9108: my ($cnum,$cdom) = @_;
9109: my $homeserver = &homeserver($cnum,$cdom);
9110: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
9111: &escape($cdom),
9112: $homeserver)));
9113: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9114: return (undef,undef);
9115: }
9116: return ($update,$comment);
9117: }
9118:
9119: sub auto_photoupdate {
9120: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9121: my $homeserver = &homeserver($cnum,$dom);
9122: my $host=&hostname($homeserver);
9123: my $cmd = '';
9124: my $maxtries = 1;
9125: foreach my $affiliate (keys(%{$affiliatesref})) {
9126: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9127: }
9128: $cmd =~ s/%%$//;
9129: $cmd = &escape($cmd);
9130: my $query = 'institutionalphotos';
9131: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9132: unless ($queryid=~/^\Q$host\E\_/) {
9133: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9134: return 'error: '.$queryid;
9135: }
9136: my $reply = &get_query_reply($queryid);
9137: my $tries = 1;
9138: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9139: $reply = &get_query_reply($queryid);
9140: $tries ++;
9141: }
9142: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9143: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9144: } else {
9145: my @responses = split(/:/,$reply);
9146: my $outcome = shift(@responses);
9147: foreach my $item (@responses) {
9148: my ($key,$value) = split(/=/,$item);
9149: $$photo{$key} = $value;
9150: }
9151: return $outcome;
9152: }
9153: return 'error';
9154: }
9155:
9156: sub auto_instcode_format {
9157: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9158: $cat_order) = @_;
9159: my $courses = '';
9160: my @homeservers;
9161: if ($caller eq 'global') {
9162: my %servers = &get_servers($codedom,'library');
9163: foreach my $tryserver (keys(%servers)) {
9164: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9165: push(@homeservers,$tryserver);
9166: }
9167: }
9168: } elsif ($caller eq 'requests') {
9169: if ($codedom =~ /^$match_domain$/) {
9170: my $chome = &domain($codedom,'primary');
9171: unless ($chome eq 'no_host') {
9172: push(@homeservers,$chome);
9173: }
9174: }
9175: } else {
9176: push(@homeservers,&homeserver($caller,$codedom));
9177: }
9178: foreach my $code (keys(%{$instcodes})) {
9179: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
9180: }
9181: chop($courses);
9182: my $ok_response = 0;
9183: my $response;
9184: while (@homeservers > 0 && $ok_response == 0) {
9185: my $server = shift(@homeservers);
9186: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9187: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9188: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
9189: split(/:/,$response);
9190: %{$codes} = (%{$codes},&str2hash($codes_str));
9191: push(@{$codetitles},&str2array($codetitles_str));
9192: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9193: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9194: $ok_response = 1;
9195: }
9196: }
9197: if ($ok_response) {
9198: return 'ok';
9199: } else {
9200: return $response;
9201: }
9202: }
9203:
9204: sub auto_instcode_defaults {
9205: my ($domain,$returnhash,$code_order) = @_;
9206: my @homeservers;
9207:
9208: my %servers = &get_servers($domain,'library');
9209: foreach my $tryserver (keys(%servers)) {
9210: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9211: push(@homeservers,$tryserver);
9212: }
9213: }
9214:
9215: my $response;
9216: foreach my $server (@homeservers) {
9217: $response=&reply('autoinstcodedefaults:'.$domain,$server);
9218: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9219:
9220: foreach my $pair (split(/\&/,$response)) {
9221: my ($name,$value)=split(/\=/,$pair);
9222: if ($name eq 'code_order') {
9223: @{$code_order} = split(/\&/,&unescape($value));
9224: } else {
9225: $returnhash->{&unescape($name)}=&unescape($value);
9226: }
9227: }
9228: return 'ok';
9229: }
9230:
9231: return $response;
9232: }
9233:
9234: sub auto_possible_instcodes {
9235: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9236: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9237: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9238: return;
9239: }
9240: my (@homeservers,$uhome);
9241: if (defined(&domain($domain,'primary'))) {
9242: $uhome=&domain($domain,'primary');
9243: push(@homeservers,&domain($domain,'primary'));
9244: } else {
9245: my %servers = &get_servers($domain,'library');
9246: foreach my $tryserver (keys(%servers)) {
9247: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9248: push(@homeservers,$tryserver);
9249: }
9250: }
9251: }
9252: my $response;
9253: foreach my $server (@homeservers) {
9254: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9255: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9256: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9257: split(':',$response);
9258: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9259: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
9260: foreach my $item (split('&',$cat_title)) {
9261: my ($name,$value)=split('=',$item);
9262: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
9263: }
9264: foreach my $item (split('&',$cat_order)) {
9265: my ($name,$value)=split('=',$item);
9266: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
9267: }
9268: return 'ok';
9269: }
9270: return $response;
9271: }
9272:
9273: sub auto_courserequest_checks {
9274: my ($dom) = @_;
9275: my ($homeserver,%validations);
9276: if ($dom =~ /^$match_domain$/) {
9277: $homeserver = &domain($dom,'primary');
9278: }
9279: unless ($homeserver eq 'no_host') {
9280: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9281: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9282: my @items = split(/&/,$response);
9283: foreach my $item (@items) {
9284: my ($key,$value) = split('=',$item);
9285: $validations{&unescape($key)} = &thaw_unescape($value);
9286: }
9287: }
9288: }
9289: return %validations;
9290: }
9291:
9292: sub auto_courserequest_validation {
9293: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
9294: my ($homeserver,$response);
9295: if ($dom =~ /^$match_domain$/) {
9296: $homeserver = &domain($dom,'primary');
9297: }
9298: unless ($homeserver eq 'no_host') {
9299: my $customdata;
9300: if (ref($custominfo) eq 'HASH') {
9301: $customdata = &freeze_escape($custominfo);
9302: }
9303: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
9304: ':'.&escape($crstype).':'.&escape($inststatuslist).
9305: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9306: $customdata,$homeserver));
9307: }
9308: return $response;
9309: }
9310:
9311: sub auto_validate_class_sec {
9312: my ($cdom,$cnum,$owners,$inst_class) = @_;
9313: my $homeserver = &homeserver($cnum,$cdom);
9314: my $ownerlist;
9315: if (ref($owners) eq 'ARRAY') {
9316: $ownerlist = join(',',@{$owners});
9317: } else {
9318: $ownerlist = $owners;
9319: }
9320: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
9321: &escape($ownerlist).':'.$cdom,$homeserver);
9322: return $response;
9323: }
9324:
9325: sub auto_validate_instclasses {
9326: my ($cdom,$cnum,$owners,$classesref) = @_;
9327: my ($homeserver,%validations);
9328: $homeserver = &homeserver($cnum,$cdom);
9329: unless ($homeserver eq 'no_host') {
9330: my $ownerlist;
9331: if (ref($owners) eq 'ARRAY') {
9332: $ownerlist = join(',',@{$owners});
9333: } else {
9334: $ownerlist = $owners;
9335: }
9336: if (ref($classesref) eq 'HASH') {
9337: my $classes = &freeze_escape($classesref);
9338: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9339: ':'.$cdom.':'.$classes,$homeserver);
9340: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9341: my @items = split(/&/,$response);
9342: foreach my $item (@items) {
9343: my ($key,$value) = split('=',$item);
9344: $validations{&unescape($key)} = &thaw_unescape($value);
9345: }
9346: }
9347: }
9348: }
9349: return %validations;
9350: }
9351:
9352: sub auto_crsreq_update {
9353: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
9354: $code,$accessstart,$accessend,$inbound) = @_;
9355: my ($homeserver,%crsreqresponse);
9356: if ($cdom =~ /^$match_domain$/) {
9357: $homeserver = &domain($cdom,'primary');
9358: }
9359: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9360: my $info;
9361: if (ref($inbound) eq 'HASH') {
9362: $info = &freeze_escape($inbound);
9363: }
9364: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9365: ':'.&escape($action).':'.&escape($ownername).':'.
9366: &escape($ownerdomain).':'.&escape($fullname).':'.
9367: &escape($title).':'.&escape($code).':'.
9368: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
9369: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9370: my @items = split(/&/,$response);
9371: foreach my $item (@items) {
9372: my ($key,$value) = split('=',$item);
9373: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9374: }
9375: }
9376: }
9377: return \%crsreqresponse;
9378: }
9379:
9380: sub auto_export_grades {
9381: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9382: my ($homeserver,%exportresponse);
9383: if ($cdom =~ /^$match_domain$/) {
9384: $homeserver = &domain($cdom,'primary');
9385: }
9386: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9387: my $info;
9388: if (ref($inforef) eq 'HASH') {
9389: $info = &freeze_escape($inforef);
9390: }
9391: if (ref($gradesref) eq 'HASH') {
9392: my $grades = &freeze_escape($gradesref);
9393: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9394: $info.':'.$grades,$homeserver);
9395: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9396: my @items = split(/&/,$response);
9397: foreach my $item (@items) {
9398: my ($key,$value) = split('=',$item);
9399: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9400: }
9401: }
9402: }
9403: }
9404: return \%exportresponse;
9405: }
9406:
9407: sub check_instcode_cloning {
9408: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9409: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9410: return;
9411: }
9412: my $canclone;
9413: if (@{$code_order} > 0) {
9414: my $instcoderegexp ='^';
9415: my @clonecodes = split(/\&/,$cloner);
9416: foreach my $item (@{$code_order}) {
9417: if (grep(/^\Q$item\E=/,@clonecodes)) {
9418: foreach my $pair (@clonecodes) {
9419: my ($key,$val) = split(/\=/,$pair,2);
9420: $val = &unescape($val);
9421: if ($key eq $item) {
9422: $instcoderegexp .= '('.$val.')';
9423: last;
9424: }
9425: }
9426: } else {
9427: $instcoderegexp .= $codedefaults->{$item};
9428: }
9429: }
9430: $instcoderegexp .= '$';
9431: my (@from,@to);
9432: eval {
9433: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9434: (@to) = ($clonetocode =~ /$instcoderegexp/);
9435: };
9436: if ((@from > 0) && (@to > 0)) {
9437: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9438: if (!@diffs) {
9439: $canclone = 1;
9440: }
9441: }
9442: }
9443: return $canclone;
9444: }
9445:
9446: sub default_instcode_cloning {
9447: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9448: my (%codedefaults,@code_order,$canclone);
9449: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9450: %codedefaults = %{$codedefaultsref};
9451: @code_order = @{$codeorderref};
9452: } elsif ($clonedom) {
9453: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9454: }
9455: if (($domdefclone) && (@code_order)) {
9456: my @clonecodes = split(/\+/,$domdefclone);
9457: my $instcoderegexp ='^';
9458: foreach my $item (@code_order) {
9459: if (grep(/^\Q$item\E$/,@clonecodes)) {
9460: $instcoderegexp .= '('.$codedefaults{$item}.')';
9461: } else {
9462: $instcoderegexp .= $codedefaults{$item};
9463: }
9464: }
9465: $instcoderegexp .= '$';
9466: my (@from,@to);
9467: eval {
9468: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9469: (@to) = ($clonetocode =~ /$instcoderegexp/);
9470: };
9471: if ((@from > 0) && (@to > 0)) {
9472: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9473: if (!@diffs) {
9474: $canclone = 1;
9475: }
9476: }
9477: }
9478: return $canclone;
9479: }
9480:
9481: # ------------------------------------------------------- Course Group routines
9482:
9483: sub get_coursegroups {
9484: my ($cdom,$cnum,$group,$namespace) = @_;
9485: return(&dump($namespace,$cdom,$cnum,$group));
9486: }
9487:
9488: sub modify_coursegroup {
9489: my ($cdom,$cnum,$groupsettings) = @_;
9490: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9491: }
9492:
9493: sub toggle_coursegroup_status {
9494: my ($cdom,$cnum,$group,$action) = @_;
9495: my ($from_namespace,$to_namespace);
9496: if ($action eq 'delete') {
9497: $from_namespace = 'coursegroups';
9498: $to_namespace = 'deleted_groups';
9499: } else {
9500: $from_namespace = 'deleted_groups';
9501: $to_namespace = 'coursegroups';
9502: }
9503: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
9504: if (my $tmp = &error(%curr_group)) {
9505: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9506: return ('read error',$tmp);
9507: } else {
9508: my %savedsettings = %curr_group;
9509: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
9510: my $deloutcome;
9511: if ($result eq 'ok') {
9512: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
9513: } else {
9514: return ('write error',$result);
9515: }
9516: if ($deloutcome eq 'ok') {
9517: return 'ok';
9518: } else {
9519: return ('delete error',$deloutcome);
9520: }
9521: }
9522: }
9523:
9524: sub modify_group_roles {
9525: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9526: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9527: my $role = 'gr/'.&escape($userprivs);
9528: my ($uname,$udom) = split(/:/,$user);
9529: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9530: if ($result eq 'ok') {
9531: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9532: }
9533: return $result;
9534: }
9535:
9536: sub modify_coursegroup_membership {
9537: my ($cdom,$cnum,$membership) = @_;
9538: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9539: return $result;
9540: }
9541:
9542: sub get_active_groups {
9543: my ($udom,$uname,$cdom,$cnum) = @_;
9544: my $now = time;
9545: my %groups = ();
9546: foreach my $key (keys(%env)) {
9547: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9548: my ($start,$end) = split(/\./,$env{$key});
9549: if (($end!=0) && ($end<$now)) { next; }
9550: if (($start!=0) && ($start>$now)) { next; }
9551: if ($1 eq $cdom && $2 eq $cnum) {
9552: $groups{$3} = $env{$key} ;
9553: }
9554: }
9555: }
9556: return %groups;
9557: }
9558:
9559: sub get_group_membership {
9560: my ($cdom,$cnum,$group) = @_;
9561: return(&dump('groupmembership',$cdom,$cnum,$group));
9562: }
9563:
9564: sub get_users_groups {
9565: my ($udom,$uname,$courseid) = @_;
9566: my @usersgroups;
9567: my $cachetime=1800;
9568:
9569: my $hashid="$udom:$uname:$courseid";
9570: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9571: if (defined($cached)) {
9572: @usersgroups = split(/:/,$grouplist);
9573: } else {
9574: $grouplist = '';
9575: my $courseurl = &courseid_to_courseurl($courseid);
9576: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9577: my $access_end = $env{'course.'.$courseid.
9578: '.default_enrollment_end_date'};
9579: my $now = time;
9580: foreach my $key (keys(%roleshash)) {
9581: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9582: my $group = $1;
9583: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9584: my $start = $2;
9585: my $end = $1;
9586: if ($start == -1) { next; } # deleted from group
9587: if (($start!=0) && ($start>$now)) { next; }
9588: if (($end!=0) && ($end<$now)) {
9589: if ($access_end && $access_end < $now) {
9590: if ($access_end - $end < 86400) {
9591: push(@usersgroups,$group);
9592: }
9593: }
9594: next;
9595: }
9596: push(@usersgroups,$group);
9597: }
9598: }
9599: }
9600: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9601: $grouplist = join(':',@usersgroups);
9602: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9603: }
9604: return @usersgroups;
9605: }
9606:
9607: sub devalidate_getgroups_cache {
9608: my ($udom,$uname,$cdom,$cnum)=@_;
9609: my $courseid = $cdom.'_'.$cnum;
9610:
9611: my $hashid="$udom:$uname:$courseid";
9612: &devalidate_cache_new('getgroups',$hashid);
9613: }
9614:
9615: # ------------------------------------------------------------------ Plain Text
9616:
9617: sub plaintext {
9618: my ($short,$type,$cid,$forcedefault) = @_;
9619: if ($short =~ m{^cr/}) {
9620: return (split('/',$short))[-1];
9621: }
9622: if (!defined($cid)) {
9623: $cid = $env{'request.course.id'};
9624: }
9625: my %rolenames = (
9626: Course => 'std',
9627: Community => 'alt1',
9628: );
9629: if ($cid ne '') {
9630: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9631: unless ($forcedefault) {
9632: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9633: &Apache::lonlocal::mt_escape(\$roletext);
9634: return &Apache::lonlocal::mt($roletext);
9635: }
9636: }
9637: }
9638: if ((defined($type)) && (defined($rolenames{$type})) &&
9639: (defined($rolenames{$type})) &&
9640: (defined($prp{$short}{$rolenames{$type}}))) {
9641: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
9642: } elsif ($cid ne '') {
9643: my $crstype = $env{'course.'.$cid.'.type'};
9644: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9645: (defined($prp{$short}{$rolenames{$crstype}}))) {
9646: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9647: }
9648: }
9649: return &Apache::lonlocal::mt($prp{$short}{'std'});
9650: }
9651:
9652: # ----------------------------------------------------------------- Assign Role
9653:
9654: sub assignrole {
9655: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9656: $context)=@_;
9657: my $mrole;
9658: if ($role =~ /^cr\//) {
9659: my $cwosec=$url;
9660: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9661: unless (&allowed('ccr',$cwosec)) {
9662: my $refused = 1;
9663: if ($context eq 'requestcourses') {
9664: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9665: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9666: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9667: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9668: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9669: if ($crsenv{'internal.courseowner'} eq
9670: $env{'user.name'}.':'.$env{'user.domain'}) {
9671: $refused = '';
9672: }
9673: }
9674: }
9675: }
9676: }
9677: if ($refused) {
9678: &logthis('Refused custom assignrole: '.
9679: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9680: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9681: return 'refused';
9682: }
9683: }
9684: $mrole='cr';
9685: } elsif ($role =~ /^gr\//) {
9686: my $cwogrp=$url;
9687: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
9688: unless (&allowed('mdg',$cwogrp)) {
9689: &logthis('Refused group assignrole: '.
9690: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9691: $env{'user.name'}.' at '.$env{'user.domain'});
9692: return 'refused';
9693: }
9694: $mrole='gr';
9695: } else {
9696: my $cwosec=$url;
9697: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9698: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9699: my $refused;
9700: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9701: if (!(&allowed('c'.$role,$url))) {
9702: $refused = 1;
9703: }
9704: } else {
9705: $refused = 1;
9706: }
9707: if ($refused) {
9708: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9709: if (!$selfenroll && $context eq 'course') {
9710: my %crsenv;
9711: if ($role eq 'cc' || $role eq 'co') {
9712: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9713: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9714: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9715: if ($crsenv{'internal.courseowner'} eq
9716: $env{'user.name'}.':'.$env{'user.domain'}) {
9717: $refused = '';
9718: }
9719: }
9720: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9721: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9722: if ($crsenv{'internal.courseowner'} eq
9723: $env{'user.name'}.':'.$env{'user.domain'}) {
9724: $refused = '';
9725: }
9726: }
9727: }
9728: }
9729: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9730: $refused = '';
9731: } elsif ($context eq 'requestcourses') {
9732: my @possroles = ('st','ta','ep','in','cc','co');
9733: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
9734: my $wrongcc;
9735: if ($cnum =~ /^$match_community$/) {
9736: $wrongcc = 1 if ($role eq 'cc');
9737: } else {
9738: $wrongcc = 1 if ($role eq 'co');
9739: }
9740: unless ($wrongcc) {
9741: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9742: if ($crsenv{'internal.courseowner'} eq
9743: $env{'user.name'}.':'.$env{'user.domain'}) {
9744: $refused = '';
9745: }
9746: }
9747: }
9748: } elsif ($context eq 'requestauthor') {
9749: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9750: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9751: if ($env{'environment.requestauthor'} eq 'automatic') {
9752: $refused = '';
9753: } else {
9754: my %domdefaults = &get_domain_defaults($udom);
9755: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9756: my $checkbystatus;
9757: if ($env{'user.adv'}) {
9758: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9759: if ($disposition eq 'automatic') {
9760: $refused = '';
9761: } elsif ($disposition eq '') {
9762: $checkbystatus = 1;
9763: }
9764: } else {
9765: $checkbystatus = 1;
9766: }
9767: if ($checkbystatus) {
9768: if ($env{'environment.inststatus'}) {
9769: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9770: foreach my $type (@inststatuses) {
9771: if (($type ne '') &&
9772: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9773: $refused = '';
9774: }
9775: }
9776: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9777: $refused = '';
9778: }
9779: }
9780: }
9781: }
9782: }
9783: }
9784: if ($refused) {
9785: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9786: ' '.$role.' '.$end.' '.$start.' by '.
9787: $env{'user.name'}.' at '.$env{'user.domain'});
9788: return 'refused';
9789: }
9790: }
9791: } elsif ($role eq 'au') {
9792: if ($url ne '/'.$udom.'/') {
9793: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9794: ' to assign author role for '.$uname.':'.$udom.
9795: ' in domain: '.$url.' refused (wrong domain).');
9796: return 'refused';
9797: }
9798: }
9799: $mrole=$role;
9800: }
9801: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9802: "$udom:$uname:$url".'_'."$mrole=$role";
9803: if ($end) { $command.='_'.$end; }
9804: if ($start) {
9805: if ($end) {
9806: $command.='_'.$start;
9807: } else {
9808: $command.='_0_'.$start;
9809: }
9810: }
9811: my $origstart = $start;
9812: my $origend = $end;
9813: my $delflag;
9814: # actually delete
9815: if ($deleteflag) {
9816: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
9817: # modify command to delete the role
9818: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
9819: "$udom:$uname:$url".'_'."$mrole";
9820: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
9821: # set start and finish to negative values for userrolelog
9822: $start=-1;
9823: $end=-1;
9824: $delflag = 1;
9825: }
9826: }
9827: # send command
9828: my $answer=&reply($command,&homeserver($uname,$udom));
9829: # log new user role if status is ok
9830: if ($answer eq 'ok') {
9831: &userrolelog($role,$uname,$udom,$url,$start,$end);
9832: if (($role eq 'cc') || ($role eq 'in') ||
9833: ($role eq 'ep') || ($role eq 'ad') ||
9834: ($role eq 'ta') || ($role eq 'st') ||
9835: ($role=~/^cr/) || ($role eq 'gr') ||
9836: ($role eq 'co')) {
9837: # for course roles, perform group memberships changes triggered by role change.
9838: unless ($role =~ /^gr/) {
9839: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9840: $origstart,$selfenroll,$context);
9841: }
9842: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9843: $selfenroll,$context);
9844: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
9845: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9846: ($role eq 'da')) {
9847: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9848: $context);
9849: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9850: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9851: $context);
9852: }
9853: if ($role eq 'cc') {
9854: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9855: }
9856: }
9857: return $answer;
9858: }
9859:
9860: sub autoupdate_coowners {
9861: my ($url,$end,$start,$uname,$udom) = @_;
9862: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9863: if (($cdom ne '') && ($cnum ne '')) {
9864: my $now = time;
9865: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9866: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9867: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9868: my $instcode = $coursehash{'internal.coursecode'};
9869: if ($instcode ne '') {
9870: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9871: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
9872: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
9873: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9874: if ($result eq 'valid') {
9875: if ($coursehash{'internal.co-owners'}) {
9876: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9877: push(@newcoowners,$coowner);
9878: }
9879: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9880: push(@newcoowners,$uname.':'.$udom);
9881: }
9882: @newcoowners = sort(@newcoowners);
9883: } else {
9884: push(@newcoowners,$uname.':'.$udom);
9885: }
9886: } else {
9887: if ($coursehash{'internal.co-owners'}) {
9888: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9889: unless ($coowner eq $uname.':'.$udom) {
9890: push(@newcoowners,$coowner);
9891: }
9892: }
9893: unless (@newcoowners > 0) {
9894: $delcoowners = 1;
9895: $coowners = '';
9896: }
9897: }
9898: }
9899: if (@newcoowners || $delcoowners) {
9900: &store_coowners($cdom,$cnum,$coursehash{'home'},
9901: $delcoowners,@newcoowners);
9902: }
9903: }
9904: }
9905: }
9906: }
9907: }
9908: }
9909:
9910: sub store_coowners {
9911: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9912: my $cid = $cdom.'_'.$cnum;
9913: my ($coowners,$delresult,$putresult);
9914: if (@newcoowners) {
9915: $coowners = join(',',@newcoowners);
9916: my %coownershash = (
9917: 'internal.co-owners' => $coowners,
9918: );
9919: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9920: if ($putresult eq 'ok') {
9921: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9922: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9923: }
9924: }
9925: }
9926: if ($delcoowners) {
9927: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9928: if ($delresult eq 'ok') {
9929: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9930: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9931: }
9932: }
9933: }
9934: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9935: my %crsinfo =
9936: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9937: if (ref($crsinfo{$cid}) eq 'HASH') {
9938: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9939: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9940: }
9941: }
9942: }
9943:
9944: # -------------------------------------------------- Modify user authentication
9945: # Overrides without validation
9946:
9947: sub modifyuserauth {
9948: my ($udom,$uname,$umode,$upass)=@_;
9949: my $uhome=&homeserver($uname,$udom);
9950: my $allowed;
9951: if (&allowed('mau',$udom)) {
9952: $allowed = 1;
9953: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
9954: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
9955: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
9956: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9957: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9958: if (($cdom ne '') && ($cnum ne '')) {
9959: my $is_owner = &is_course_owner($cdom,$cnum);
9960: if ($is_owner) {
9961: $allowed = 1;
9962: }
9963: }
9964: }
9965: unless ($allowed) { return 'refused'; }
9966: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
9967: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9968: ' in domain '.$env{'request.role.domain'});
9969: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9970: &escape($upass),$uhome);
9971: my $ip = &get_requestor_ip();
9972: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
9973: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9974: '(Remote '.$ip.'): '.$reply);
9975: &log($udom,,$uname,$uhome,
9976: 'Authentication changed by '.$env{'user.domain'}.', '.
9977: $env{'user.name'}.', '.$umode.
9978: '(Remote '.$ip.'): '.$reply);
9979: unless ($reply eq 'ok') {
9980: &logthis('Authentication mode error: '.$reply);
9981: return 'error: '.$reply;
9982: }
9983: return 'ok';
9984: }
9985:
9986: # --------------------------------------------------------------- Modify a user
9987:
9988: sub modifyuser {
9989: my ($udom, $uname, $uid,
9990: $umode, $upass, $first,
9991: $middle, $last, $gene,
9992: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
9993: $udom= &LONCAPA::clean_domain($udom);
9994: $uname=&LONCAPA::clean_username($uname);
9995: my $showcandelete = 'none';
9996: if (ref($candelete) eq 'ARRAY') {
9997: if (@{$candelete} > 0) {
9998: $showcandelete = join(', ',@{$candelete});
9999: }
10000: }
10001: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10002: $umode.', '.$first.', '.$middle.', '.
10003: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10004: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10005: ' desiredhome not specified').
10006: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10007: ' in domain '.$env{'request.role.domain'});
10008: my $uhome=&homeserver($uname,$udom,'true');
10009: my $newuser;
10010: if ($uhome eq 'no_host') {
10011: $newuser = 1;
10012: }
10013: # ----------------------------------------------------------------- Create User
10014: if (($uhome eq 'no_host') &&
10015: (($umode && $upass) || ($umode eq 'localauth'))) {
10016: my $unhome='';
10017: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
10018: $unhome = $desiredhome;
10019: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10020: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10021: } else { # load balancing routine for determining $unhome
10022: my $loadm=10000000;
10023: my %servers = &get_servers($udom,'library');
10024: foreach my $tryserver (keys(%servers)) {
10025: my $answer=reply('load',$tryserver);
10026: if (($answer=~/\d+/) && ($answer<$loadm)) {
10027: $loadm=$answer;
10028: $unhome=$tryserver;
10029: }
10030: }
10031: }
10032: if (($unhome eq '') || ($unhome eq 'no_host')) {
10033: return 'error: unable to find a home server for '.$uname.
10034: ' in domain '.$udom;
10035: }
10036: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10037: &escape($upass),$unhome);
10038: unless ($reply eq 'ok') {
10039: return 'error: '.$reply;
10040: }
10041: $uhome=&homeserver($uname,$udom,'true');
10042: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10043: return 'error: unable verify users home machine.';
10044: }
10045: } # End of creation of new user
10046: # ---------------------------------------------------------------------- Add ID
10047: if ($uid) {
10048: $uid=~tr/A-Z/a-z/;
10049: my %uidhash=&idrget($udom,$uname);
10050: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10051: && (!$forceid)) {
10052: unless ($uid eq $uidhash{$uname}) {
10053: return 'error: user id "'.$uid.'" does not match '.
10054: 'current user id "'.$uidhash{$uname}.'".';
10055: }
10056: } else {
10057: &idput($udom,($uname => $uid));
10058: }
10059: }
10060: # -------------------------------------------------------------- Add names, etc
10061: my @tmp=&get('environment',
10062: ['firstname','middlename','lastname','generation','id',
10063: 'permanentemail','inststatus'],
10064: $udom,$uname);
10065: my (%names,%oldnames);
10066: if ($tmp[0] =~ m/^error:.*/) {
10067: %names=();
10068: } else {
10069: %names = @tmp;
10070: %oldnames = %names;
10071: }
10072: #
10073: # If name, email and/or uid are blank (e.g., because an uploaded file
10074: # of users did not contain them), do not overwrite existing values
10075: # unless field is in $candelete array ref.
10076: #
10077:
10078: my @fields = ('firstname','middlename','lastname','generation',
10079: 'permanentemail','id');
10080: my %newvalues;
10081: if (ref($candelete) eq 'ARRAY') {
10082: foreach my $field (@fields) {
10083: if (grep(/^\Q$field\E$/,@{$candelete})) {
10084: if ($field eq 'firstname') {
10085: $names{$field} = $first;
10086: } elsif ($field eq 'middlename') {
10087: $names{$field} = $middle;
10088: } elsif ($field eq 'lastname') {
10089: $names{$field} = $last;
10090: } elsif ($field eq 'generation') {
10091: $names{$field} = $gene;
10092: } elsif ($field eq 'permanentemail') {
10093: $names{$field} = $email;
10094: } elsif ($field eq 'id') {
10095: $names{$field} = $uid;
10096: }
10097: }
10098: }
10099: }
10100: if ($first) { $names{'firstname'} = $first; }
10101: if (defined($middle)) { $names{'middlename'} = $middle; }
10102: if ($last) { $names{'lastname'} = $last; }
10103: if (defined($gene)) { $names{'generation'} = $gene; }
10104: if ($email) {
10105: $email=~s/[^\w\@\.\-\,]//gs;
10106: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10107: }
10108: if ($uid) { $names{'id'} = $uid; }
10109: if (defined($inststatus)) {
10110: $names{'inststatus'} = '';
10111: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10112: if (ref($usertypes) eq 'HASH') {
10113: my @okstatuses;
10114: foreach my $item (split(/:/,$inststatus)) {
10115: if (defined($usertypes->{$item})) {
10116: push(@okstatuses,$item);
10117: }
10118: }
10119: if (@okstatuses) {
10120: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10121: }
10122: }
10123: }
10124: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10125: $umode.', '.$first.', '.$middle.', '.
10126: $last.', '.$gene.', '.$email.', '.$inststatus;
10127: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10128: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10129: } else {
10130: $logmsg .= ' during self creation';
10131: }
10132: my $changed;
10133: if ($newuser) {
10134: $changed = 1;
10135: } else {
10136: foreach my $field (@fields) {
10137: if ($names{$field} ne $oldnames{$field}) {
10138: $changed = 1;
10139: last;
10140: }
10141: }
10142: }
10143: unless ($changed) {
10144: $logmsg = 'No changes in user information needed for: '.$logmsg;
10145: &logthis($logmsg);
10146: return 'ok';
10147: }
10148: my $reply = &put('environment', \%names, $udom,$uname);
10149: if ($reply ne 'ok') {
10150: return 'error: '.$reply;
10151: }
10152: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10153: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10154: }
10155: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10156: &devalidate_cache_new('namescache',$uname.':'.$udom);
10157: $logmsg = 'Success modifying user '.$logmsg;
10158: &logthis($logmsg);
10159: return 'ok';
10160: }
10161:
10162: # -------------------------------------------------------------- Modify student
10163:
10164: sub modifystudent {
10165: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10166: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10167: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10168: if (!$cid) {
10169: unless ($cid=$env{'request.course.id'}) {
10170: return 'not_in_class';
10171: }
10172: }
10173: # --------------------------------------------------------------- Make the user
10174: my $reply=&modifyuser
10175: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10176: $desiredhome,$email,$inststatus);
10177: unless ($reply eq 'ok') { return $reply; }
10178: # This will cause &modify_student_enrollment to get the uid from the
10179: # student's environment
10180: $uid = undef if (!$forceid);
10181: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10182: $gene,$usec,$end,$start,$type,$locktype,
10183: $cid,$selfenroll,$context,$credits,$instsec);
10184: return $reply;
10185: }
10186:
10187: sub modify_student_enrollment {
10188: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10189: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10190: my ($cdom,$cnum,$chome);
10191: if (!$cid) {
10192: unless ($cid=$env{'request.course.id'}) {
10193: return 'not_in_class';
10194: }
10195: $cdom=$env{'course.'.$cid.'.domain'};
10196: $cnum=$env{'course.'.$cid.'.num'};
10197: } else {
10198: ($cdom,$cnum)=split(/_/,$cid);
10199: }
10200: $chome=$env{'course.'.$cid.'.home'};
10201: if (!$chome) {
10202: $chome=&homeserver($cnum,$cdom);
10203: }
10204: if (!$chome) { return 'unknown_course'; }
10205: # Make sure the user exists
10206: my $uhome=&homeserver($uname,$udom);
10207: if (($uhome eq '') || ($uhome eq 'no_host')) {
10208: return 'error: no such user';
10209: }
10210: # Get student data if we were not given enough information
10211: if (!defined($first) || $first eq '' ||
10212: !defined($last) || $last eq '' ||
10213: !defined($uid) || $uid eq '' ||
10214: !defined($middle) || $middle eq '' ||
10215: !defined($gene) || $gene eq '') {
10216: # They did not supply us with enough data to enroll the student, so
10217: # we need to pick up more information.
10218: my %tmp = &get('environment',
10219: ['firstname','middlename','lastname', 'generation','id']
10220: ,$udom,$uname);
10221:
10222: #foreach my $key (keys(%tmp)) {
10223: # &logthis("key $key = ".$tmp{$key});
10224: #}
10225: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10226: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10227: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
10228: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
10229: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10230: }
10231: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10232: my $user = "$uname:$udom";
10233: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10234: my $reply=cput('classlist',
10235: {$user =>
10236: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10237: $cdom,$cnum);
10238: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10239: &devalidate_getsection_cache($udom,$uname,$cid);
10240: } else {
10241: return 'error: '.$reply;
10242: }
10243: # Add student role to user
10244: my $uurl='/'.$cid;
10245: $uurl=~s/\_/\//g;
10246: if ($usec) {
10247: $uurl.='/'.$usec;
10248: }
10249: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10250: $selfenroll,$context);
10251: if ($result ne 'ok') {
10252: if ($old_entry{$user} ne '') {
10253: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10254: } else {
10255: $reply = &del('classlist',[$user],$cdom,$cnum);
10256: }
10257: }
10258: return $result;
10259: }
10260:
10261: sub format_name {
10262: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10263: my $name;
10264: if ($first ne 'lastname') {
10265: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10266: } else {
10267: if ($lastname=~/\S/) {
10268: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10269: $name=~s/\s+,/,/;
10270: } else {
10271: $name.= $firstname.' '.$middlename.' '.$generation;
10272: }
10273: }
10274: $name=~s/^\s+//;
10275: $name=~s/\s+$//;
10276: $name=~s/\s+/ /g;
10277: return $name;
10278: }
10279:
10280: # ------------------------------------------------- Write to course preferences
10281:
10282: sub writecoursepref {
10283: my ($courseid,%prefs)=@_;
10284: $courseid=~s/^\///;
10285: $courseid=~s/\_/\//g;
10286: my ($cdomain,$cnum)=split(/\//,$courseid);
10287: my $chome=homeserver($cnum,$cdomain);
10288: if (($chome eq '') || ($chome eq 'no_host')) {
10289: return 'error: no such course';
10290: }
10291: my $cstring='';
10292: foreach my $pref (keys(%prefs)) {
10293: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10294: }
10295: $cstring=~s/\&$//;
10296: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10297: }
10298:
10299: # ---------------------------------------------------------- Make/modify course
10300:
10301: sub createcourse {
10302: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10303: $course_owner,$crstype,$cnum,$context,$category)=@_;
10304: $url=&declutter($url);
10305: my $cid='';
10306: if ($context eq 'requestcourses') {
10307: my $can_create = 0;
10308: my ($ownername,$ownerdom) = split(':',$course_owner);
10309: if ($udom eq $ownerdom) {
10310: if (&usertools_access($ownername,$ownerdom,$category,undef,
10311: $context)) {
10312: $can_create = 1;
10313: }
10314: } else {
10315: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10316: $category);
10317: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10318: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10319: if (@curr > 0) {
10320: my @options = qw(approval validate autolimit);
10321: my $optregex = join('|',@options);
10322: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10323: $can_create = 1;
10324: }
10325: }
10326: }
10327: }
10328: if ($can_create) {
10329: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10330: unless (&allowed('ccc',$udom)) {
10331: return 'refused';
10332: }
10333: }
10334: } else {
10335: return 'refused';
10336: }
10337: } elsif (!&allowed('ccc',$udom)) {
10338: return 'refused';
10339: }
10340: # --------------------------------------------------------------- Get Unique ID
10341: my $uname;
10342: if ($cnum =~ /^$match_courseid$/) {
10343: my $chome=&homeserver($cnum,$udom,'true');
10344: if (($chome eq '') || ($chome eq 'no_host')) {
10345: $uname = $cnum;
10346: } else {
10347: $uname = &generate_coursenum($udom,$crstype);
10348: }
10349: } else {
10350: $uname = &generate_coursenum($udom,$crstype);
10351: }
10352: return $uname if ($uname =~ /^error/);
10353: # -------------------------------------------------- Check supplied server name
10354: if (!defined($course_server)) {
10355: if (defined(&domain($udom,'primary'))) {
10356: $course_server = &domain($udom,'primary');
10357: } else {
10358: $course_server = $env{'user.home'};
10359: }
10360: }
10361: my %host_servers =
10362: &Apache::lonnet::get_servers($udom,'library');
10363: unless ($host_servers{$course_server}) {
10364: return 'error: invalid home server for course: '.$course_server;
10365: }
10366: # ------------------------------------------------------------- Make the course
10367: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10368: $course_server);
10369: unless ($reply eq 'ok') { return 'error: '.$reply; }
10370: my $uhome=&homeserver($uname,$udom,'true');
10371: if (($uhome eq '') || ($uhome eq 'no_host')) {
10372: return 'error: no such course';
10373: }
10374: # ----------------------------------------------------------------- Course made
10375: # log existence
10376: my $now = time;
10377: my $newcourse = {
10378: $udom.'_'.$uname => {
10379: description => $description,
10380: inst_code => $inst_code,
10381: owner => $course_owner,
10382: type => $crstype,
10383: creator => $env{'user.name'}.':'.
10384: $env{'user.domain'},
10385: created => $now,
10386: context => $context,
10387: },
10388: };
10389: &courseidput($udom,$newcourse,$uhome,'notime');
10390: # set toplevel url
10391: my $topurl=$url;
10392: unless ($nonstandard) {
10393: # ------------------------------------------ For standard courses, make top url
10394: my $mapurl=&clutter($url);
10395: if ($mapurl eq '/res/') { $mapurl=''; }
10396: $env{'form.initmap'}=(<<ENDINITMAP);
10397: <map>
10398: <resource id="1" type="start"></resource>
10399: <resource id="2" src="$mapurl"></resource>
10400: <resource id="3" type="finish"></resource>
10401: <link index="1" from="1" to="2"></link>
10402: <link index="2" from="2" to="3"></link>
10403: </map>
10404: ENDINITMAP
10405: $topurl=&declutter(
10406: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10407: );
10408: }
10409: # ----------------------------------------------------------- Write preferences
10410: &writecoursepref($udom.'_'.$uname,
10411: ('description' => $description,
10412: 'url' => $topurl,
10413: 'internal.creator' => $env{'user.name'}.':'.
10414: $env{'user.domain'},
10415: 'internal.created' => $now,
10416: 'internal.creationcontext' => $context)
10417: );
10418: return '/'.$udom.'/'.$uname;
10419: }
10420:
10421: # ------------------------------------------------------------------- Create ID
10422: sub generate_coursenum {
10423: my ($udom,$crstype) = @_;
10424: my $domdesc = &domain($udom);
10425: return 'error: invalid domain' if ($domdesc eq '');
10426: my $first;
10427: if ($crstype eq 'Community') {
10428: $first = '0';
10429: } else {
10430: $first = int(1+rand(9));
10431: }
10432: my $uname=$first.
10433: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10434: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10435: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10436: # ----------------------------------------------- Make sure that does not exist
10437: my $uhome=&homeserver($uname,$udom,'true');
10438: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10439: if ($crstype eq 'Community') {
10440: $first = '0';
10441: } else {
10442: $first = int(1+rand(9));
10443: }
10444: $uname=$first.
10445: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10446: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10447: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10448: $uhome=&homeserver($uname,$udom,'true');
10449: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10450: return 'error: unable to generate unique course-ID';
10451: }
10452: }
10453: return $uname;
10454: }
10455:
10456: sub is_course {
10457: my ($cdom, $cnum) = scalar(@_) == 1 ?
10458: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10459: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10460: my $uhome=&homeserver($cnum,$cdom);
10461: my $iscourse;
10462: if (grep { $_ eq $uhome } current_machine_ids()) {
10463: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10464: } else {
10465: my $hashid = $cdom.':'.$cnum;
10466: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10467: unless (defined($cached)) {
10468: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10469: $cnum,undef,undef,'.');
10470: $iscourse = 0;
10471: if (exists($courses{$cdom.'_'.$cnum})) {
10472: $iscourse = 1;
10473: }
10474: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10475: }
10476: }
10477: return unless($iscourse);
10478: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10479: }
10480:
10481: sub store_userdata {
10482: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10483: my $result;
10484: if ($datakey ne '') {
10485: if (ref($storehash) eq 'HASH') {
10486: if ($udom eq '' || $uname eq '') {
10487: $udom = $env{'user.domain'};
10488: $uname = $env{'user.name'};
10489: }
10490: my $uhome=&homeserver($uname,$udom);
10491: if (($uhome eq '') || ($uhome eq 'no_host')) {
10492: $result = 'error: no_host';
10493: } else {
10494: $storehash->{'ip'} = &get_requestor_ip();
10495: $storehash->{'host'} = $perlvar{'lonHostID'};
10496:
10497: my $namevalue='';
10498: foreach my $key (keys(%{$storehash})) {
10499: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10500: }
10501: $namevalue=~s/\&$//;
10502: unless ($namespace eq 'courserequests') {
10503: $datakey = &escape($datakey);
10504: }
10505: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10506: $namevalue,$uhome);
10507: }
10508: } else {
10509: $result = 'error: data to store was not a hash reference';
10510: }
10511: } else {
10512: $result= 'error: invalid requestkey';
10513: }
10514: return $result;
10515: }
10516:
10517: # ---------------------------------------------------------- Assign Custom Role
10518:
10519: sub assigncustomrole {
10520: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10521: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10522: $end,$start,$deleteflag,$selfenroll,$context);
10523: }
10524:
10525: # ----------------------------------------------------------------- Revoke Role
10526:
10527: sub revokerole {
10528: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10529: my $now=time;
10530: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10531: }
10532:
10533: # ---------------------------------------------------------- Revoke Custom Role
10534:
10535: sub revokecustomrole {
10536: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10537: my $now=time;
10538: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10539: $deleteflag,$selfenroll,$context);
10540: }
10541:
10542: # ------------------------------------------------------------ Disk usage
10543: sub diskusage {
10544: my ($udom,$uname,$directorypath,$getpropath)=@_;
10545: $directorypath =~ s/\/$//;
10546: my $listing=&reply('du2:'.&escape($directorypath).':'
10547: .&escape($getpropath).':'.&escape($uname).':'
10548: .&escape($udom),homeserver($uname,$udom));
10549: if ($listing eq 'unknown_cmd') {
10550: if ($getpropath) {
10551: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10552: }
10553: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10554: }
10555: return $listing;
10556: }
10557:
10558: sub is_locked {
10559: my ($file_name, $domain, $user, $which) = @_;
10560: my @check;
10561: my $is_locked;
10562: push (@check,$file_name);
10563: my %locked = &get('file_permissions',\@check,
10564: $env{'user.domain'},$env{'user.name'});
10565: my ($tmp)=keys(%locked);
10566: if ($tmp=~/^error:/) { undef(%locked); }
10567:
10568: if (ref($locked{$file_name}) eq 'ARRAY') {
10569: $is_locked = 'false';
10570: foreach my $entry (@{$locked{$file_name}}) {
10571: if (ref($entry) eq 'ARRAY') {
10572: $is_locked = 'true';
10573: if (ref($which) eq 'ARRAY') {
10574: push(@{$which},$entry);
10575: } else {
10576: last;
10577: }
10578: }
10579: }
10580: } else {
10581: $is_locked = 'false';
10582: }
10583: return $is_locked;
10584: }
10585:
10586: sub declutter_portfile {
10587: my ($file) = @_;
10588: $file =~ s{^(/portfolio/|portfolio/)}{/};
10589: return $file;
10590: }
10591:
10592: # ------------------------------------------------------------- Mark as Read Only
10593:
10594: sub mark_as_readonly {
10595: my ($domain,$user,$files,$what) = @_;
10596: my %current_permissions = &dump('file_permissions',$domain,$user);
10597: my ($tmp)=keys(%current_permissions);
10598: if ($tmp=~/^error:/) { undef(%current_permissions); }
10599: foreach my $file (@{$files}) {
10600: $file = &declutter_portfile($file);
10601: push(@{$current_permissions{$file}},$what);
10602: }
10603: &put('file_permissions',\%current_permissions,$domain,$user);
10604: return;
10605: }
10606:
10607: # ------------------------------------------------------------Save Selected Files
10608:
10609: sub save_selected_files {
10610: my ($user, $path, @files) = @_;
10611: my $filename = $user."savedfiles";
10612: my @other_files = &files_not_in_path($user, $path);
10613: open (OUT,'>',LONCAPA::tempdir().$filename);
10614: foreach my $file (@files) {
10615: print (OUT $env{'form.currentpath'}.$file."\n");
10616: }
10617: foreach my $file (@other_files) {
10618: print (OUT $file."\n");
10619: }
10620: close (OUT);
10621: return 'ok';
10622: }
10623:
10624: sub clear_selected_files {
10625: my ($user) = @_;
10626: my $filename = $user."savedfiles";
10627: open (OUT,'>',LONCAPA::tempdir().$filename);
10628: print (OUT undef);
10629: close (OUT);
10630: return ("ok");
10631: }
10632:
10633: sub files_in_path {
10634: my ($user, $path) = @_;
10635: my $filename = $user."savedfiles";
10636: my %return_files;
10637: open (IN,'<',LONCAPA::tempdir().$filename);
10638: while (my $line_in = <IN>) {
10639: chomp ($line_in);
10640: my @paths_and_file = split (m!/!, $line_in);
10641: my $file_part = pop (@paths_and_file);
10642: my $path_part = join ('/', @paths_and_file);
10643: $path_part.='/';
10644: my $path_and_file = $path_part.$file_part;
10645: if ($path_part eq $path) {
10646: $return_files{$file_part}= 'selected';
10647: }
10648: }
10649: close (IN);
10650: return (\%return_files);
10651: }
10652:
10653: # called in portfolio select mode, to show files selected NOT in current directory
10654: sub files_not_in_path {
10655: my ($user, $path) = @_;
10656: my $filename = $user."savedfiles";
10657: my @return_files;
10658: my $path_part;
10659: open(IN, '<',LONCAPA::tempdir().$filename);
10660: while (my $line = <IN>) {
10661: #ok, I know it's clunky, but I want it to work
10662: my @paths_and_file = split(m|/|, $line);
10663: my $file_part = pop(@paths_and_file);
10664: chomp($file_part);
10665: my $path_part = join('/', @paths_and_file);
10666: $path_part .= '/';
10667: my $path_and_file = $path_part.$file_part;
10668: if ($path_part ne $path) {
10669: push(@return_files, ($path_and_file));
10670: }
10671: }
10672: close(OUT);
10673: return (@return_files);
10674: }
10675:
10676: #----------------------------------------------Get portfolio file permissions
10677:
10678: sub get_portfile_permissions {
10679: my ($domain,$user) = @_;
10680: my %current_permissions = &dump('file_permissions',$domain,$user);
10681: my ($tmp)=keys(%current_permissions);
10682: if ($tmp=~/^error:/) { undef(%current_permissions); }
10683: return \%current_permissions;
10684: }
10685:
10686: #---------------------------------------------Get portfolio file access controls
10687:
10688: sub get_access_controls {
10689: my ($current_permissions,$group,$file) = @_;
10690: my %access;
10691: my $real_file = $file;
10692: $file =~ s/\.meta$//;
10693: if (defined($file)) {
10694: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10695: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10696: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10697: }
10698: }
10699: } else {
10700: foreach my $key (keys(%{$current_permissions})) {
10701: if ($key =~ /\0accesscontrol$/) {
10702: if (defined($group)) {
10703: if ($key !~ m-^\Q$group\E/-) {
10704: next;
10705: }
10706: }
10707: my ($fullpath) = split(/\0/,$key);
10708: if (ref($$current_permissions{$key}) eq 'HASH') {
10709: foreach my $control (keys(%{$$current_permissions{$key}})) {
10710: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10711: }
10712: }
10713: }
10714: }
10715: }
10716: return %access;
10717: }
10718:
10719: sub modify_access_controls {
10720: my ($file_name,$changes,$domain,$user)=@_;
10721: my ($outcome,$deloutcome);
10722: my %store_permissions;
10723: my %new_values;
10724: my %new_control;
10725: my %translation;
10726: my @deletions = ();
10727: my $now = time;
10728: if (exists($$changes{'activate'})) {
10729: if (ref($$changes{'activate'}) eq 'HASH') {
10730: my @newitems = sort(keys(%{$$changes{'activate'}}));
10731: my $numnew = scalar(@newitems);
10732: for (my $i=0; $i<$numnew; $i++) {
10733: my $newkey = $newitems[$i];
10734: my $newid = &Apache::loncommon::get_cgi_id();
10735: if ($newkey =~ /^\d+:/) {
10736: $newkey =~ s/^(\d+)/$newid/;
10737: $translation{$1} = $newid;
10738: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10739: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10740: $translation{$1} = $newid;
10741: }
10742: $new_values{$file_name."\0".$newkey} =
10743: $$changes{'activate'}{$newitems[$i]};
10744: $new_control{$newkey} = $now;
10745: }
10746: }
10747: }
10748: my %todelete;
10749: my %changed_items;
10750: foreach my $action ('delete','update') {
10751: if (exists($$changes{$action})) {
10752: if (ref($$changes{$action}) eq 'HASH') {
10753: foreach my $key (keys(%{$$changes{$action}})) {
10754: my ($itemnum) = ($key =~ /^([^:]+):/);
10755: if ($action eq 'delete') {
10756: $todelete{$itemnum} = 1;
10757: } else {
10758: $changed_items{$itemnum} = $key;
10759: }
10760: }
10761: }
10762: }
10763: }
10764: # get lock on access controls for file.
10765: my $lockhash = {
10766: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10767: ':'.$env{'user.domain'},
10768: };
10769: my $tries = 0;
10770: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10771:
10772: while (($gotlock ne 'ok') && $tries < 10) {
10773: $tries ++;
10774: sleep(0.1);
10775: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10776: }
10777: if ($gotlock eq 'ok') {
10778: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10779: my ($tmp)=keys(%curr_permissions);
10780: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10781: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10782: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10783: if (ref($curr_controls) eq 'HASH') {
10784: foreach my $control_item (keys(%{$curr_controls})) {
10785: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10786: if (defined($todelete{$itemnum})) {
10787: push(@deletions,$file_name."\0".$control_item);
10788: } else {
10789: if (defined($changed_items{$itemnum})) {
10790: $new_control{$changed_items{$itemnum}} = $now;
10791: push(@deletions,$file_name."\0".$control_item);
10792: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10793: } else {
10794: $new_control{$control_item} = $$curr_controls{$control_item};
10795: }
10796: }
10797: }
10798: }
10799: }
10800: my ($group);
10801: if (&is_course($domain,$user)) {
10802: ($group,my $file) = split(/\//,$file_name,2);
10803: }
10804: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10805: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10806: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10807: # remove lock
10808: my @del_lock = ($file_name."\0".'locked_access_records');
10809: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10810: my $sqlresult =
10811: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10812: $group);
10813: } else {
10814: $outcome = "error: could not obtain lockfile\n";
10815: }
10816: return ($outcome,$deloutcome,\%new_values,\%translation);
10817: }
10818:
10819: sub make_public_indefinitely {
10820: my ($requrl) = @_;
10821: my $now = time;
10822: my $action = 'activate';
10823: my $aclnum = 0;
10824: if (&is_portfolio_url($requrl)) {
10825: my (undef,$udom,$unum,$file_name,$group) =
10826: &parse_portfolio_url($requrl);
10827: my $current_perms = &get_portfile_permissions($udom,$unum);
10828: my %access_controls = &get_access_controls($current_perms,
10829: $group,$file_name);
10830: foreach my $key (keys(%{$access_controls{$file_name}})) {
10831: my ($num,$scope,$end,$start) =
10832: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10833: if ($scope eq 'public') {
10834: if ($start <= $now && $end == 0) {
10835: $action = 'none';
10836: } else {
10837: $action = 'update';
10838: $aclnum = $num;
10839: }
10840: last;
10841: }
10842: }
10843: if ($action eq 'none') {
10844: return 'ok';
10845: } else {
10846: my %changes;
10847: my $newend = 0;
10848: my $newstart = $now;
10849: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10850: $changes{$action}{$newkey} = {
10851: type => 'public',
10852: time => {
10853: start => $newstart,
10854: end => $newend,
10855: },
10856: };
10857: my ($outcome,$deloutcome,$new_values,$translation) =
10858: &modify_access_controls($file_name,\%changes,$udom,$unum);
10859: return $outcome;
10860: }
10861: } else {
10862: return 'invalid';
10863: }
10864: }
10865:
10866: #------------------------------------------------------Get Marked as Read Only
10867:
10868: sub get_marked_as_readonly {
10869: my ($domain,$user,$what,$group) = @_;
10870: my $current_permissions = &get_portfile_permissions($domain,$user);
10871: my @readonly_files;
10872: my $cmp1=$what;
10873: if (ref($what)) { $cmp1=join('',@{$what}) };
10874: while (my ($file_name,$value) = each(%{$current_permissions})) {
10875: if (defined($group)) {
10876: if ($file_name !~ m-^\Q$group\E/-) {
10877: next;
10878: }
10879: }
10880: if (ref($value) eq "ARRAY"){
10881: foreach my $stored_what (@{$value}) {
10882: my $cmp2=$stored_what;
10883: if (ref($stored_what) eq 'ARRAY') {
10884: $cmp2=join('',@{$stored_what});
10885: }
10886: if ($cmp1 eq $cmp2) {
10887: push(@readonly_files, $file_name);
10888: last;
10889: } elsif (!defined($what)) {
10890: push(@readonly_files, $file_name);
10891: last;
10892: }
10893: }
10894: }
10895: }
10896: return @readonly_files;
10897: }
10898: #-----------------------------------------------------------Get Marked as Read Only Hash
10899:
10900: sub get_marked_as_readonly_hash {
10901: my ($current_permissions,$group,$what) = @_;
10902: my %readonly_files;
10903: while (my ($file_name,$value) = each(%{$current_permissions})) {
10904: if (defined($group)) {
10905: if ($file_name !~ m-^\Q$group\E/-) {
10906: next;
10907: }
10908: }
10909: if (ref($value) eq "ARRAY"){
10910: foreach my $stored_what (@{$value}) {
10911: if (ref($stored_what) eq 'ARRAY') {
10912: foreach my $lock_descriptor(@{$stored_what}) {
10913: if ($lock_descriptor eq 'graded') {
10914: $readonly_files{$file_name} = 'graded';
10915: } elsif ($lock_descriptor eq 'handback') {
10916: $readonly_files{$file_name} = 'handback';
10917: } else {
10918: if (!exists($readonly_files{$file_name})) {
10919: $readonly_files{$file_name} = 'locked';
10920: }
10921: }
10922: }
10923: }
10924: }
10925: }
10926: }
10927: return %readonly_files;
10928: }
10929: # ------------------------------------------------------------ Unmark as Read Only
10930:
10931: sub unmark_as_readonly {
10932: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10933: # for portfolio submissions, $what contains [$symb,$crsid]
10934: my ($domain,$user,$what,$file_name,$group) = @_;
10935: $file_name = &declutter_portfile($file_name);
10936: my $symb_crs = $what;
10937: if (ref($what)) { $symb_crs=join('',@$what); }
10938: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10939: my ($tmp)=keys(%current_permissions);
10940: if ($tmp=~/^error:/) { undef(%current_permissions); }
10941: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10942: foreach my $file (@readonly_files) {
10943: my $clean_file = &declutter_portfile($file);
10944: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10945: my $current_locks = $current_permissions{$file};
10946: my @new_locks;
10947: my @del_keys;
10948: if (ref($current_locks) eq "ARRAY"){
10949: foreach my $locker (@{$current_locks}) {
10950: my $compare=$locker;
10951: if (ref($locker) eq 'ARRAY') {
10952: $compare=join('',@{$locker});
10953: if ($compare ne $symb_crs) {
10954: push(@new_locks, $locker);
10955: }
10956: }
10957: }
10958: if (scalar(@new_locks) > 0) {
10959: $current_permissions{$file} = \@new_locks;
10960: } else {
10961: push(@del_keys, $file);
10962: &del('file_permissions',\@del_keys, $domain, $user);
10963: delete($current_permissions{$file});
10964: }
10965: }
10966: }
10967: &put('file_permissions',\%current_permissions,$domain,$user);
10968: return;
10969: }
10970:
10971: # ------------------------------------------------------------ Directory lister
10972:
10973: sub dirlist {
10974: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10975: $uri=~s/^\///;
10976: $uri=~s/\/$//;
10977: my ($udom, $uname);
10978: if ($getuserdir) {
10979: $udom = $userdomain;
10980: $uname = $username;
10981: } else {
10982: (undef,$udom,$uname)=split(/\//,$uri);
10983: if(defined($userdomain)) {
10984: $udom = $userdomain;
10985: }
10986: if(defined($username)) {
10987: $uname = $username;
10988: }
10989: }
10990: my ($dirRoot,$listing,@listing_results);
10991:
10992: $dirRoot = $perlvar{'lonDocRoot'};
10993: if (defined($getpropath)) {
10994: $dirRoot = &propath($udom,$uname);
10995: $dirRoot =~ s/\/$//;
10996: } elsif (defined($getuserdir)) {
10997: my $subdir=$uname.'__';
10998: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10999: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11000: ."/$udom/$subdir/$uname";
11001: } elsif (defined($alternateRoot)) {
11002: $dirRoot = $alternateRoot;
11003: }
11004:
11005: if($udom) {
11006: if($uname) {
11007: my $uhome = &homeserver($uname,$udom);
11008: if ($uhome eq 'no_host') {
11009: return ([],'no_host');
11010: }
11011: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11012: .$getuserdir.':'.&escape($dirRoot)
11013: .':'.&escape($uname).':'.&escape($udom),$uhome);
11014: if ($listing eq 'unknown_cmd') {
11015: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11016: } else {
11017: @listing_results = map { &unescape($_); } split(/:/,$listing);
11018: }
11019: if ($listing eq 'unknown_cmd') {
11020: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11021: @listing_results = split(/:/,$listing);
11022: } else {
11023: @listing_results = map { &unescape($_); } split(/:/,$listing);
11024: }
11025: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11026: ($listing eq 'rejected') || ($listing eq 'refused') ||
11027: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11028: return ([],$listing);
11029: } else {
11030: return (\@listing_results);
11031: }
11032: } elsif(!$alternateRoot) {
11033: my (%allusers,%listerror);
11034: my %servers = &get_servers($udom,'library');
11035: foreach my $tryserver (keys(%servers)) {
11036: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11037: &escape($udom),$tryserver);
11038: if ($listing eq 'unknown_cmd') {
11039: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11040: $udom, $tryserver);
11041: } else {
11042: @listing_results = map { &unescape($_); } split(/:/,$listing);
11043: }
11044: if ($listing eq 'unknown_cmd') {
11045: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11046: $udom, $tryserver);
11047: @listing_results = split(/:/,$listing);
11048: } else {
11049: @listing_results =
11050: map { &unescape($_); } split(/:/,$listing);
11051: }
11052: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11053: ($listing eq 'rejected') || ($listing eq 'refused') ||
11054: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11055: $listerror{$tryserver} = $listing;
11056: } else {
11057: foreach my $line (@listing_results) {
11058: my ($entry) = split(/&/,$line,2);
11059: $allusers{$entry} = 1;
11060: }
11061: }
11062: }
11063: my @alluserslist=();
11064: foreach my $user (sort(keys(%allusers))) {
11065: push(@alluserslist,$user.'&user');
11066: }
11067: if (!%listerror) {
11068: # no errors
11069: return (\@alluserslist);
11070: } elsif (scalar(keys(%servers)) == 1) {
11071: # one library server, one error
11072: my ($key) = keys(%listerror);
11073: return (\@alluserslist, $listerror{$key});
11074: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11075: # con_lost indicates that we might miss data from at least one
11076: # library server
11077: return (\@alluserslist, 'con_lost');
11078: } else {
11079: # multiple library servers and no con_lost -> data should be
11080: # complete.
11081: return (\@alluserslist);
11082: }
11083:
11084: } else {
11085: return ([],'missing username');
11086: }
11087: } elsif(!defined($getpropath)) {
11088: my $path = $perlvar{'lonDocRoot'}.'/res/';
11089: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11090: return (\@all_domains);
11091: } else {
11092: return ([],'missing domain');
11093: }
11094: }
11095:
11096: # --------------------------------------------- GetFileTimestamp
11097: # This function utilizes dirlist and returns the date stamp for
11098: # when it was last modified. It will also return an error of -1
11099: # if an error occurs
11100:
11101: sub GetFileTimestamp {
11102: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11103: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11104: $studentName = &LONCAPA::clean_username($studentName);
11105: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11106: undef,$getuserdir);
11107: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11108: return -1;
11109: }
11110: if (ref($fileref) eq 'ARRAY') {
11111: my @stats = split('&',$fileref->[0]);
11112: # @stats contains first the filename, then the stat output
11113: return $stats[10]; # so this is 10 instead of 9.
11114: } else {
11115: return -1;
11116: }
11117: }
11118:
11119: sub stat_file {
11120: my ($uri) = @_;
11121: $uri = &clutter_with_no_wrapper($uri);
11122:
11123: my ($udom,$uname,$file);
11124: if ($uri =~ m-^/(uploaded|editupload)/-) {
11125: ($udom,$uname,$file) =
11126: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11127: $file = 'userfiles/'.$file;
11128: }
11129: if ($uri =~ m-^/res/-) {
11130: ($udom,$uname) =
11131: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11132: $file = $uri;
11133: }
11134:
11135: if (!$udom || !$uname || !$file) {
11136: # unable to handle the uri
11137: return ();
11138: }
11139: my $getpropath;
11140: if ($file =~ /^userfiles\//) {
11141: $getpropath = 1;
11142: }
11143: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11144: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11145: return ();
11146: } else {
11147: if (ref($listref) eq 'ARRAY') {
11148: my @stats = split('&',$listref->[0]);
11149: shift(@stats); #filename is first
11150: return @stats;
11151: }
11152: }
11153: return ();
11154: }
11155:
11156: # -------------------------------------------------------- Value of a Condition
11157:
11158: # gets the value of a specific preevaluated condition
11159: # stored in the string $env{user.state.<cid>}
11160: # or looks up a condition reference in the bighash and if if hasn't
11161: # already been evaluated recurses into docondval to get the value of
11162: # the condition, then memoizing it to
11163: # $env{user.state.<cid>.<condition>}
11164: sub directcondval {
11165: my $number=shift;
11166: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11167: &Apache::lonuserstate::evalstate();
11168: }
11169: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11170: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11171: } elsif ($number =~ /^_/) {
11172: my $sub_condition;
11173: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11174: &GDBM_READER(),0640)) {
11175: $sub_condition=$bighash{'conditions'.$number};
11176: untie(%bighash);
11177: }
11178: my $value = &docondval($sub_condition);
11179: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11180: return $value;
11181: }
11182: if ($env{'user.state.'.$env{'request.course.id'}}) {
11183: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11184: } else {
11185: return 2;
11186: }
11187: }
11188:
11189: # get the collection of conditions for this resource
11190: sub condval {
11191: my $condidx=shift;
11192: my $allpathcond='';
11193: foreach my $cond (split(/\|/,$condidx)) {
11194: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11195: $allpathcond.=
11196: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11197: }
11198: }
11199: $allpathcond=~s/\|$//;
11200: return &docondval($allpathcond);
11201: }
11202:
11203: #evaluates an expression of conditions
11204: sub docondval {
11205: my ($allpathcond) = @_;
11206: my $result=0;
11207: if ($env{'request.course.id'}
11208: && defined($allpathcond)) {
11209: my $operand='|';
11210: my @stack;
11211: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11212: if ($chunk eq '(') {
11213: push @stack,($operand,$result);
11214: } elsif ($chunk eq ')') {
11215: my $before=pop @stack;
11216: if (pop @stack eq '&') {
11217: $result=$result>$before?$before:$result;
11218: } else {
11219: $result=$result>$before?$result:$before;
11220: }
11221: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11222: $operand=$chunk;
11223: } else {
11224: my $new=directcondval($chunk);
11225: if ($operand eq '&') {
11226: $result=$result>$new?$new:$result;
11227: } else {
11228: $result=$result>$new?$result:$new;
11229: }
11230: }
11231: }
11232: }
11233: return $result;
11234: }
11235:
11236: # ---------------------------------------------------- Devalidate courseresdata
11237:
11238: sub devalidatecourseresdata {
11239: my ($coursenum,$coursedomain)=@_;
11240: my $hashid=$coursenum.':'.$coursedomain;
11241: &devalidate_cache_new('courseres',$hashid);
11242: }
11243:
11244:
11245: # --------------------------------------------------- Course Resourcedata Query
11246: #
11247: # Parameters:
11248: # $coursenum - Number of the course.
11249: # $coursedomain - Domain at which the course was created.
11250: # Returns:
11251: # A hash of the course parameters along (I think) with timestamps
11252: # and version info.
11253:
11254: sub get_courseresdata {
11255: my ($coursenum,$coursedomain)=@_;
11256: my $coursehom=&homeserver($coursenum,$coursedomain);
11257: my $hashid=$coursenum.':'.$coursedomain;
11258: my ($result,$cached)=&is_cached_new('courseres',$hashid);
11259: my %dumpreply;
11260: unless (defined($cached)) {
11261: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11262: $result=\%dumpreply;
11263: my ($tmp) = keys(%dumpreply);
11264: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11265: &do_cache_new('courseres',$hashid,$result,600);
11266: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11267: return $tmp;
11268: } elsif ($tmp =~ /^(error)/) {
11269: $result=undef;
11270: &do_cache_new('courseres',$hashid,$result,600);
11271: }
11272: }
11273: return $result;
11274: }
11275:
11276: sub devalidateuserresdata {
11277: my ($uname,$udom)=@_;
11278: my $hashid="$udom:$uname";
11279: &devalidate_cache_new('userres',$hashid);
11280: }
11281:
11282: sub get_userresdata {
11283: my ($uname,$udom)=@_;
11284: #most student don\'t have any data set, check if there is some data
11285: if (&EXT_cache_status($udom,$uname)) { return undef; }
11286:
11287: my $hashid="$udom:$uname";
11288: my ($result,$cached)=&is_cached_new('userres',$hashid);
11289: if (!defined($cached)) {
11290: my %resourcedata=&dump('resourcedata',$udom,$uname);
11291: $result=\%resourcedata;
11292: &do_cache_new('userres',$hashid,$result,600);
11293: }
11294: my ($tmp)=keys(%$result);
11295: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11296: return $result;
11297: }
11298: #error 2 occurs when the .db doesn't exist
11299: if ($tmp!~/error: 2 /) {
11300: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11301: &logthis("<font color=\"blue\">WARNING:".
11302: " Trying to get resource data for ".
11303: $uname." at ".$udom.": ".
11304: $tmp."</font>");
11305: }
11306: } elsif ($tmp=~/error: 2 /) {
11307: #&EXT_cache_set($udom,$uname);
11308: &do_cache_new('userres',$hashid,undef,600);
11309: undef($tmp); # not really an error so don't send it back
11310: }
11311: return $tmp;
11312: }
11313: #----------------------------------------------- resdata - return resource data
11314: # Purpose:
11315: # Return resource data for either users or for a course.
11316: # Parameters:
11317: # $name - Course/user name.
11318: # $domain - Name of the domain the user/course is registered on.
11319: # $type - Type of thing $name is (must be 'course' or 'user'
11320: # @which - Array of names of resources desired.
11321: # Returns:
11322: # The value of the first reasource in @which that is found in the
11323: # resource hash.
11324: # Exceptional Conditions:
11325: # If the $type passed in is not valid (not the string 'course' or
11326: # 'user', an undefined reference is returned.
11327: # If none of the resources are found, an undef is returned
11328: sub resdata {
11329: my ($name,$domain,$type,@which)=@_;
11330: my $result;
11331: if ($type eq 'course') {
11332: $result=&get_courseresdata($name,$domain);
11333: } elsif ($type eq 'user') {
11334: $result=&get_userresdata($name,$domain);
11335: }
11336: if (!ref($result)) { return $result; }
11337: foreach my $item (@which) {
11338: if (defined($result->{$item->[0]})) {
11339: return [$result->{$item->[0]},$item->[1]];
11340: }
11341: }
11342: return undef;
11343: }
11344:
11345: sub get_numsuppfiles {
11346: my ($cnum,$cdom,$ignorecache)=@_;
11347: my $hashid=$cnum.':'.$cdom;
11348: my ($suppcount,$cached);
11349: unless ($ignorecache) {
11350: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11351: }
11352: unless (defined($cached)) {
11353: my $chome=&homeserver($cnum,$cdom);
11354: unless ($chome eq 'no_host') {
11355: ($suppcount,my $errors) = (0,0);
11356: my $suppmap = 'supplemental.sequence';
11357: ($suppcount,$errors) =
11358: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11359: }
11360: &do_cache_new('suppcount',$hashid,$suppcount,600);
11361: }
11362: return $suppcount;
11363: }
11364:
11365: #
11366: # EXT resource caching routines
11367: #
11368:
11369: sub clear_EXT_cache_status {
11370: &delenv('cache.EXT.');
11371: }
11372:
11373: sub EXT_cache_status {
11374: my ($target_domain,$target_user) = @_;
11375: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11376: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11377: # We know already the user has no data
11378: return 1;
11379: } else {
11380: return 0;
11381: }
11382: }
11383:
11384: sub EXT_cache_set {
11385: my ($target_domain,$target_user) = @_;
11386: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11387: #&appenv({$cachename => time});
11388: }
11389:
11390: # --------------------------------------------------------- Value of a Variable
11391: sub EXT {
11392:
11393: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11394: unless ($varname) { return ''; }
11395: #get real user name/domain, courseid and symb
11396: my $courseid;
11397: my $publicuser;
11398: if ($symbparm) {
11399: $symbparm=&get_symb_from_alias($symbparm);
11400: }
11401: if (!($uname && $udom)) {
11402: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11403: if (!$symbparm) { $symbparm=$cursymb; }
11404: } else {
11405: $courseid=$env{'request.course.id'};
11406: }
11407: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11408: my $rest;
11409: if (defined($therest[0])) {
11410: $rest=join('.',@therest);
11411: } else {
11412: $rest='';
11413: }
11414:
11415: my $qualifierrest=$qualifier;
11416: if ($rest) { $qualifierrest.='.'.$rest; }
11417: my $spacequalifierrest=$space;
11418: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11419: if ($realm eq 'user') {
11420: # --------------------------------------------------------------- user.resource
11421: if ($space eq 'resource') {
11422: if ( (defined($Apache::lonhomework::parsing_a_problem)
11423: || defined($Apache::lonhomework::parsing_a_task))
11424: &&
11425: ($symbparm eq &symbread()) ) {
11426: # if we are in the middle of processing the resource the
11427: # get the value we are planning on committing
11428: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11429: return $Apache::lonhomework::results{$qualifierrest};
11430: } else {
11431: return $Apache::lonhomework::history{$qualifierrest};
11432: }
11433: } else {
11434: my %restored;
11435: if ($publicuser || $env{'request.state'} eq 'construct') {
11436: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11437: } else {
11438: %restored=&restore($symbparm,$courseid,$udom,$uname);
11439: }
11440: return $restored{$qualifierrest};
11441: }
11442: # ----------------------------------------------------------------- user.access
11443: } elsif ($space eq 'access') {
11444: # FIXME - not supporting calls for a specific user
11445: return &allowed($qualifier,$rest);
11446: # ------------------------------------------ user.preferences, user.environment
11447: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11448: if (($uname eq $env{'user.name'}) &&
11449: ($udom eq $env{'user.domain'})) {
11450: return $env{join('.',('environment',$qualifierrest))};
11451: } else {
11452: my %returnhash;
11453: if (!$publicuser) {
11454: %returnhash=&userenvironment($udom,$uname,
11455: $qualifierrest);
11456: }
11457: return $returnhash{$qualifierrest};
11458: }
11459: # ----------------------------------------------------------------- user.course
11460: } elsif ($space eq 'course') {
11461: # FIXME - not supporting calls for a specific user
11462: return $env{join('.',('request.course',$qualifier))};
11463: # ------------------------------------------------------------------- user.role
11464: } elsif ($space eq 'role') {
11465: # FIXME - not supporting calls for a specific user
11466: my ($role,$where)=split(/\./,$env{'request.role'});
11467: if ($qualifier eq 'value') {
11468: return $role;
11469: } elsif ($qualifier eq 'extent') {
11470: return $where;
11471: }
11472: # ----------------------------------------------------------------- user.domain
11473: } elsif ($space eq 'domain') {
11474: return $udom;
11475: # ------------------------------------------------------------------- user.name
11476: } elsif ($space eq 'name') {
11477: return $uname;
11478: # ---------------------------------------------------- Any other user namespace
11479: } else {
11480: my %reply;
11481: if (!$publicuser) {
11482: %reply=&get($space,[$qualifierrest],$udom,$uname);
11483: }
11484: return $reply{$qualifierrest};
11485: }
11486: } elsif ($realm eq 'query') {
11487: # ---------------------------------------------- pull stuff out of query string
11488: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11489: [$spacequalifierrest]);
11490: return $env{'form.'.$spacequalifierrest};
11491: } elsif ($realm eq 'request') {
11492: # ------------------------------------------------------------- request.browser
11493: if ($space eq 'browser') {
11494: return $env{'browser.'.$qualifier};
11495: # ------------------------------------------------------------ request.filename
11496: } else {
11497: return $env{'request.'.$spacequalifierrest};
11498: }
11499: } elsif ($realm eq 'course') {
11500: # ---------------------------------------------------------- course.description
11501: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11502: } elsif ($realm eq 'resource') {
11503:
11504: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11505: if (!$symbparm) { $symbparm=&symbread(); }
11506: }
11507:
11508: if ($qualifier eq '') {
11509: if ($space eq 'title') {
11510: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11511: return &gettitle($symbparm);
11512: }
11513:
11514: if ($space eq 'map') {
11515: my ($map) = &decode_symb($symbparm);
11516: return &symbread($map);
11517: }
11518: if ($space eq 'maptitle') {
11519: my ($map) = &decode_symb($symbparm);
11520: return &gettitle($map);
11521: }
11522: if ($space eq 'filename') {
11523: if ($symbparm) {
11524: return &clutter((&decode_symb($symbparm))[2]);
11525: }
11526: return &hreflocation('',$env{'request.filename'});
11527: }
11528:
11529: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11530: if ($space eq 'visibleparts') {
11531: my $navmap = Apache::lonnavmaps::navmap->new();
11532: my $item;
11533: if (ref($navmap)) {
11534: my $res = $navmap->getBySymb($symbparm);
11535: my $parts = $res->parts();
11536: if (ref($parts) eq 'ARRAY') {
11537: $item = join(',',@{$parts});
11538: }
11539: undef($navmap);
11540: }
11541: return $item;
11542: }
11543: }
11544: }
11545:
11546: my ($section, $group, @groups);
11547: my ($courselevelm,$courselevel);
11548: if (($courseid eq '') && ($cid)) {
11549: $courseid = $cid;
11550: }
11551: if (($symbparm && $courseid) &&
11552: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11553:
11554: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11555:
11556: # ----------------------------------------------------- Cascading lookup scheme
11557: my $symbp=$symbparm;
11558: my $mapp=&deversion((&decode_symb($symbp))[0]);
11559:
11560: my $symbparm=$symbp.'.'.$spacequalifierrest;
11561: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11562:
11563: if (($env{'user.name'} eq $uname) &&
11564: ($env{'user.domain'} eq $udom)) {
11565: $section=$env{'request.course.sec'};
11566: @groups = split(/:/,$env{'request.course.groups'});
11567: @groups=&sort_course_groups($courseid,@groups);
11568: } else {
11569: if (! defined($usection)) {
11570: $section=&getsection($udom,$uname,$courseid);
11571: } else {
11572: $section = $usection;
11573: }
11574: @groups = &get_users_groups($udom,$uname,$courseid);
11575: }
11576:
11577: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11578: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11579: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11580:
11581: $courselevel=$courseid.'.'.$spacequalifierrest;
11582: my $courselevelr=$courseid.'.'.$symbparm;
11583: $courselevelm=$courseid.'.'.$mapparm;
11584:
11585: # ----------------------------------------------------------- first, check user
11586:
11587: my $userreply=&resdata($uname,$udom,'user',
11588: ([$courselevelr,'resource'],
11589: [$courselevelm,'map' ],
11590: [$courselevel, 'course' ]));
11591: if (defined($userreply)) { return &get_reply($userreply); }
11592:
11593: # ------------------------------------------------ second, check some of course
11594: my $coursereply;
11595: if (@groups > 0) {
11596: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11597: $mapparm,$spacequalifierrest);
11598: if (defined($coursereply)) { return &get_reply($coursereply); }
11599: }
11600:
11601: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11602: $env{'course.'.$courseid.'.domain'},
11603: 'course',
11604: ([$seclevelr, 'resource'],
11605: [$seclevelm, 'map' ],
11606: [$seclevel, 'course' ],
11607: [$courselevelr,'resource']));
11608: if (defined($coursereply)) { return &get_reply($coursereply); }
11609:
11610: # ------------------------------------------------------ third, check map parms
11611: my %parmhash=();
11612: my $thisparm='';
11613: if (tie(%parmhash,'GDBM_File',
11614: $env{'request.course.fn'}.'_parms.db',
11615: &GDBM_READER(),0640)) {
11616: $thisparm=$parmhash{$symbparm};
11617: untie(%parmhash);
11618: }
11619: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11620: }
11621: # ------------------------------------------ fourth, look in resource metadata
11622:
11623: $spacequalifierrest=~s/\./\_/;
11624: my $filename;
11625: if (!$symbparm) { $symbparm=&symbread(); }
11626: if ($symbparm) {
11627: $filename=(&decode_symb($symbparm))[2];
11628: } else {
11629: $filename=$env{'request.filename'};
11630: }
11631: my $metadata=&metadata($filename,$spacequalifierrest);
11632: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11633: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11634: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11635:
11636: # ---------------------------------------------- fourth, look in rest of course
11637: if ($symbparm && defined($courseid) &&
11638: $courseid eq $env{'request.course.id'}) {
11639: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11640: $env{'course.'.$courseid.'.domain'},
11641: 'course',
11642: ([$courselevelm,'map' ],
11643: [$courselevel, 'course']));
11644: if (defined($coursereply)) { return &get_reply($coursereply); }
11645: }
11646: # ------------------------------------------------------------------ Cascade up
11647: unless ($space eq '0') {
11648: my @parts=split(/_/,$space);
11649: my $id=pop(@parts);
11650: my $part=join('_',@parts);
11651: if ($part eq '') { $part='0'; }
11652: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11653: $symbparm,$udom,$uname,$section,1);
11654: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11655: }
11656: if ($recurse) { return undef; }
11657: my $pack_def=&packages_tab_default($filename,$varname);
11658: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11659: # ---------------------------------------------------- Any other user namespace
11660: } elsif ($realm eq 'environment') {
11661: # ----------------------------------------------------------------- environment
11662: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11663: return $env{'environment.'.$spacequalifierrest};
11664: } else {
11665: if ($uname eq 'anonymous' && $udom eq '') {
11666: return '';
11667: }
11668: my %returnhash=&userenvironment($udom,$uname,
11669: $spacequalifierrest);
11670: return $returnhash{$spacequalifierrest};
11671: }
11672: } elsif ($realm eq 'system') {
11673: # ----------------------------------------------------------------- system.time
11674: if ($space eq 'time') {
11675: return time;
11676: }
11677: } elsif ($realm eq 'server') {
11678: # ----------------------------------------------------------------- system.time
11679: if ($space eq 'name') {
11680: return $ENV{'SERVER_NAME'};
11681: }
11682: }
11683: return '';
11684: }
11685:
11686: sub get_reply {
11687: my ($reply_value) = @_;
11688: if (ref($reply_value) eq 'ARRAY') {
11689: if (wantarray) {
11690: return @$reply_value;
11691: }
11692: return $reply_value->[0];
11693: } else {
11694: return $reply_value;
11695: }
11696: }
11697:
11698: sub check_group_parms {
11699: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11700: my @groupitems = ();
11701: my $resultitem;
11702: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11703: foreach my $group (@{$groups}) {
11704: foreach my $level (@levels) {
11705: my $item = $courseid.'.['.$group.'].'.$level->[0];
11706: push(@groupitems,[$item,$level->[1]]);
11707: }
11708: }
11709: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11710: $env{'course.'.$courseid.'.domain'},
11711: 'course',@groupitems);
11712: return $coursereply;
11713: }
11714:
11715: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11716: my ($courseid,@groups) = @_;
11717: @groups = sort(@groups);
11718: return @groups;
11719: }
11720:
11721: sub packages_tab_default {
11722: my ($uri,$varname)=@_;
11723: my (undef,$part,$name)=split(/\./,$varname);
11724:
11725: my (@extension,@specifics,$do_default);
11726: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11727: my ($pack_type,$pack_part)=split(/_/,$package,2);
11728: if ($pack_type eq 'default') {
11729: $do_default=1;
11730: } elsif ($pack_type eq 'extension') {
11731: push(@extension,[$package,$pack_type,$pack_part]);
11732: } elsif ($pack_part eq $part || $pack_type eq 'part') {
11733: # only look at packages defaults for packages that this id is
11734: push(@specifics,[$package,$pack_type,$pack_part]);
11735: }
11736: }
11737: # first look for a package that matches the requested part id
11738: foreach my $package (@specifics) {
11739: my (undef,$pack_type,$pack_part)=@{$package};
11740: next if ($pack_part ne $part);
11741: if (defined($packagetab{"$pack_type&$name&default"})) {
11742: return $packagetab{"$pack_type&$name&default"};
11743: }
11744: }
11745: # look for any possible matching non extension_ package
11746: foreach my $package (@specifics) {
11747: my (undef,$pack_type,$pack_part)=@{$package};
11748: if (defined($packagetab{"$pack_type&$name&default"})) {
11749: return $packagetab{"$pack_type&$name&default"};
11750: }
11751: if ($pack_type eq 'part') { $pack_part='0'; }
11752: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11753: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11754: }
11755: }
11756: # look for any posible extension_ match
11757: foreach my $package (@extension) {
11758: my ($package,$pack_type)=@{$package};
11759: if (defined($packagetab{"$pack_type&$name&default"})) {
11760: return $packagetab{"$pack_type&$name&default"};
11761: }
11762: if (defined($packagetab{$package."&$name&default"})) {
11763: return $packagetab{$package."&$name&default"};
11764: }
11765: }
11766: # look for a global default setting
11767: if ($do_default && defined($packagetab{"default&$name&default"})) {
11768: return $packagetab{"default&$name&default"};
11769: }
11770: return undef;
11771: }
11772:
11773: sub add_prefix_and_part {
11774: my ($prefix,$part)=@_;
11775: my $keyroot;
11776: if (defined($prefix) && $prefix !~ /^__/) {
11777: # prefix that has a part already
11778: $keyroot=$prefix;
11779: } elsif (defined($prefix)) {
11780: # prefix that is missing a part
11781: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11782: } else {
11783: # no prefix at all
11784: if (defined($part)) { $keyroot='_'.$part; }
11785: }
11786: return $keyroot;
11787: }
11788:
11789: # ---------------------------------------------------------------- Get metadata
11790:
11791: my %metaentry;
11792: my %importedpartids;
11793: my %importedrespids;
11794: sub metadata {
11795: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11796: $uri=&declutter($uri);
11797: # if it is a non metadata possible uri return quickly
11798: if (($uri eq '') ||
11799: (($uri =~ m|^/*adm/|) &&
11800: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
11801: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11802: return undef;
11803: }
11804: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
11805: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11806: return undef;
11807: }
11808: my $filename=$uri;
11809: $uri=~s/\.meta$//;
11810: #
11811: # Is the metadata already cached?
11812: # Look at timestamp of caching
11813: # Everything is cached by the main uri, libraries are never directly cached
11814: #
11815: if (!defined($liburi)) {
11816: my ($result,$cached)=&is_cached_new('meta',$uri);
11817: if (defined($cached)) { return $result->{':'.$what}; }
11818: }
11819: {
11820: # Imported parts would go here
11821: my @origfiletagids=();
11822: my $importedparts=0;
11823:
11824: # Imported responseids would go here
11825: my $importedresponses=0;
11826: #
11827: # Is this a recursive call for a library?
11828: #
11829: # if (! exists($metacache{$uri})) {
11830: # $metacache{$uri}={};
11831: # }
11832: my $cachetime = 60*60;
11833: if ($liburi) {
11834: $liburi=&declutter($liburi);
11835: $filename=$liburi;
11836: } else {
11837: &devalidate_cache_new('meta',$uri);
11838: undef(%metaentry);
11839: }
11840: my %metathesekeys=();
11841: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11842: my $metastring;
11843: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11844: my $which = &hreflocation('','/'.($liburi || $uri));
11845: $metastring =
11846: &Apache::lonnet::ssi_body($which,
11847: ('grade_target' => 'meta'));
11848: $cachetime = 1; # only want this cached in the child not long term
11849: } elsif (($uri !~ m -^(editupload)/-) &&
11850: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11851: my $file=&filelocation('',&clutter($filename));
11852: #push(@{$metaentry{$uri.'.file'}},$file);
11853: $metastring=&getfile($file);
11854: }
11855: my $parser=HTML::LCParser->new(\$metastring);
11856: my $token;
11857: undef %metathesekeys;
11858: while ($token=$parser->get_token) {
11859: if ($token->[0] eq 'S') {
11860: if (defined($token->[2]->{'package'})) {
11861: #
11862: # This is a package - get package info
11863: #
11864: my $package=$token->[2]->{'package'};
11865: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11866: if (defined($token->[2]->{'id'})) {
11867: $keyroot.='_'.$token->[2]->{'id'};
11868: }
11869: if ($metaentry{':packages'}) {
11870: $metaentry{':packages'}.=','.$package.$keyroot;
11871: } else {
11872: $metaentry{':packages'}=$package.$keyroot;
11873: }
11874: foreach my $pack_entry (keys(%packagetab)) {
11875: my $part=$keyroot;
11876: $part=~s/^\_//;
11877: if ($pack_entry=~/^\Q$package\E\&/ ||
11878: $pack_entry=~/^\Q$package\E_0\&/) {
11879: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11880: # ignore package.tab specified default values
11881: # here &package_tab_default() will fetch those
11882: if ($subp eq 'default') { next; }
11883: my $value=$packagetab{$pack_entry};
11884: my $unikey;
11885: if ($pack =~ /_0$/) {
11886: $unikey='parameter_0_'.$name;
11887: $part=0;
11888: } else {
11889: $unikey='parameter'.$keyroot.'_'.$name;
11890: }
11891: if ($subp eq 'display') {
11892: $value.=' [Part: '.$part.']';
11893: }
11894: $metaentry{':'.$unikey.'.part'}=$part;
11895: $metathesekeys{$unikey}=1;
11896: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11897: $metaentry{':'.$unikey.'.'.$subp}=$value;
11898: }
11899: if (defined($metaentry{':'.$unikey.'.default'})) {
11900: $metaentry{':'.$unikey}=
11901: $metaentry{':'.$unikey.'.default'};
11902: }
11903: }
11904: }
11905: } else {
11906: #
11907: # This is not a package - some other kind of start tag
11908: #
11909: my $entry=$token->[1];
11910: my $unikey='';
11911:
11912: if ($entry eq 'import') {
11913: #
11914: # Importing a library here
11915: #
11916: my $location=$parser->get_text('/import');
11917: my $dir=$filename;
11918: $dir=~s|[^/]*$||;
11919: $location=&filelocation($dir,$location);
11920:
11921: my $importid=$token->[2]->{'id'};
11922: my $importmode=$token->[2]->{'importmode'};
11923: #
11924: # Check metadata for imported file to
11925: # see if it contained response items
11926: #
11927: my %currmetaentry = %metaentry;
11928: my $libresponseorder = &metadata($location,'responseorder');
11929: my $origfile;
11930: if ($libresponseorder ne '') {
11931: if ($#origfiletagids<0) {
11932: undef(%importedrespids);
11933: undef(%importedpartids);
11934: }
11935: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11936: if (@{$importedrespids{$importid}} > 0) {
11937: $importedresponses = 1;
11938: # We need to get the original file and the imported file to get the response order correct
11939: # Load and inspect original file
11940: if ($#origfiletagids<0) {
11941: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11942: $origfile=&getfile($origfilelocation);
11943: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11944: }
11945: }
11946: }
11947: # Do not overwrite contents of %metaentry hash for resource itself with
11948: # hash populated for imported library file
11949: %metaentry = %currmetaentry;
11950: undef(%currmetaentry);
11951: if ($importmode eq 'problem') {
11952: # Import as problem/response
11953: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11954: } elsif ($importmode eq 'part') {
11955: # Import as part(s)
11956: $importedparts=1;
11957: # We need to get the original file and the imported file to get the part order correct
11958: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11959: # Load and inspect original file if we didn't do that already
11960: if ($#origfiletagids<0) {
11961: undef(%importedrespids);
11962: undef(%importedpartids);
11963: if ($origfile eq '') {
11964: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11965: $origfile=&getfile($origfilelocation);
11966: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11967: }
11968: }
11969:
11970: # Load and inspect imported file
11971: my $impfile=&getfile($location);
11972: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11973: if ($#impfilepartids>=0) {
11974: # This problem had parts
11975: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11976: } else {
11977: # Importing by turning a single problem into a problem part
11978: # It gets the import-tags ID as part-ID
11979: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11980: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11981: }
11982: } else {
11983: # Normal import
11984: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11985: if (defined($token->[2]->{'id'})) {
11986: $unikey.='_'.$token->[2]->{'id'};
11987: }
11988: }
11989:
11990: if ($depthcount<20) {
11991: my $metadata =
11992: &metadata($uri,'keys', $location,$unikey,
11993: $depthcount+1);
11994: foreach my $meta (split(',',$metadata)) {
11995: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11996: $metathesekeys{$meta}=1;
11997: }
11998:
11999: }
12000: } else {
12001: #
12002: # Not importing, some other kind of non-package, non-library start tag
12003: #
12004: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12005: if (defined($token->[2]->{'id'})) {
12006: $unikey.='_'.$token->[2]->{'id'};
12007: }
12008: if (defined($token->[2]->{'name'})) {
12009: $unikey.='_'.$token->[2]->{'name'};
12010: }
12011: $metathesekeys{$unikey}=1;
12012: foreach my $param (@{$token->[3]}) {
12013: $metaentry{':'.$unikey.'.'.$param} =
12014: $token->[2]->{$param};
12015: }
12016: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12017: my $default=$metaentry{':'.$unikey.'.default'};
12018: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12019: # only ws inside the tag, and not in default, so use default
12020: # as value
12021: $metaentry{':'.$unikey}=$default;
12022: } elsif ( $internaltext =~ /\S/ ) {
12023: # something interesting inside the tag
12024: $metaentry{':'.$unikey}=$internaltext;
12025: } else {
12026: # no interesting values, don't set a default
12027: }
12028: # end of not-a-package not-a-library import
12029: }
12030: # end of not-a-package start tag
12031: }
12032: # the next is the end of "start tag"
12033: }
12034: }
12035: my ($extension) = ($uri =~ /\.(\w+)$/);
12036: $extension = lc($extension);
12037: if ($extension eq 'htm') { $extension='html'; }
12038:
12039: foreach my $key (keys(%packagetab)) {
12040: #no specific packages #how's our extension
12041: if ($key!~/^extension_\Q$extension\E&/) { next; }
12042: &metadata_create_package_def($uri,$key,'extension_'.$extension,
12043: \%metathesekeys);
12044: }
12045:
12046: if (!exists($metaentry{':packages'})
12047: || $packagetab{"import_defaults&extension_$extension"}) {
12048: foreach my $key (keys(%packagetab)) {
12049: #no specific packages well let's get default then
12050: if ($key!~/^default&/) { next; }
12051: &metadata_create_package_def($uri,$key,'default',
12052: \%metathesekeys);
12053: }
12054: }
12055: # are there custom rights to evaluate
12056: if ($metaentry{':copyright'} eq 'custom') {
12057:
12058: #
12059: # Importing a rights file here
12060: #
12061: unless ($depthcount) {
12062: my $location=$metaentry{':customdistributionfile'};
12063: my $dir=$filename;
12064: $dir=~s|[^/]*$||;
12065: $location=&filelocation($dir,$location);
12066: my $rights_metadata =
12067: &metadata($uri,'keys',$location,'_rights',
12068: $depthcount+1);
12069: foreach my $rights (split(',',$rights_metadata)) {
12070: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12071: $metathesekeys{$rights}=1;
12072: }
12073: }
12074: }
12075: # uniqifiy package listing
12076: my %seen;
12077: my @uniq_packages =
12078: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12079: $metaentry{':packages'} = join(',',@uniq_packages);
12080:
12081: if (($importedresponses) || ($importedparts)) {
12082: if ($importedparts) {
12083: # We had imported parts and need to rebuild partorder
12084: $metaentry{':partorder'}='';
12085: $metathesekeys{'partorder'}=1;
12086: }
12087: if ($importedresponses) {
12088: # We had imported responses and need to rebuild responseorder
12089: $metaentry{':responseorder'}='';
12090: $metathesekeys{'responseorder'}=1;
12091: }
12092: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12093: my $origid = $origfiletagids[$index+1];
12094: if ($origfiletagids[$index] eq 'part') {
12095: # Original part, part of the problem
12096: if ($importedparts) {
12097: $metaentry{':partorder'}.=','.$origid;
12098: }
12099: } elsif ($origfiletagids[$index] eq 'import') {
12100: if ($importedparts) {
12101: # We have imported parts at this position
12102: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12103: }
12104: if ($importedresponses) {
12105: # We have imported responses at this position
12106: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12107: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12108: }
12109: }
12110: } else {
12111: # Original response item, part of the problem
12112: if ($importedresponses) {
12113: $metaentry{':responseorder'}.=','.$origid;
12114: }
12115: }
12116: }
12117: if ($importedparts) {
12118: $metaentry{':partorder'}=~s/^\,//;
12119: }
12120: if ($importedresponses) {
12121: $metaentry{':responseorder'}=~s/^\,//;
12122: }
12123: }
12124:
12125: $metaentry{':keys'} = join(',',keys(%metathesekeys));
12126: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12127: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12128: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12129: # this is the end of "was not already recently cached
12130: }
12131: return $metaentry{':'.$what};
12132: }
12133:
12134: sub metadata_create_package_def {
12135: my ($uri,$key,$package,$metathesekeys)=@_;
12136: my ($pack,$name,$subp)=split(/\&/,$key);
12137: if ($subp eq 'default') { next; }
12138:
12139: if (defined($metaentry{':packages'})) {
12140: $metaentry{':packages'}.=','.$package;
12141: } else {
12142: $metaentry{':packages'}=$package;
12143: }
12144: my $value=$packagetab{$key};
12145: my $unikey;
12146: $unikey='parameter_0_'.$name;
12147: $metaentry{':'.$unikey.'.part'}=0;
12148: $$metathesekeys{$unikey}=1;
12149: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12150: $metaentry{':'.$unikey.'.'.$subp}=$value;
12151: }
12152: if (defined($metaentry{':'.$unikey.'.default'})) {
12153: $metaentry{':'.$unikey}=
12154: $metaentry{':'.$unikey.'.default'};
12155: }
12156: }
12157:
12158: sub metadata_generate_part0 {
12159: my ($metadata,$metacache,$uri) = @_;
12160: my %allnames;
12161: foreach my $metakey (keys(%$metadata)) {
12162: if ($metakey=~/^parameter\_(.*)/) {
12163: my $part=$$metacache{':'.$metakey.'.part'};
12164: my $name=$$metacache{':'.$metakey.'.name'};
12165: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12166: $allnames{$name}=$part;
12167: }
12168: }
12169: }
12170: foreach my $name (keys(%allnames)) {
12171: $$metadata{"parameter_0_$name"}=1;
12172: my $key=":parameter_0_$name";
12173: $$metacache{"$key.part"}='0';
12174: $$metacache{"$key.name"}=$name;
12175: $$metacache{"$key.type"}=$$metacache{':parameter_'.
12176: $allnames{$name}.'_'.$name.
12177: '.type'};
12178: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12179: '.display'};
12180: my $expr='[Part: '.$allnames{$name}.']';
12181: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12182: $$metacache{"$key.display"}=$olddis;
12183: }
12184: }
12185:
12186: # ------------------------------------------------------ Devalidate title cache
12187:
12188: sub devalidate_title_cache {
12189: my ($url)=@_;
12190: if (!$env{'request.course.id'}) { return; }
12191: my $symb=&symbread($url);
12192: if (!$symb) { return; }
12193: my $key=$env{'request.course.id'}."\0".$symb;
12194: &devalidate_cache_new('title',$key);
12195: }
12196:
12197: # ------------------------------------------------- Get the title of a course
12198:
12199: sub current_course_title {
12200: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12201: }
12202: # ------------------------------------------------- Get the title of a resource
12203:
12204: sub gettitle {
12205: my $urlsymb=shift;
12206: my $symb=&symbread($urlsymb);
12207: if ($symb) {
12208: my $key=$env{'request.course.id'}."\0".$symb;
12209: my ($result,$cached)=&is_cached_new('title',$key);
12210: if (defined($cached)) {
12211: return $result;
12212: }
12213: my ($map,$resid,$url)=&decode_symb($symb);
12214: my $title='';
12215: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12216: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12217: } else {
12218: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12219: &GDBM_READER(),0640)) {
12220: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12221: $title=$bighash{'title_'.$mapid.'.'.$resid};
12222: untie(%bighash);
12223: }
12224: }
12225: $title=~s/\&colon\;/\:/gs;
12226: if ($title) {
12227: # Remember both $symb and $title for dynamic metadata
12228: $accesshash{$symb.'___crstitle'}=$title;
12229: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12230: # Cache this title and then return it
12231: return &do_cache_new('title',$key,$title,600);
12232: }
12233: $urlsymb=$url;
12234: }
12235: my $title=&metadata($urlsymb,'title');
12236: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12237: return $title;
12238: }
12239:
12240: sub get_slot {
12241: my ($which,$cnum,$cdom)=@_;
12242: if (!$cnum || !$cdom) {
12243: (undef,my $courseid)=&whichuser();
12244: $cdom=$env{'course.'.$courseid.'.domain'};
12245: $cnum=$env{'course.'.$courseid.'.num'};
12246: }
12247: my $key=join("\0",'slots',$cdom,$cnum,$which);
12248: my %slotinfo;
12249: if (exists($remembered{$key})) {
12250: $slotinfo{$which} = $remembered{$key};
12251: } else {
12252: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12253: &Apache::lonhomework::showhash(%slotinfo);
12254: my ($tmp)=keys(%slotinfo);
12255: if ($tmp=~/^error:/) { return (); }
12256: $remembered{$key} = $slotinfo{$which};
12257: }
12258: if (ref($slotinfo{$which}) eq 'HASH') {
12259: return %{$slotinfo{$which}};
12260: }
12261: return $slotinfo{$which};
12262: }
12263:
12264: sub get_reservable_slots {
12265: my ($cnum,$cdom,$uname,$udom) = @_;
12266: my $now = time;
12267: my $reservable_info;
12268: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12269: if (exists($remembered{$key})) {
12270: $reservable_info = $remembered{$key};
12271: } else {
12272: my %resv;
12273: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12274: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12275: $reservable_info = \%resv;
12276: $remembered{$key} = $reservable_info;
12277: }
12278: return $reservable_info;
12279: }
12280:
12281: sub get_course_slots {
12282: my ($cnum,$cdom) = @_;
12283: my $hashid=$cnum.':'.$cdom;
12284: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12285: if (defined($cached)) {
12286: if (ref($result) eq 'HASH') {
12287: return %{$result};
12288: }
12289: } else {
12290: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12291: my ($tmp) = keys(%slots);
12292: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12293: &do_cache_new('allslots',$hashid,\%slots,600);
12294: return %slots;
12295: }
12296: }
12297: return;
12298: }
12299:
12300: sub devalidate_slots_cache {
12301: my ($cnum,$cdom)=@_;
12302: my $hashid=$cnum.':'.$cdom;
12303: &devalidate_cache_new('allslots',$hashid);
12304: }
12305:
12306: sub get_coursechange {
12307: my ($cdom,$cnum) = @_;
12308: if ($cdom eq '' || $cnum eq '') {
12309: return unless ($env{'request.course.id'});
12310: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12311: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12312: }
12313: my $hashid=$cdom.'_'.$cnum;
12314: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12315: if ((defined($cached)) && ($change ne '')) {
12316: return $change;
12317: } else {
12318: my %crshash;
12319: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12320: if ($crshash{'internal.contentchange'} eq '') {
12321: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12322: if ($change eq '') {
12323: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12324: $change = $crshash{'internal.created'};
12325: }
12326: } else {
12327: $change = $crshash{'internal.contentchange'};
12328: }
12329: my $cachetime = 600;
12330: &do_cache_new('crschange',$hashid,$change,$cachetime);
12331: }
12332: return $change;
12333: }
12334:
12335: sub devalidate_coursechange_cache {
12336: my ($cnum,$cdom)=@_;
12337: my $hashid=$cnum.':'.$cdom;
12338: &devalidate_cache_new('crschange',$hashid);
12339: }
12340:
12341: # ------------------------------------------------- Update symbolic store links
12342:
12343: sub symblist {
12344: my ($mapname,%newhash)=@_;
12345: $mapname=&deversion(&declutter($mapname));
12346: my %hash;
12347: if (($env{'request.course.fn'}) && (%newhash)) {
12348: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12349: &GDBM_WRCREAT(),0640)) {
12350: foreach my $url (keys(%newhash)) {
12351: next if ($url eq 'last_known'
12352: && $env{'form.no_update_last_known'});
12353: $hash{declutter($url)}=&encode_symb($mapname,
12354: $newhash{$url}->[1],
12355: $newhash{$url}->[0]);
12356: }
12357: if (untie(%hash)) {
12358: return 'ok';
12359: }
12360: }
12361: }
12362: return 'error';
12363: }
12364:
12365: # --------------------------------------------------------------- Verify a symb
12366:
12367: sub symbverify {
12368: my ($symb,$thisurl,$encstate)=@_;
12369: my $thisfn=$thisurl;
12370: $thisfn=&declutter($thisfn);
12371: # direct jump to resource in page or to a sequence - will construct own symbs
12372: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12373: # check URL part
12374: my ($map,$resid,$url)=&decode_symb($symb);
12375:
12376: unless ($url eq $thisfn) { return 0; }
12377:
12378: $symb=&symbclean($symb);
12379: $thisurl=&deversion($thisurl);
12380: $thisfn=&deversion($thisfn);
12381:
12382: my %bighash;
12383: my $okay=0;
12384:
12385: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12386: &GDBM_READER(),0640)) {
12387: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12388: $thisurl =~ s/\?.+$//;
12389: if ($map =~ m{^uploaded/.+\.page$}) {
12390: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12391: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12392: }
12393: }
12394: my $ids;
12395: if ($map =~ m{^uploaded/.+\.page$}) {
12396: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12397: } else {
12398: $ids=$bighash{'ids_'.&clutter($thisurl)};
12399: }
12400: unless ($ids) {
12401: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12402: $ids=$bighash{$idkey};
12403: }
12404: if ($ids) {
12405: # ------------------------------------------------------------------- Has ID(s)
12406: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12407: $symb =~ s/\?.+$//;
12408: }
12409: foreach my $id (split(/\,/,$ids)) {
12410: my ($mapid,$resid)=split(/\./,$id);
12411: if (
12412: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12413: eq $symb) {
12414: if (ref($encstate)) {
12415: $$encstate = $bighash{'encrypted_'.$id};
12416: }
12417: if (($env{'request.role.adv'}) ||
12418: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12419: ($thisurl eq '/adm/navmaps')) {
12420: $okay=1;
12421: last;
12422: }
12423: }
12424: }
12425: }
12426: untie(%bighash);
12427: }
12428: return $okay;
12429: }
12430:
12431: # --------------------------------------------------------------- Clean-up symb
12432:
12433: sub symbclean {
12434: my $symb=shift;
12435: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12436: # remove version from map
12437: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12438:
12439: # remove version from URL
12440: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12441:
12442: # remove wrapper
12443:
12444: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12445: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12446: return $symb;
12447: }
12448:
12449: # ---------------------------------------------- Split symb to find map and url
12450:
12451: sub encode_symb {
12452: my ($map,$resid,$url)=@_;
12453: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12454: }
12455:
12456: sub decode_symb {
12457: my $symb=shift;
12458: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12459: my ($map,$resid,$url)=split(/___/,$symb);
12460: return (&fixversion($map),$resid,&fixversion($url));
12461: }
12462:
12463: sub fixversion {
12464: my $fn=shift;
12465: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12466: my %bighash;
12467: my $uri=&clutter($fn);
12468: my $key=$env{'request.course.id'}.'_'.$uri;
12469: # is this cached?
12470: my ($result,$cached)=&is_cached_new('courseresversion',$key);
12471: if (defined($cached)) { return $result; }
12472: # unfortunately not cached, or expired
12473: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12474: &GDBM_READER(),0640)) {
12475: if ($bighash{'version_'.$uri}) {
12476: my $version=$bighash{'version_'.$uri};
12477: unless (($version eq 'mostrecent') ||
12478: ($version==&getversion($uri))) {
12479: $uri=~s/\.(\w+)$/\.$version\.$1/;
12480: }
12481: }
12482: untie %bighash;
12483: }
12484: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12485: }
12486:
12487: sub deversion {
12488: my $url=shift;
12489: $url=~s/\.\d+\.(\w+)$/\.$1/;
12490: return $url;
12491: }
12492:
12493: # ------------------------------------------------------ Return symb list entry
12494:
12495: sub symbread {
12496: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12497: $ignoresymbdb,$noenccheck)=@_;
12498: my $cache_str='request.symbread.cached.'.$thisfn;
12499: if (defined($env{$cache_str})) {
12500: unless (ref($possibles) eq 'HASH') {
12501: if ($ignorecachednull) {
12502: return $env{$cache_str} unless ($env{$cache_str} eq '');
12503: } else {
12504: return $env{$cache_str};
12505: }
12506: }
12507: }
12508: # no filename provided? try from environment
12509: unless ($thisfn) {
12510: if ($env{'request.symb'}) {
12511: return $env{$cache_str}=&symbclean($env{'request.symb'});
12512: }
12513: $thisfn=$env{'request.filename'};
12514: }
12515: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12516: # is that filename actually a symb? Verify, clean, and return
12517: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12518: if (&symbverify($thisfn,$1)) {
12519: return $env{$cache_str}=&symbclean($thisfn);
12520: }
12521: }
12522: $thisfn=declutter($thisfn);
12523: my %hash;
12524: my %bighash;
12525: my $syval='';
12526: if (($env{'request.course.fn'}) && ($thisfn)) {
12527: my $targetfn = $thisfn;
12528: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12529: $targetfn = 'adm/wrapper/'.$thisfn;
12530: }
12531: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12532: $targetfn=$1;
12533: }
12534: unless ($ignoresymbdb) {
12535: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12536: &GDBM_READER(),0640)) {
12537: $syval=$hash{$targetfn};
12538: untie(%hash);
12539: }
12540: if ($syval && $checkforblock) {
12541: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12542: if (@blockers) {
12543: $syval='';
12544: }
12545: }
12546: }
12547: # ---------------------------------------------------------- There was an entry
12548: if ($syval) {
12549: #unless ($syval=~/\_\d+$/) {
12550: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12551: #&appenv({'request.ambiguous' => $thisfn});
12552: #return $env{$cache_str}='';
12553: #}
12554: #$syval.=$1;
12555: #}
12556: } else {
12557: # ------------------------------------------------------- Was not in symb table
12558: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12559: &GDBM_READER(),0640)) {
12560: # ---------------------------------------------- Get ID(s) for current resource
12561: my $ids=$bighash{'ids_'.&clutter($thisfn)};
12562: unless ($ids) {
12563: $ids=$bighash{'ids_/'.$thisfn};
12564: }
12565: unless ($ids) {
12566: # alias?
12567: $ids=$bighash{'mapalias_'.$thisfn};
12568: }
12569: if ($ids) {
12570: # ------------------------------------------------------------------- Has ID(s)
12571: my @possibilities=split(/\,/,$ids);
12572: if ($#possibilities==0) {
12573: # ----------------------------------------------- There is only one possibility
12574: my ($mapid,$resid)=split(/\./,$ids);
12575: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12576: $resid,$thisfn);
12577: if (ref($possibles) eq 'HASH') {
12578: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12579: $possibles->{$syval} = 1;
12580: }
12581: }
12582: if ($checkforblock) {
12583: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12584: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12585: if (@blockers) {
12586: $syval = '';
12587: untie(%bighash);
12588: return $env{$cache_str}='';
12589: }
12590: }
12591: }
12592: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12593: # ------------------------------------------ There is more than one possibility
12594: my $realpossible=0;
12595: foreach my $id (@possibilities) {
12596: my $file=$bighash{'src_'.$id};
12597: my $canaccess;
12598: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12599: $canaccess = 1;
12600: } else {
12601: $canaccess = &allowed('bre',$file);
12602: }
12603: if ($canaccess) {
12604: my ($mapid,$resid)=split(/\./,$id);
12605: if ($bighash{'map_type_'.$mapid} ne 'page') {
12606: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12607: $resid,$thisfn);
12608: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12609: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
12610: if ($checkforblock) {
12611: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12612: if (@blockers > 0) {
12613: $syval = '';
12614: } else {
12615: $syval = $poss_syval;
12616: $realpossible++;
12617: }
12618: } else {
12619: $syval = $poss_syval;
12620: $realpossible++;
12621: }
12622: if ($syval) {
12623: if (ref($possibles) eq 'HASH') {
12624: $possibles->{$syval} = 1;
12625: }
12626: }
12627: }
12628: }
12629: }
12630: if ($realpossible!=1) { $syval=''; }
12631: } else {
12632: $syval='';
12633: }
12634: }
12635: untie(%bighash);
12636: }
12637: }
12638: if ($syval) {
12639: return $env{$cache_str}=$syval;
12640: }
12641: }
12642: &appenv({'request.ambiguous' => $thisfn});
12643: return $env{$cache_str}='';
12644: }
12645:
12646: # ---------------------------------------------------------- Return random seed
12647:
12648: sub numval {
12649: my $txt=shift;
12650: $txt=~tr/A-J/0-9/;
12651: $txt=~tr/a-j/0-9/;
12652: $txt=~tr/K-T/0-9/;
12653: $txt=~tr/k-t/0-9/;
12654: $txt=~tr/U-Z/0-5/;
12655: $txt=~tr/u-z/0-5/;
12656: $txt=~s/\D//g;
12657: if ($_64bit) { if ($txt > 2**32) { return -1; } }
12658: return int($txt);
12659: }
12660:
12661: sub numval2 {
12662: my $txt=shift;
12663: $txt=~tr/A-J/0-9/;
12664: $txt=~tr/a-j/0-9/;
12665: $txt=~tr/K-T/0-9/;
12666: $txt=~tr/k-t/0-9/;
12667: $txt=~tr/U-Z/0-5/;
12668: $txt=~tr/u-z/0-5/;
12669: $txt=~s/\D//g;
12670: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12671: my $total;
12672: foreach my $val (@txts) { $total+=$val; }
12673: if ($_64bit) { if ($total > 2**32) { return -1; } }
12674: return int($total);
12675: }
12676:
12677: sub numval3 {
12678: use integer;
12679: my $txt=shift;
12680: $txt=~tr/A-J/0-9/;
12681: $txt=~tr/a-j/0-9/;
12682: $txt=~tr/K-T/0-9/;
12683: $txt=~tr/k-t/0-9/;
12684: $txt=~tr/U-Z/0-5/;
12685: $txt=~tr/u-z/0-5/;
12686: $txt=~s/\D//g;
12687: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12688: my $total;
12689: foreach my $val (@txts) { $total+=$val; }
12690: if ($_64bit) { $total=(($total<<32)>>32); }
12691: return $total;
12692: }
12693:
12694: sub digest {
12695: my ($data)=@_;
12696: my $digest=&Digest::MD5::md5($data);
12697: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12698: my ($e,$f);
12699: {
12700: use integer;
12701: $e=($a+$b);
12702: $f=($c+$d);
12703: if ($_64bit) {
12704: $e=(($e<<32)>>32);
12705: $f=(($f<<32)>>32);
12706: }
12707: }
12708: if (wantarray) {
12709: return ($e,$f);
12710: } else {
12711: my $g;
12712: {
12713: use integer;
12714: $g=($e+$f);
12715: if ($_64bit) {
12716: $g=(($g<<32)>>32);
12717: }
12718: }
12719: return $g;
12720: }
12721: }
12722:
12723: sub latest_rnd_algorithm_id {
12724: return '64bit5';
12725: }
12726:
12727: sub get_rand_alg {
12728: my ($courseid)=@_;
12729: if (!$courseid) { $courseid=(&whichuser())[1]; }
12730: if ($courseid) {
12731: return $env{"course.$courseid.rndseed"};
12732: }
12733: return &latest_rnd_algorithm_id();
12734: }
12735:
12736: sub validCODE {
12737: my ($CODE)=@_;
12738: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12739: return 0;
12740: }
12741:
12742: sub getCODE {
12743: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12744: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12745: defined($Apache::lonhomework::parsing_a_task) ) &&
12746: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12747: return $Apache::lonhomework::history{'resource.CODE'};
12748: }
12749: return undef;
12750: }
12751: #
12752: # Determines the random seed for a specific context:
12753: #
12754: # parameters:
12755: # symb - in course context the symb for the seed.
12756: # course_id - The course id of the form domain_coursenum.
12757: # domain - Domain for the user.
12758: # course - Course for the user.
12759: # cenv - environment of the course.
12760: #
12761: # NOTE:
12762: # All parameters are picked out of the environment if missing
12763: # or not defined.
12764: # If a symb cannot be determined the current time is used instead.
12765: #
12766: # For a given well defined symb, courside, domain, username,
12767: # and course environment, the seed is reproducible.
12768: #
12769: sub rndseed {
12770: my ($symb,$courseid,$domain,$username, $cenv)=@_;
12771: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12772: if (!defined($symb)) {
12773: unless ($symb=$wsymb) { return time; }
12774: }
12775: if (!defined $courseid) {
12776: $courseid=$wcourseid;
12777: }
12778: if (!defined $domain) { $domain=$wdomain; }
12779: if (!defined $username) { $username=$wusername }
12780:
12781: my $which;
12782: if (defined($cenv->{'rndseed'})) {
12783: $which = $cenv->{'rndseed'};
12784: } else {
12785: $which =&get_rand_alg($courseid);
12786: }
12787: if (defined(&getCODE())) {
12788: if ($which eq '64bit5') {
12789: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12790: } elsif ($which eq '64bit4') {
12791: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12792: } else {
12793: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12794: }
12795: } elsif ($which eq '64bit5') {
12796: return &rndseed_64bit5($symb,$courseid,$domain,$username);
12797: } elsif ($which eq '64bit4') {
12798: return &rndseed_64bit4($symb,$courseid,$domain,$username);
12799: } elsif ($which eq '64bit3') {
12800: return &rndseed_64bit3($symb,$courseid,$domain,$username);
12801: } elsif ($which eq '64bit2') {
12802: return &rndseed_64bit2($symb,$courseid,$domain,$username);
12803: } elsif ($which eq '64bit') {
12804: return &rndseed_64bit($symb,$courseid,$domain,$username);
12805: }
12806: return &rndseed_32bit($symb,$courseid,$domain,$username);
12807: }
12808:
12809: sub rndseed_32bit {
12810: my ($symb,$courseid,$domain,$username)=@_;
12811: {
12812: use integer;
12813: my $symbchck=unpack("%32C*",$symb) << 27;
12814: my $symbseed=numval($symb) << 22;
12815: my $namechck=unpack("%32C*",$username) << 17;
12816: my $nameseed=numval($username) << 12;
12817: my $domainseed=unpack("%32C*",$domain) << 7;
12818: my $courseseed=unpack("%32C*",$courseid);
12819: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12820: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12821: #&logthis("rndseed :$num:$symb");
12822: if ($_64bit) { $num=(($num<<32)>>32); }
12823: return $num;
12824: }
12825: }
12826:
12827: sub rndseed_64bit {
12828: my ($symb,$courseid,$domain,$username)=@_;
12829: {
12830: use integer;
12831: my $symbchck=unpack("%32S*",$symb) << 21;
12832: my $symbseed=numval($symb) << 10;
12833: my $namechck=unpack("%32S*",$username);
12834:
12835: my $nameseed=numval($username) << 21;
12836: my $domainseed=unpack("%32S*",$domain) << 10;
12837: my $courseseed=unpack("%32S*",$courseid);
12838:
12839: my $num1=$symbchck+$symbseed+$namechck;
12840: my $num2=$nameseed+$domainseed+$courseseed;
12841: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12842: #&logthis("rndseed :$num:$symb");
12843: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12844: return "$num1,$num2";
12845: }
12846: }
12847:
12848: sub rndseed_64bit2 {
12849: my ($symb,$courseid,$domain,$username)=@_;
12850: {
12851: use integer;
12852: # strings need to be an even # of cahracters long, it it is odd the
12853: # last characters gets thrown away
12854: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12855: my $symbseed=numval($symb) << 10;
12856: my $namechck=unpack("%32S*",$username.' ');
12857:
12858: my $nameseed=numval($username) << 21;
12859: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12860: my $courseseed=unpack("%32S*",$courseid.' ');
12861:
12862: my $num1=$symbchck+$symbseed+$namechck;
12863: my $num2=$nameseed+$domainseed+$courseseed;
12864: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12865: #&logthis("rndseed :$num:$symb");
12866: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12867: return "$num1,$num2";
12868: }
12869: }
12870:
12871: sub rndseed_64bit3 {
12872: my ($symb,$courseid,$domain,$username)=@_;
12873: {
12874: use integer;
12875: # strings need to be an even # of cahracters long, it it is odd the
12876: # last characters gets thrown away
12877: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12878: my $symbseed=numval2($symb) << 10;
12879: my $namechck=unpack("%32S*",$username.' ');
12880:
12881: my $nameseed=numval2($username) << 21;
12882: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12883: my $courseseed=unpack("%32S*",$courseid.' ');
12884:
12885: my $num1=$symbchck+$symbseed+$namechck;
12886: my $num2=$nameseed+$domainseed+$courseseed;
12887: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12888: #&logthis("rndseed :$num1:$num2:$_64bit");
12889: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12890:
12891: return "$num1:$num2";
12892: }
12893: }
12894:
12895: sub rndseed_64bit4 {
12896: my ($symb,$courseid,$domain,$username)=@_;
12897: {
12898: use integer;
12899: # strings need to be an even # of cahracters long, it it is odd the
12900: # last characters gets thrown away
12901: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12902: my $symbseed=numval3($symb) << 10;
12903: my $namechck=unpack("%32S*",$username.' ');
12904:
12905: my $nameseed=numval3($username) << 21;
12906: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12907: my $courseseed=unpack("%32S*",$courseid.' ');
12908:
12909: my $num1=$symbchck+$symbseed+$namechck;
12910: my $num2=$nameseed+$domainseed+$courseseed;
12911: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12912: #&logthis("rndseed :$num1:$num2:$_64bit");
12913: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12914:
12915: return "$num1:$num2";
12916: }
12917: }
12918:
12919: sub rndseed_64bit5 {
12920: my ($symb,$courseid,$domain,$username)=@_;
12921: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12922: return "$num1:$num2";
12923: }
12924:
12925: sub rndseed_CODE_64bit {
12926: my ($symb,$courseid,$domain,$username)=@_;
12927: {
12928: use integer;
12929: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12930: my $symbseed=numval2($symb);
12931: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12932: my $CODEseed=numval(&getCODE());
12933: my $courseseed=unpack("%32S*",$courseid.' ');
12934: my $num1=$symbseed+$CODEchck;
12935: my $num2=$CODEseed+$courseseed+$symbchck;
12936: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12937: #&logthis("rndseed :$num1:$num2:$symb");
12938: if ($_64bit) { $num1=(($num1<<32)>>32); }
12939: if ($_64bit) { $num2=(($num2<<32)>>32); }
12940: return "$num1:$num2";
12941: }
12942: }
12943:
12944: sub rndseed_CODE_64bit4 {
12945: my ($symb,$courseid,$domain,$username)=@_;
12946: {
12947: use integer;
12948: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12949: my $symbseed=numval3($symb);
12950: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12951: my $CODEseed=numval3(&getCODE());
12952: my $courseseed=unpack("%32S*",$courseid.' ');
12953: my $num1=$symbseed+$CODEchck;
12954: my $num2=$CODEseed+$courseseed+$symbchck;
12955: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12956: #&logthis("rndseed :$num1:$num2:$symb");
12957: if ($_64bit) { $num1=(($num1<<32)>>32); }
12958: if ($_64bit) { $num2=(($num2<<32)>>32); }
12959: return "$num1:$num2";
12960: }
12961: }
12962:
12963: sub rndseed_CODE_64bit5 {
12964: my ($symb,$courseid,$domain,$username)=@_;
12965: my $code = &getCODE();
12966: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12967: return "$num1:$num2";
12968: }
12969:
12970: sub setup_random_from_rndseed {
12971: my ($rndseed)=@_;
12972: if ($rndseed =~/([,:])/) {
12973: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12974: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12975: &Math::Random::random_set_seed_from_phrase($rndseed);
12976: } else {
12977: &Math::Random::random_set_seed($num1,$num2);
12978: }
12979: } else {
12980: &Math::Random::random_set_seed_from_phrase($rndseed);
12981: }
12982: }
12983:
12984: sub latest_receipt_algorithm_id {
12985: return 'receipt3';
12986: }
12987:
12988: sub recunique {
12989: my $fucourseid=shift;
12990: my $unique;
12991: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12992: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12993: $unique=$env{"course.$fucourseid.internal.encseed"};
12994: } else {
12995: $unique=$perlvar{'lonReceipt'};
12996: }
12997: return unpack("%32C*",$unique);
12998: }
12999:
13000: sub recprefix {
13001: my $fucourseid=shift;
13002: my $prefix;
13003: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13004: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13005: $prefix=$env{"course.$fucourseid.internal.encpref"};
13006: } else {
13007: $prefix=$perlvar{'lonHostID'};
13008: }
13009: return unpack("%32C*",$prefix);
13010: }
13011:
13012: sub ireceipt {
13013: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13014:
13015: my $return =&recprefix($fucourseid).'-';
13016:
13017: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13018: $env{'request.state'} eq 'construct') {
13019: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13020: return $return;
13021: }
13022:
13023: my $cuname=unpack("%32C*",$funame);
13024: my $cudom=unpack("%32C*",$fudom);
13025: my $cucourseid=unpack("%32C*",$fucourseid);
13026: my $cusymb=unpack("%32C*",$fusymb);
13027: my $cunique=&recunique($fucourseid);
13028: my $cpart=unpack("%32S*",$part);
13029: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13030:
13031: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
13032:
13033: $return.= ($cunique%$cuname+
13034: $cunique%$cudom+
13035: $cusymb%$cuname+
13036: $cusymb%$cudom+
13037: $cucourseid%$cuname+
13038: $cucourseid%$cudom+
13039: $cpart%$cuname+
13040: $cpart%$cudom);
13041: } else {
13042: $return.= ($cunique%$cuname+
13043: $cunique%$cudom+
13044: $cusymb%$cuname+
13045: $cusymb%$cudom+
13046: $cucourseid%$cuname+
13047: $cucourseid%$cudom);
13048: }
13049: return $return;
13050: }
13051:
13052: sub receipt {
13053: my ($part)=@_;
13054: my ($symb,$courseid,$domain,$name) = &whichuser();
13055: return &ireceipt($name,$domain,$courseid,$symb,$part);
13056: }
13057:
13058: sub whichuser {
13059: my ($passedsymb)=@_;
13060: my ($symb,$courseid,$domain,$name,$publicuser);
13061: if (defined($env{'form.grade_symb'})) {
13062: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13063: my $allowed=&allowed('vgr',$tmp_courseid);
13064: if (!$allowed &&
13065: exists($env{'request.course.sec'}) &&
13066: $env{'request.course.sec'} !~ /^\s*$/) {
13067: $allowed=&allowed('vgr',$tmp_courseid.
13068: '/'.$env{'request.course.sec'});
13069: }
13070: if ($allowed) {
13071: ($symb)=&get_env_multiple('form.grade_symb');
13072: $courseid=$tmp_courseid;
13073: ($domain)=&get_env_multiple('form.grade_domain');
13074: ($name)=&get_env_multiple('form.grade_username');
13075: return ($symb,$courseid,$domain,$name,$publicuser);
13076: }
13077: }
13078: if (!$passedsymb) {
13079: $symb=&symbread();
13080: } else {
13081: $symb=$passedsymb;
13082: }
13083: $courseid=$env{'request.course.id'};
13084: $domain=$env{'user.domain'};
13085: $name=$env{'user.name'};
13086: if ($name eq 'public' && $domain eq 'public') {
13087: if (!defined($env{'form.username'})) {
13088: $env{'form.username'}.=time.rand(10000000);
13089: }
13090: $name.=$env{'form.username'};
13091: }
13092: return ($symb,$courseid,$domain,$name,$publicuser);
13093:
13094: }
13095:
13096: # ------------------------------------------------------------ Serves up a file
13097: # returns either the contents of the file or
13098: # -1 if the file doesn't exist
13099: #
13100: # if the target is a file that was uploaded via DOCS,
13101: # a check will be made to see if a current copy exists on the local server,
13102: # if it does this will be served, otherwise a copy will be retrieved from
13103: # the home server for the course and stored in /home/httpd/html/userfiles on
13104: # the local server.
13105:
13106: sub getfile {
13107: my ($file) = @_;
13108: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13109: &repcopy($file);
13110: return &readfile($file);
13111: }
13112:
13113: sub repcopy_userfile {
13114: my ($file)=@_;
13115: my $londocroot = $perlvar{'lonDocRoot'};
13116: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13117: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13118: my ($cdom,$cnum,$filename) =
13119: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13120: my $uri="/uploaded/$cdom/$cnum/$filename";
13121: if (-e "$file") {
13122: # we already have a local copy, check it out
13123: my @fileinfo = stat($file);
13124: my $rtncode;
13125: my $info;
13126: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13127: if ($lwpresp ne 'ok') {
13128: # there is no such file anymore, even though we had a local copy
13129: if ($rtncode eq '404') {
13130: unlink($file);
13131: }
13132: return -1;
13133: }
13134: if ($info < $fileinfo[9]) {
13135: # nice, the file we have is up-to-date, just say okay
13136: return 'ok';
13137: } else {
13138: # the file is outdated, get rid of it
13139: unlink($file);
13140: }
13141: }
13142: # one way or the other, at this point, we don't have the file
13143: # construct the correct path for the file
13144: my @parts = ($cdom,$cnum);
13145: if ($filename =~ m|^(.+)/[^/]+$|) {
13146: push @parts, split(/\//,$1);
13147: }
13148: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13149: foreach my $part (@parts) {
13150: $path .= '/'.$part;
13151: if (!-e $path) {
13152: mkdir($path,0770);
13153: }
13154: }
13155: # now the path exists for sure
13156: # get a user agent
13157: my $ua=new LWP::UserAgent;
13158: my $transferfile=$file.'.in.transfer';
13159: # FIXME: this should flock
13160: if (-e $transferfile) { return 'ok'; }
13161: my $request;
13162: $uri=~s/^\///;
13163: my $homeserver = &homeserver($cnum,$cdom);
13164: my $hostname = &hostname($homeserver);
13165: my $protocol = $protocol{$homeserver};
13166: $protocol = 'http' if ($protocol ne 'https');
13167: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13168: my $response=$ua->request($request,$transferfile);
13169: # did it work?
13170: if ($response->is_error()) {
13171: unlink($transferfile);
13172: &logthis("Userfile repcopy failed for $uri");
13173: return -1;
13174: }
13175: # worked, rename the transfer file
13176: rename($transferfile,$file);
13177: return 'ok';
13178: }
13179:
13180: sub tokenwrapper {
13181: my $uri=shift;
13182: $uri=~s|^https?\://([^/]+)||;
13183: $uri=~s|^/||;
13184: $env{'user.environment'}=~/\/([^\/]+)\.id/;
13185: my $token=$1;
13186: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13187: if ($udom && $uname && $file) {
13188: $file=~s|(\?\.*)*$||;
13189: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13190: my $homeserver = &homeserver($uname,$udom);
13191: my $hostname = &hostname($homeserver);
13192: my $protocol = $protocol{$homeserver};
13193: $protocol = 'http' if ($protocol ne 'https');
13194: return $protocol.'://'.$hostname.'/'.$uri.
13195: (($uri=~/\?/)?'&':'?').'token='.$token.
13196: '&tokenissued='.$perlvar{'lonHostID'};
13197: } else {
13198: return '/adm/notfound.html';
13199: }
13200: }
13201:
13202: # call with reqtype HEAD: get last modification time
13203: # call with reqtype GET: get the file contents
13204: # Do not call this with reqtype GET for large files! It loads everything into memory
13205: #
13206: sub getuploaded {
13207: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13208: $uri=~s/^\///;
13209: my $homeserver = &homeserver($cnum,$cdom);
13210: my $hostname = &hostname($homeserver);
13211: my $protocol = $protocol{$homeserver};
13212: $protocol = 'http' if ($protocol ne 'https');
13213: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13214: my $ua=new LWP::UserAgent;
13215: my $request=new HTTP::Request($reqtype,$uri);
13216: my $response=$ua->request($request);
13217: $$rtncode = $response->code;
13218: if (! $response->is_success()) {
13219: return 'failed';
13220: }
13221: if ($reqtype eq 'HEAD') {
13222: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13223: } elsif ($reqtype eq 'GET') {
13224: $$info = $response->content;
13225: }
13226: return 'ok';
13227: }
13228:
13229: sub readfile {
13230: my $file = shift;
13231: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13232: my $fh;
13233: open($fh,"<",$file);
13234: my $a='';
13235: while (my $line = <$fh>) { $a .= $line; }
13236: return $a;
13237: }
13238:
13239: sub filelocation {
13240: my ($dir,$file) = @_;
13241: my $location;
13242: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13243:
13244: if ($file =~ m-^/adm/-) {
13245: $file=~s-^/adm/wrapper/-/-;
13246: $file=~s-^/adm/coursedocs/showdoc/-/-;
13247: }
13248:
13249: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13250: $location = $file;
13251: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13252: my ($udom,$uname,$filename)=
13253: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13254: my $home=&homeserver($uname,$udom);
13255: my $is_me=0;
13256: my @ids=¤t_machine_ids();
13257: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13258: if ($is_me) {
13259: $location=propath($udom,$uname).'/userfiles/'.$filename;
13260: } else {
13261: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13262: $udom.'/'.$uname.'/'.$filename;
13263: }
13264: } elsif ($file =~ m-^/adm/-) {
13265: $location = $perlvar{'lonDocRoot'}.'/'.$file;
13266: } else {
13267: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13268: $file=~s:^/(res|priv)/:/:;
13269: my $space=$1;
13270: if ( !( $file =~ m:^/:) ) {
13271: $location = $dir. '/'.$file;
13272: } else {
13273: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13274: }
13275: }
13276: $location=~s://+:/:g; # remove duplicate /
13277: while ($location=~m{/\.\./}) {
13278: if ($location =~ m{/[^/]+/\.\./}) {
13279: $location=~ s{/[^/]+/\.\./}{/}g;
13280: } else {
13281: $location=~ s{/\.\./}{/}g;
13282: }
13283: } #remove dir/..
13284: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13285: return $location;
13286: }
13287:
13288: sub hreflocation {
13289: my ($dir,$file)=@_;
13290: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13291: $file=filelocation($dir,$file);
13292: } elsif ($file=~m-^/adm/-) {
13293: $file=~s-^/adm/wrapper/-/-;
13294: $file=~s-^/adm/coursedocs/showdoc/-/-;
13295: }
13296: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13297: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13298: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13299: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13300: {/uploaded/$1/$2/}x;
13301: }
13302: if ($file=~ m{^/userfiles/}) {
13303: $file =~ s{^/userfiles/}{/uploaded/};
13304: }
13305: return $file;
13306: }
13307:
13308:
13309:
13310:
13311:
13312: sub current_machine_domains {
13313: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13314: }
13315:
13316: sub machine_domains {
13317: my ($hostname) = @_;
13318: my @domains;
13319: my %hostname = &all_hostnames();
13320: while( my($id, $name) = each(%hostname)) {
13321: # &logthis("-$id-$name-$hostname-");
13322: if ($hostname eq $name) {
13323: push(@domains,&host_domain($id));
13324: }
13325: }
13326: return @domains;
13327: }
13328:
13329: sub current_machine_ids {
13330: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13331: }
13332:
13333: sub machine_ids {
13334: my ($hostname) = @_;
13335: $hostname ||= &hostname($perlvar{'lonHostID'});
13336: my @ids;
13337: my %name_to_host = &all_names();
13338: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13339: return @{ $name_to_host{$hostname} };
13340: }
13341: return;
13342: }
13343:
13344: sub additional_machine_domains {
13345: my @domains;
13346: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13347: while( my $line = <$fh>) {
13348: $line =~ s/\s//g;
13349: push(@domains,$line);
13350: }
13351: return @domains;
13352: }
13353:
13354: sub default_login_domain {
13355: my $domain = $perlvar{'lonDefDomain'};
13356: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13357: foreach my $posdom (¤t_machine_domains(),
13358: &additional_machine_domains()) {
13359: if (lc($posdom) eq lc($testdomain)) {
13360: $domain=$posdom;
13361: last;
13362: }
13363: }
13364: return $domain;
13365: }
13366:
13367: sub shared_institution {
13368: my ($dom,$lonhost) = @_;
13369: if ($lonhost eq '') {
13370: $lonhost = $perlvar{'lonHostID'};
13371: }
13372: my $same_intdom;
13373: my $hostintdom = &internet_dom($lonhost);
13374: if ($hostintdom ne '') {
13375: my %iphost = &get_iphost();
13376: my $primary_id = &domain($dom,'primary');
13377: my $primary_ip = &get_host_ip($primary_id);
13378: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13379: foreach my $id (@{$iphost{$primary_ip}}) {
13380: my $intdom = &internet_dom($id);
13381: if ($intdom eq $hostintdom) {
13382: $same_intdom = 1;
13383: last;
13384: }
13385: }
13386: }
13387: }
13388: return $same_intdom;
13389: }
13390:
13391: sub uses_sts {
13392: my ($ignore_cache) = @_;
13393: my $lonhost = $perlvar{'lonHostID'};
13394: my $hostname = &hostname($lonhost);
13395: my $sts_on;
13396: if ($protocol{$lonhost} eq 'https') {
13397: my $cachetime = 12*3600;
13398: if (!$ignore_cache) {
13399: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13400: if (defined($cached)) {
13401: return $sts_on;
13402: }
13403: }
13404: my $ua=new LWP::UserAgent;
13405: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13406: my $request=new HTTP::Request('HEAD',$url);
13407: my $response=$ua->request($request);
13408: if ($response->is_success) {
13409: my $has_sts = $response->header('Strict-Transport-Security');
13410: if ($has_sts eq '') {
13411: $sts_on = 0;
13412: } else {
13413: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13414: my $maxage = $1;
13415: if ($maxage) {
13416: $sts_on = 1;
13417: } else {
13418: $sts_on = 0;
13419: }
13420: } else {
13421: $sts_on = 0;
13422: }
13423: }
13424: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13425: }
13426: }
13427: return;
13428: }
13429:
13430: sub get_requestor_ip {
13431: my ($r,$nolookup,$noproxy) = @_;
13432: my $from_ip;
13433: if (ref($r)) {
13434: $from_ip = $r->get_remote_host($nolookup);
13435: } else {
13436: $from_ip = $ENV{'REMOTE_ADDR'};
13437: }
13438: return $from_ip;
13439: }
13440:
13441: # ------------------------------------------------------------- Declutters URLs
13442:
13443: sub declutter {
13444: my $thisfn=shift;
13445: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13446: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13447: $thisfn=~s{^/home/httpd/html}{};
13448: }
13449: $thisfn=~s/^\///;
13450: $thisfn=~s|^adm/wrapper/||;
13451: $thisfn=~s|^adm/coursedocs/showdoc/||;
13452: $thisfn=~s/^res\///;
13453: $thisfn=~s/^priv\///;
13454: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13455: $thisfn=~s/\?.+$//;
13456: }
13457: return $thisfn;
13458: }
13459:
13460: # ------------------------------------------------------------- Clutter up URLs
13461:
13462: sub clutter {
13463: my $thisfn='/'.&declutter(shift);
13464: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13465: || $thisfn =~ m{^/adm/(includes|pages)} ) {
13466: $thisfn='/res'.$thisfn;
13467: }
13468: if ($thisfn !~m|^/adm|) {
13469: if ($thisfn =~ m|^/ext/|) {
13470: $thisfn='/adm/wrapper'.$thisfn;
13471: } else {
13472: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13473: my $embstyle=&Apache::loncommon::fileembstyle($ext);
13474: if ($embstyle eq 'ssi'
13475: || ($embstyle eq 'hdn')
13476: || ($embstyle eq 'rat')
13477: || ($embstyle eq 'prv')
13478: || ($embstyle eq 'ign')) {
13479: #do nothing with these
13480: } elsif (($embstyle eq 'img')
13481: || ($embstyle eq 'emb')
13482: || ($embstyle eq 'wrp')) {
13483: $thisfn='/adm/wrapper'.$thisfn;
13484: } elsif ($embstyle eq 'unk'
13485: && $thisfn!~/\.(sequence|page)$/) {
13486: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
13487: } else {
13488: # &logthis("Got a blank emb style");
13489: }
13490: }
13491: }
13492: return $thisfn;
13493: }
13494:
13495: sub clutter_with_no_wrapper {
13496: my $uri = &clutter(shift);
13497: if ($uri =~ m-^/adm/-) {
13498: $uri =~ s-^/adm/wrapper/-/-;
13499: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13500: }
13501: return $uri;
13502: }
13503:
13504: sub freeze_escape {
13505: my ($value)=@_;
13506: if (ref($value)) {
13507: $value=&nfreeze($value);
13508: return '__FROZEN__'.&escape($value);
13509: }
13510: return &escape($value);
13511: }
13512:
13513:
13514: sub thaw_unescape {
13515: my ($value)=@_;
13516: if ($value =~ /^__FROZEN__/) {
13517: substr($value,0,10,undef);
13518: $value=&unescape($value);
13519: return &thaw($value);
13520: }
13521: return &unescape($value);
13522: }
13523:
13524: sub correct_line_ends {
13525: my ($result)=@_;
13526: $$result =~s/\r\n/\n/mg;
13527: $$result =~s/\r/\n/mg;
13528: }
13529: # ================================================================ Main Program
13530:
13531: sub goodbye {
13532: &logthis("Starting Shut down");
13533: #not converted to using infrastruture and probably shouldn't be
13534: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13535: #converted
13536: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13537: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13538: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13539: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13540: #1.1 only
13541: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13542: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13543: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13544: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13545: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13546: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13547: &logthis(sprintf("%-20s is %s",'hits',$hits));
13548: &flushcourselogs();
13549: &logthis("Shutting down");
13550: }
13551:
13552: sub get_dns {
13553: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13554: if (!$ignore_cache) {
13555: my ($content,$cached)=
13556: &Apache::lonnet::is_cached_new('dns',$url);
13557: if ($cached) {
13558: &$func($content,$hashref);
13559: return;
13560: }
13561: }
13562:
13563: my %alldns;
13564: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13565: foreach my $dns (<$config>) {
13566: next if ($dns !~ /^\^(\S*)/x);
13567: my $line = $1;
13568: my ($host,$protocol) = split(/:/,$line);
13569: if ($protocol ne 'https') {
13570: $protocol = 'http';
13571: }
13572: $alldns{$host} = $protocol;
13573: }
13574: close($config);
13575: }
13576: while (%alldns) {
13577: my ($dns) = sort { $b cmp $a } keys(%alldns);
13578: my $ua=new LWP::UserAgent;
13579: $ua->timeout(30);
13580: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13581: my $response=$ua->request($request);
13582: delete($alldns{$dns});
13583: next if ($response->is_error());
13584: my @content = split("\n",$response->content);
13585: unless ($nocache) {
13586: &do_cache_new('dns',$url,\@content,30*24*60*60);
13587: }
13588: &$func(\@content,$hashref);
13589: return;
13590: }
13591: my $which = (split('/',$url))[3];
13592: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13593: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13594: my @content = <$config>;
13595: &$func(\@content,$hashref);
13596: }
13597: return;
13598: }
13599:
13600: # ------------------------------------------------------Get DNS checksums file
13601: sub parse_dns_checksums_tab {
13602: my ($lines,$hashref) = @_;
13603: my $lonhost = $perlvar{'lonHostID'};
13604: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13605: my $loncaparev = &get_server_loncaparev($machine_dom);
13606: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13607: my $webconfdir = '/etc/httpd/conf';
13608: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13609: $webconfdir = '/etc/apache2';
13610: } elsif ($distro =~ /^sles(\d+)$/) {
13611: if ($1 >= 10) {
13612: $webconfdir = '/etc/apache2';
13613: }
13614: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13615: if ($1 >= 10.0) {
13616: $webconfdir = '/etc/apache2';
13617: }
13618: }
13619: my ($release,$timestamp) = split(/\-/,$loncaparev);
13620: my (%chksum,%revnum);
13621: if (ref($lines) eq 'ARRAY') {
13622: chomp(@{$lines});
13623: my $version = shift(@{$lines});
13624: if ($version eq $release) {
13625: foreach my $line (@{$lines}) {
13626: my ($file,$version,$shasum) = split(/,/,$line);
13627: if ($file =~ m{^/etc/httpd/conf}) {
13628: if ($webconfdir eq '/etc/apache2') {
13629: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13630: }
13631: }
13632: $chksum{$file} = $shasum;
13633: $revnum{$file} = $version;
13634: }
13635: if (ref($hashref) eq 'HASH') {
13636: %{$hashref} = (
13637: sums => \%chksum,
13638: versions => \%revnum,
13639: );
13640: }
13641: }
13642: }
13643: return;
13644: }
13645:
13646: sub fetch_dns_checksums {
13647: my %checksums;
13648: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13649: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13650: my ($release,$timestamp) = split(/\-/,$loncaparev);
13651: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13652: \%checksums);
13653: return \%checksums;
13654: }
13655:
13656: # ------------------------------------------------------------ Read domain file
13657: {
13658: my $loaded;
13659: my %domain;
13660:
13661: sub parse_domain_tab {
13662: my ($lines) = @_;
13663: foreach my $line (@$lines) {
13664: next if ($line =~ /^(\#|\s*$ )/x);
13665:
13666: chomp($line);
13667: my ($name,@elements) = split(/:/,$line,9);
13668: my %this_domain;
13669: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13670: 'lang_def', 'city', 'longi', 'lati',
13671: 'primary') {
13672: $this_domain{$field} = shift(@elements);
13673: }
13674: $domain{$name} = \%this_domain;
13675: }
13676: }
13677:
13678: sub reset_domain_info {
13679: undef($loaded);
13680: undef(%domain);
13681: }
13682:
13683: sub load_domain_tab {
13684: my ($ignore_cache,$nocache) = @_;
13685: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13686: my $fh;
13687: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13688: my @lines = <$fh>;
13689: &parse_domain_tab(\@lines);
13690: }
13691: close($fh);
13692: $loaded = 1;
13693: }
13694:
13695: sub domain {
13696: &load_domain_tab() if (!$loaded);
13697:
13698: my ($name,$what) = @_;
13699: return if ( !exists($domain{$name}) );
13700:
13701: if (!$what) {
13702: return $domain{$name}{'description'};
13703: }
13704: return $domain{$name}{$what};
13705: }
13706:
13707: sub domain_info {
13708: &load_domain_tab() if (!$loaded);
13709: return %domain;
13710: }
13711:
13712: }
13713:
13714:
13715: # ------------------------------------------------------------- Read hosts file
13716: {
13717: my %hostname;
13718: my %hostdom;
13719: my %libserv;
13720: my $loaded;
13721: my %name_to_host;
13722: my %internetdom;
13723: my %LC_dns_serv;
13724:
13725: sub parse_hosts_tab {
13726: my ($file) = @_;
13727: foreach my $configline (@$file) {
13728: next if ($configline =~ /^(\#|\s*$ )/x);
13729: chomp($configline);
13730: if ($configline =~ /^\^/) {
13731: if ($configline =~ /^\^([\w.\-]+)/) {
13732: $LC_dns_serv{$1} = 1;
13733: }
13734: next;
13735: }
13736: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13737: $name=~s/\s//g;
13738: if ($id && $domain && $role && $name) {
13739: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13740: my $curr = $hostname{$id};
13741: my $skip;
13742: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13743: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13744: $skip = 1;
13745: } else {
13746: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13747: }
13748: }
13749: unless ($skip) {
13750: push(@{$name_to_host{$name}},$id);
13751: }
13752: } else {
13753: push(@{$name_to_host{$name}},$id);
13754: }
13755: $hostname{$id}=$name;
13756: $hostdom{$id}=$domain;
13757: if ($role eq 'library') { $libserv{$id}=$name; }
13758: if (defined($protocol)) {
13759: if ($protocol eq 'https') {
13760: $protocol{$id} = $protocol;
13761: } else {
13762: $protocol{$id} = 'http';
13763: }
13764: } else {
13765: $protocol{$id} = 'http';
13766: }
13767: if (defined($intdom)) {
13768: $internetdom{$id} = $intdom;
13769: }
13770: }
13771: }
13772: }
13773:
13774: sub reset_hosts_info {
13775: &purge_remembered();
13776: &reset_domain_info();
13777: &reset_hosts_ip_info();
13778: undef(%name_to_host);
13779: undef(%hostname);
13780: undef(%hostdom);
13781: undef(%libserv);
13782: undef($loaded);
13783: }
13784:
13785: sub load_hosts_tab {
13786: my ($ignore_cache,$nocache) = @_;
13787: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13788: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13789: my @config = <$config>;
13790: &parse_hosts_tab(\@config);
13791: close($config);
13792: $loaded=1;
13793: }
13794:
13795: sub hostname {
13796: &load_hosts_tab() if (!$loaded);
13797:
13798: my ($lonid) = @_;
13799: return $hostname{$lonid};
13800: }
13801:
13802: sub all_hostnames {
13803: &load_hosts_tab() if (!$loaded);
13804:
13805: return %hostname;
13806: }
13807:
13808: sub all_names {
13809: my ($ignore_cache,$nocache) = @_;
13810: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13811:
13812: return %name_to_host;
13813: }
13814:
13815: sub all_host_domain {
13816: &load_hosts_tab() if (!$loaded);
13817: return %hostdom;
13818: }
13819:
13820: sub is_library {
13821: &load_hosts_tab() if (!$loaded);
13822:
13823: return exists($libserv{$_[0]});
13824: }
13825:
13826: sub all_library {
13827: &load_hosts_tab() if (!$loaded);
13828:
13829: return %libserv;
13830: }
13831:
13832: sub unique_library {
13833: #2x reverse removes all hostnames that appear more than once
13834: my %unique = reverse &all_library();
13835: return reverse %unique;
13836: }
13837:
13838: sub get_servers {
13839: &load_hosts_tab() if (!$loaded);
13840:
13841: my ($domain,$type) = @_;
13842: my %possible_hosts = ($type eq 'library') ? %libserv
13843: : %hostname;
13844: my %result;
13845: if (ref($domain) eq 'ARRAY') {
13846: while ( my ($host,$hostname) = each(%possible_hosts)) {
13847: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13848: $result{$host} = $hostname;
13849: }
13850: }
13851: } else {
13852: while ( my ($host,$hostname) = each(%possible_hosts)) {
13853: if ($hostdom{$host} eq $domain) {
13854: $result{$host} = $hostname;
13855: }
13856: }
13857: }
13858: return %result;
13859: }
13860:
13861: sub get_unique_servers {
13862: my %unique = reverse &get_servers(@_);
13863: return reverse %unique;
13864: }
13865:
13866: sub host_domain {
13867: &load_hosts_tab() if (!$loaded);
13868:
13869: my ($lonid) = @_;
13870: return $hostdom{$lonid};
13871: }
13872:
13873: sub all_domains {
13874: &load_hosts_tab() if (!$loaded);
13875:
13876: my %seen;
13877: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13878: return @uniq;
13879: }
13880:
13881: sub internet_dom {
13882: &load_hosts_tab() if (!$loaded);
13883:
13884: my ($lonid) = @_;
13885: return $internetdom{$lonid};
13886: }
13887:
13888: sub is_LC_dns {
13889: &load_hosts_tab() if (!$loaded);
13890:
13891: my ($hostname) = @_;
13892: return exists($LC_dns_serv{$hostname});
13893: }
13894:
13895: }
13896:
13897: {
13898: my %iphost;
13899: my %name_to_ip;
13900: my %lonid_to_ip;
13901:
13902: sub get_hosts_from_ip {
13903: my ($ip) = @_;
13904: my %iphosts = &get_iphost();
13905: if (ref($iphosts{$ip})) {
13906: return @{$iphosts{$ip}};
13907: }
13908: return;
13909: }
13910:
13911: sub reset_hosts_ip_info {
13912: undef(%iphost);
13913: undef(%name_to_ip);
13914: undef(%lonid_to_ip);
13915: }
13916:
13917: sub get_host_ip {
13918: my ($lonid) = @_;
13919: if (exists($lonid_to_ip{$lonid})) {
13920: return $lonid_to_ip{$lonid};
13921: }
13922: my $name=&hostname($lonid);
13923: my $ip = gethostbyname($name);
13924: return if (!$ip || length($ip) ne 4);
13925: $ip=inet_ntoa($ip);
13926: $name_to_ip{$name} = $ip;
13927: $lonid_to_ip{$lonid} = $ip;
13928: return $ip;
13929: }
13930:
13931: sub get_iphost {
13932: my ($ignore_cache,$nocache) = @_;
13933:
13934: if (!$ignore_cache) {
13935: if (%iphost) {
13936: return %iphost;
13937: }
13938: my ($ip_info,$cached)=
13939: &Apache::lonnet::is_cached_new('iphost','iphost');
13940: if ($cached) {
13941: %iphost = %{$ip_info->[0]};
13942: %name_to_ip = %{$ip_info->[1]};
13943: %lonid_to_ip = %{$ip_info->[2]};
13944: return %iphost;
13945: }
13946: }
13947:
13948: # get yesterday's info for fallback
13949: my %old_name_to_ip;
13950: my ($ip_info,$cached)=
13951: &Apache::lonnet::is_cached_new('iphost','iphost');
13952: if ($cached) {
13953: %old_name_to_ip = %{$ip_info->[1]};
13954: }
13955:
13956: my %name_to_host = &all_names($ignore_cache,$nocache);
13957: foreach my $name (keys(%name_to_host)) {
13958: my $ip;
13959: if (!exists($name_to_ip{$name})) {
13960: $ip = gethostbyname($name);
13961: if (!$ip || length($ip) ne 4) {
13962: if (defined($old_name_to_ip{$name})) {
13963: $ip = $old_name_to_ip{$name};
13964: &logthis("Can't find $name defaulting to old $ip");
13965: } else {
13966: &logthis("Name $name no IP found");
13967: next;
13968: }
13969: } else {
13970: $ip=inet_ntoa($ip);
13971: }
13972: $name_to_ip{$name} = $ip;
13973: } else {
13974: $ip = $name_to_ip{$name};
13975: }
13976: foreach my $id (@{ $name_to_host{$name} }) {
13977: $lonid_to_ip{$id} = $ip;
13978: }
13979: push(@{$iphost{$ip}},@{$name_to_host{$name}});
13980: }
13981: unless ($nocache) {
13982: &do_cache_new('iphost','iphost',
13983: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13984: 48*60*60);
13985: }
13986:
13987: return %iphost;
13988: }
13989:
13990: #
13991: # Given a DNS returns the loncapa host name for that DNS
13992: #
13993: sub host_from_dns {
13994: my ($dns) = @_;
13995: my @hosts;
13996: my $ip;
13997:
13998: if (exists($name_to_ip{$dns})) {
13999: $ip = $name_to_ip{$dns};
14000: }
14001: if (!$ip) {
14002: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14003: if (length($ip) == 4) {
14004: $ip = &IO::Socket::inet_ntoa($ip);
14005: }
14006: }
14007: if ($ip) {
14008: @hosts = get_hosts_from_ip($ip);
14009: return $hosts[0];
14010: }
14011: return undef;
14012: }
14013:
14014: sub get_internet_names {
14015: my ($lonid) = @_;
14016: return if ($lonid eq '');
14017: my ($idnref,$cached)=
14018: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14019: if ($cached) {
14020: return $idnref;
14021: }
14022: my $ip = &get_host_ip($lonid);
14023: my @hosts = &get_hosts_from_ip($ip);
14024: my %iphost = &get_iphost();
14025: my (@idns,%seen);
14026: foreach my $id (@hosts) {
14027: my $dom = &host_domain($id);
14028: my $prim_id = &domain($dom,'primary');
14029: my $prim_ip = &get_host_ip($prim_id);
14030: next if ($seen{$prim_ip});
14031: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14032: foreach my $id (@{$iphost{$prim_ip}}) {
14033: my $intdom = &internet_dom($id);
14034: unless (grep(/^\Q$intdom\E$/,@idns)) {
14035: push(@idns,$intdom);
14036: }
14037: }
14038: }
14039: $seen{$prim_ip} = 1;
14040: }
14041: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14042: }
14043:
14044: }
14045:
14046: sub all_loncaparevs {
14047: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10 2.11);
14048: }
14049:
14050: # ------------------------------------------------------- Read loncaparev table
14051: {
14052: sub load_loncaparevs {
14053: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14054: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14055: while (my $configline=<$config>) {
14056: chomp($configline);
14057: my ($hostid,$loncaparev)=split(/:/,$configline);
14058: $loncaparevs{$hostid}=$loncaparev;
14059: }
14060: close($config);
14061: }
14062: }
14063: }
14064: }
14065:
14066: # ----------------------------------------------------- Read serverhostID table
14067: {
14068: sub load_serverhomeIDs {
14069: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14070: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14071: while (my $configline=<$config>) {
14072: chomp($configline);
14073: my ($name,$id)=split(/:/,$configline);
14074: $serverhomeIDs{$name}=$id;
14075: }
14076: close($config);
14077: }
14078: }
14079: }
14080: }
14081:
14082:
14083: BEGIN {
14084:
14085: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14086: unless ($readit) {
14087: {
14088: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14089: %perlvar = (%perlvar,%{$configvars});
14090: }
14091:
14092:
14093: # ------------------------------------------------------ Read spare server file
14094: {
14095: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14096:
14097: while (my $configline=<$config>) {
14098: chomp($configline);
14099: if ($configline) {
14100: my ($host,$type) = split(':',$configline,2);
14101: if (!defined($type) || $type eq '') { $type = 'default' };
14102: push(@{ $spareid{$type} }, $host);
14103: }
14104: }
14105: close($config);
14106: }
14107: # ------------------------------------------------------------ Read permissions
14108: {
14109: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14110:
14111: while (my $configline=<$config>) {
14112: chomp($configline);
14113: if ($configline) {
14114: my ($role,$perm)=split(/ /,$configline);
14115: if ($perm ne '') { $pr{$role}=$perm; }
14116: }
14117: }
14118: close($config);
14119: }
14120:
14121: # -------------------------------------------- Read plain texts for permissions
14122: {
14123: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14124:
14125: while (my $configline=<$config>) {
14126: chomp($configline);
14127: if ($configline) {
14128: my ($short,@plain)=split(/:/,$configline);
14129: %{$prp{$short}} = ();
14130: if (@plain > 0) {
14131: $prp{$short}{'std'} = $plain[0];
14132: for (my $i=1; $i<@plain; $i++) {
14133: $prp{$short}{'alt'.$i} = $plain[$i];
14134: }
14135: }
14136: }
14137: }
14138: close($config);
14139: }
14140:
14141: # ---------------------------------------------------------- Read package table
14142: {
14143: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14144:
14145: while (my $configline=<$config>) {
14146: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14147: chomp($configline);
14148: my ($short,$plain)=split(/:/,$configline);
14149: my ($pack,$name)=split(/\&/,$short);
14150: if ($plain ne '') {
14151: $packagetab{$pack.'&'.$name.'&name'}=$name;
14152: $packagetab{$short}=$plain;
14153: }
14154: }
14155: close($config);
14156: }
14157:
14158: # --------------------------------------------------------- Read loncaparev table
14159:
14160: &load_loncaparevs();
14161:
14162: # ------------------------------------------------------- Read serverhostID table
14163:
14164: &load_serverhomeIDs();
14165:
14166: # ---------------------------------------------------------- Read releaseslist XML
14167: {
14168: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14169: if (-e $file) {
14170: my $parser = HTML::LCParser->new($file);
14171: while (my $token = $parser->get_token()) {
14172: if ($token->[0] eq 'S') {
14173: my $item = $token->[1];
14174: my $name = $token->[2]{'name'};
14175: my $value = $token->[2]{'value'};
14176: if ($item ne '' && $name ne '' && $value ne '') {
14177: my $release = $parser->get_text();
14178: $release =~ s/(^\s*|\s*$ )//gx;
14179: $needsrelease{$item.':'.$name.':'.$value} = $release;
14180: }
14181: }
14182: }
14183: }
14184: }
14185:
14186: # ---------------------------------------------------------- Read managers table
14187: {
14188: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14189: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14190: while (my $configline=<$config>) {
14191: chomp($configline);
14192: next if ($configline =~ /^\#/);
14193: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14194: $managerstab{$configline} = 1;
14195: }
14196: }
14197: close($config);
14198: }
14199: }
14200: }
14201:
14202: # ------------- set up temporary directory
14203: {
14204: $tmpdir = LONCAPA::tempdir();
14205:
14206: }
14207:
14208: # ------------- set default texengine (domain default overrides this)
14209: {
14210: $deftex = LONCAPA::texengine();
14211: }
14212:
14213: # ------------- set default minimum length for passwords for internal auth users
14214: {
14215: $passwdmin = LONCAPA::passwd_min();
14216: }
14217:
14218: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14219: 'compress_threshold'=> 20_000,
14220: });
14221:
14222: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14223: $dumpcount=0;
14224: $locknum=0;
14225:
14226: &logtouch();
14227: &logthis('<font color="yellow">INFO: Read configuration</font>');
14228: $readit=1;
14229: {
14230: use integer;
14231: my $test=(2**32)+1;
14232: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14233: &logthis(" Detected 64bit platform ($_64bit)");
14234: }
14235: }
14236: }
14237:
14238: 1;
14239: __END__
14240:
14241: =pod
14242:
14243: =head1 NAME
14244:
14245: Apache::lonnet - Subroutines to ask questions about things in the network.
14246:
14247: =head1 SYNOPSIS
14248:
14249: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14250:
14251: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14252:
14253: Common parameters:
14254:
14255: =over 4
14256:
14257: =item *
14258:
14259: $uname : an internal username (if $cname expecting a course Id specifically)
14260:
14261: =item *
14262:
14263: $udom : a domain (if $cdom expecting a course's domain specifically)
14264:
14265: =item *
14266:
14267: $symb : a resource instance identifier
14268:
14269: =item *
14270:
14271: $namespace : the name of a .db file that contains the data needed or
14272: being set.
14273:
14274: =back
14275:
14276: =head1 OVERVIEW
14277:
14278: lonnet provides subroutines which interact with the
14279: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14280: about classes, users, and resources.
14281:
14282: For many of these objects you can also use this to store data about
14283: them or modify them in various ways.
14284:
14285: =head2 Symbs
14286:
14287: To identify a specific instance of a resource, LON-CAPA uses symbols
14288: or "symbs"X<symb>. These identifiers are built from the URL of the
14289: map, the resource number of the resource in the map, and the URL of
14290: the resource itself. The latter is somewhat redundant, but might help
14291: if maps change.
14292:
14293: An example is
14294:
14295: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14296:
14297: The respective map entry is
14298:
14299: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14300: title="Problem 2">
14301: </resource>
14302:
14303: Symbs are used by the random number generator, as well as to store and
14304: restore data specific to a certain instance of for example a problem.
14305:
14306: =head2 Storing And Retrieving Data
14307:
14308: X<store()>X<cstore()>X<restore()>Three of the most important functions
14309: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14310: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14311: is is the non-critical message twin of cstore. These functions are for
14312: handlers to store a perl hash to a user's permanent data space in an
14313: easy manner, and to retrieve it again on another call. It is expected
14314: that a handler would use this once at the beginning to retrieve data,
14315: and then again once at the end to send only the new data back.
14316:
14317: The data is stored in the user's data directory on the user's
14318: homeserver under the ID of the course.
14319:
14320: The hash that is returned by restore will have all of the previous
14321: value for all of the elements of the hash.
14322:
14323: Example:
14324:
14325: #creating a hash
14326: my %hash;
14327: $hash{'foo'}='bar';
14328:
14329: #storing it
14330: &Apache::lonnet::cstore(\%hash);
14331:
14332: #changing a value
14333: $hash{'foo'}='notbar';
14334:
14335: #adding a new value
14336: $hash{'bar'}='foo';
14337: &Apache::lonnet::cstore(\%hash);
14338:
14339: #retrieving the hash
14340: my %history=&Apache::lonnet::restore();
14341:
14342: #print the hash
14343: foreach my $key (sort(keys(%history))) {
14344: print("\%history{$key} = $history{$key}");
14345: }
14346:
14347: Will print out:
14348:
14349: %history{1:foo} = bar
14350: %history{1:keys} = foo:timestamp
14351: %history{1:timestamp} = 990455579
14352: %history{2:bar} = foo
14353: %history{2:foo} = notbar
14354: %history{2:keys} = foo:bar:timestamp
14355: %history{2:timestamp} = 990455580
14356: %history{bar} = foo
14357: %history{foo} = notbar
14358: %history{timestamp} = 990455580
14359: %history{version} = 2
14360:
14361: Note that the special hash entries C<keys>, C<version> and
14362: C<timestamp> were added to the hash. C<version> will be equal to the
14363: total number of versions of the data that have been stored. The
14364: C<timestamp> attribute will be the UNIX time the hash was
14365: stored. C<keys> is available in every historical section to list which
14366: keys were added or changed at a specific historical revision of a
14367: hash.
14368:
14369: B<Warning>: do not store the hash that restore returns directly. This
14370: will cause a mess since it will restore the historical keys as if the
14371: were new keys. I.E. 1:foo will become 1:1:foo etc.
14372:
14373: Calling convention:
14374:
14375: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14376: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14377:
14378: For more detailed information, see lonnet specific documentation.
14379:
14380: =head1 RETURN MESSAGES
14381:
14382: =over 4
14383:
14384: =item * B<con_lost>: unable to contact remote host
14385:
14386: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14387: when the connection is brought back up
14388:
14389: =item * B<con_failed>: unable to contact remote host and unable to save message
14390: for later delivery
14391:
14392: =item * B<error:>: an error a occurred, a description of the error follows the :
14393:
14394: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14395: that was requested
14396:
14397: =back
14398:
14399: =head1 PUBLIC SUBROUTINES
14400:
14401: =head2 Session Environment Functions
14402:
14403: =over 4
14404:
14405: =item *
14406: X<appenv()>
14407: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14408: the user envirnoment file, and will be restored for each access this
14409: user makes during this session, also modifies the %env for the current
14410: process. Optional rolesarrayref - if defined contains a reference to an array
14411: of roles which are exempt from the restriction on modifying user.role entries
14412: in the user's environment.db and in %env.
14413:
14414: =item *
14415: X<delenv()>
14416: B<delenv($delthis,$regexp)>: removes all items from the session
14417: environment file that begin with $delthis. If the
14418: optional second arg - $regexp - is true, $delthis is treated as a
14419: regular expression, otherwise \Q$delthis\E is used.
14420: The values are also deleted from the current processes %env.
14421:
14422: =item * get_env_multiple($name)
14423:
14424: gets $name from the %env hash, it seemlessly handles the cases where multiple
14425: values may be defined and end up as an array ref.
14426:
14427: returns an array of values
14428:
14429: =back
14430:
14431: =head2 User Information
14432:
14433: =over 4
14434:
14435: =item *
14436: X<queryauthenticate()>
14437: B<queryauthenticate($uname,$udom)>: try to determine user's current
14438: authentication scheme
14439:
14440: =item *
14441: X<authenticate()>
14442: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14443: authenticate user from domain's lib servers (first use the current
14444: one). C<$upass> should be the users password.
14445: $checkdefauth is optional (value is 1 if a check should be made to
14446: authenticate user using default authentication method, and allow
14447: account creation if username does not have account in the domain).
14448: $clientcancheckhost is optional (value is 1 if checking whether the
14449: server can host will occur on the client side in lonauth.pm).
14450:
14451: =item *
14452: X<homeserver()>
14453: B<homeserver($uname,$udom)>: find the server which has
14454: the user's directory and files (there must be only one), this caches
14455: the answer, and also caches if there is a borken connection.
14456:
14457: =item *
14458: X<idget()>
14459: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14460: (IDs are a unique resource in a domain, there must be only 1 ID per
14461: username, and only 1 username per ID in a specific domain) (returns
14462: hash: id=>name,id=>name)
14463:
14464: =item *
14465: X<idrget()>
14466: B<idrget($udom,@unames)>: find the IDs behind a list of
14467: usernames (returns hash: name=>id,name=>id)
14468:
14469: =item *
14470: X<idput()>
14471: B<idput($udom,%ids)>: store away a list of names and associated IDs
14472:
14473: =item *
14474: X<rolesinit()>
14475: B<rolesinit($udom,$username)>: get user privileges.
14476: returns user role, first access and timer interval hashes
14477:
14478: =item *
14479: X<privileged()>
14480: B<privileged($username,$domain)>: returns a true if user has a
14481: privileged and active role (i.e. su or dc), false otherwise.
14482:
14483: =item *
14484: X<getsection()>
14485: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14486: course $cname, return section name/number or '' for "not in course"
14487: and '-1' for "no section"
14488:
14489: =item *
14490: X<userenvironment()>
14491: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14492: passed in @what from the requested user's environment, returns a hash
14493:
14494: =item *
14495: X<userlog_query()>
14496: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14497: activity.log file. %filters defines filters applied when parsing the
14498: log file. These can be start or end timestamps, or the type of action
14499: - log to look for Login or Logout events, check for Checkin or
14500: Checkout, role for role selection. The response is in the form
14501: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14502: escaped strings of the action recorded in the activity.log file.
14503:
14504: =back
14505:
14506: =head2 User Roles
14507:
14508: =over 4
14509:
14510: =item *
14511:
14512: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14513: returns codes for allowed actions.
14514:
14515: The first argument is required, all others are optional.
14516:
14517: $priv is the privilege being checked.
14518: $uri contains additional information about what is being checked for access (e.g.,
14519: URL, course ID etc.).
14520: $symb is the unique resource instance identifier in a course; if needed,
14521: but not provided, it will be retrieved via a call to &symbread().
14522: $role is the role for which a priv is being checked (only used if priv is evb).
14523: $clientip is the user's IP address (only used when checking for access to portfolio
14524: files).
14525: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14526: prevents recursive calls to &allowed.
14527:
14528: F: full access
14529: U,I,K: authentication modes (cxx only)
14530: '': forbidden
14531: 1: user needs to choose course
14532: 2: browse allowed
14533: A: passphrase authentication needed
14534: B: access temporarily blocked because of a blocking event in a course.
14535:
14536: =item *
14537:
14538: constructaccess($url,$setpriv) : check for access to construction space URL
14539:
14540: See if the owner domain and name in the URL match those in the
14541: expected environment. If so, return three element list
14542: ($ownername,$ownerdomain,$ownerhome).
14543:
14544: Otherwise return the null string.
14545:
14546: If second argument 'setpriv' is true, it assigns the privileges,
14547: and returns the same three element list, unless the owner has
14548: blocked "ad hoc" Domain Coordinator access to the Author Space,
14549: in which case the null string is returned.
14550:
14551: =item *
14552:
14553: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14554: define a custom role rolename set privileges in format of lonTabs/roles.tab
14555: for system, domain, and course level. $uname and $udom are optional (current
14556: user's username and domain will be used when either of $uname or $udom are absent.
14557:
14558: =item *
14559:
14560: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14561: (rolesplain.tab); plain text explanation of a user role term.
14562: $type is Course (default) or Community.
14563: If $forcedefault evaluates to true, text returned will be default
14564: text for $type. Otherwise, if this is a course, the text returned
14565: will be a custom name for the role (if defined in the course's
14566: environment). If no custom name is defined the default is returned.
14567:
14568: =item *
14569:
14570: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14571: All arguments are optional. Returns a hash of a roles, either for
14572: co-author/assistant author roles for a user's Construction Space
14573: (default), or if $context is 'userroles', roles for the user himself,
14574: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14575: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14576: For each key, value is set to colon-separated start and end times for
14577: the role. If no username and domain are specified, will default to
14578: current user/domain. Types, roles, and roledoms are references to arrays
14579: of role statuses (active, future or previous), roles
14580: (e.g., cc,in, st etc.) and domains of the roles which can be used
14581: to restrict the list of roles reported. If no array ref is
14582: provided for types, will default to return only active roles.
14583:
14584: =item *
14585:
14586: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14587: user: $uname:$udom has a role in the course: $cdom_$cnum.
14588:
14589: Additional optional arguments are: $type (if role checking is to be restricted
14590: to certain user status types -- previous (expired roles), active (currently
14591: available roles) or future (roles available in the future), and
14592: $hideprivileged -- if true will not report course roles for users who
14593: have active Domain Coordinator role in course's domain or in additional
14594: domains (specified in 'Domains to check for privileged users' in course
14595: environment -- set via: Course Settings -> Classlists and staff listing).
14596:
14597: =item *
14598:
14599: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14600: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14601: $possdomains and $possroles are optional array refs -- to domains to check and
14602: roles to check. If $possdomains is not specified, a dump will be done of the
14603: users' roles.db to check for a dc or su role in any domain. This can be
14604: time consuming if &privileged is called repeatedly (e.g., when displaying a
14605: classlist), so in such cases, supplying a $possdomains array is preferred, as
14606: this then allows &privileged_by_domain() to be used, which caches the identity
14607: of privileged users, eliminating the need for repeated calls to &dump().
14608:
14609: =item *
14610:
14611: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14612: where the outer hash keys are domains specified in the $possdomains array ref,
14613: next inner hash keys are privileged roles specified in the $roles array ref,
14614: and the innermost hash contains key = value pairs for username:domain = end:start
14615: for active or future "privileged" users with that role in that domain. To avoid
14616: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14617: innerhash are cached using priv_$role and $dom as the identifiers.
14618:
14619: =back
14620:
14621: =head2 User Modification
14622:
14623: =over 4
14624:
14625: =item *
14626:
14627: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14628: user for the level given by URL. Optional start and end dates (leave empty
14629: string or zero for "no date")
14630:
14631: =item *
14632:
14633: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14634: change a users, password, possible return values are: ok,
14635: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14636: refused
14637:
14638: =item *
14639:
14640: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14641:
14642: =item *
14643:
14644: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14645: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14646:
14647: will update user information (firstname,middlename,lastname,generation,
14648: permanentemail), and if forceid is true, student/employee ID also.
14649: A user's institutional affiliation(s) can also be updated.
14650: User information fields will not be overwritten with empty entries
14651: unless the field is included in the $candelete array reference.
14652: This array is included when a single user is modified via "Manage Users",
14653: or when Autoupdate.pl is run by cron in a domain.
14654:
14655: =item *
14656:
14657: modifystudent
14658:
14659: modify a student's enrollment and identification information.
14660: The course id is resolved based on the current user's environment.
14661: This means the invoking user must be a course coordinator or otherwise
14662: associated with a course.
14663:
14664: This call is essentially a wrapper for lonnet::modifyuser and
14665: lonnet::modify_student_enrollment
14666:
14667: Inputs:
14668:
14669: =over 4
14670:
14671: =item B<$udom> Student's loncapa domain
14672:
14673: =item B<$uname> Student's loncapa login name
14674:
14675: =item B<$uid> Student/Employee ID
14676:
14677: =item B<$umode> Student's authentication mode
14678:
14679: =item B<$upass> Student's password
14680:
14681: =item B<$first> Student's first name
14682:
14683: =item B<$middle> Student's middle name
14684:
14685: =item B<$last> Student's last name
14686:
14687: =item B<$gene> Student's generation
14688:
14689: =item B<$usec> Student's section in course
14690:
14691: =item B<$end> Unix time of the roles expiration
14692:
14693: =item B<$start> Unix time of the roles start date
14694:
14695: =item B<$forceid> If defined, allow $uid to be changed
14696:
14697: =item B<$desiredhome> server to use as home server for student
14698:
14699: =item B<$email> Student's permanent e-mail address
14700:
14701: =item B<$type> Type of enrollment (auto or manual)
14702:
14703: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14704:
14705: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14706:
14707: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14708:
14709: =item B<$context> role change context (shown in User Management Logs display in a course)
14710:
14711: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14712:
14713: =item B<$credits> Number of credits student will earn from this class - only needs to be supplied if value needs to be different from default credits for class.
14714:
14715: =back
14716:
14717: =item *
14718:
14719: modify_student_enrollment
14720:
14721: Change a student's enrollment status in a class. The environment variable
14722: 'role.request.course' must be defined for this function to proceed.
14723:
14724: Inputs:
14725:
14726: =over 4
14727:
14728: =item $udom, student's domain
14729:
14730: =item $uname, student's name
14731:
14732: =item $uid, student's user id
14733:
14734: =item $first, student's first name
14735:
14736: =item $middle
14737:
14738: =item $last
14739:
14740: =item $gene
14741:
14742: =item $usec
14743:
14744: =item $end
14745:
14746: =item $start
14747:
14748: =item $type
14749:
14750: =item $locktype
14751:
14752: =item $cid
14753:
14754: =item $selfenroll
14755:
14756: =item $context
14757:
14758: =item $credits, number of credits student will earn from this class
14759:
14760: =item $instsec, institutional course section code for student
14761:
14762: =back
14763:
14764:
14765: =item *
14766:
14767: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14768: custom role; give a custom role to a user for the level given by URL. Specify
14769: name and domain of role author, and role name
14770:
14771: =item *
14772:
14773: revokerole($udom,$uname,$url,$role) : revoke a role for url
14774:
14775: =item *
14776:
14777: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14778:
14779: =back
14780:
14781: =head2 Course Infomation
14782:
14783: =over 4
14784:
14785: =item *
14786:
14787: coursedescription($courseid,$options) : returns a hash of information about the
14788: specified course id, including all environment settings for the
14789: course, the description of the course will be in the hash under the
14790: key 'description'
14791:
14792: $options is an optional parameter that if supplied is a hash reference that controls
14793: what how this function works. It has the following key/values:
14794:
14795: =over 4
14796:
14797: =item freshen_cache
14798:
14799: If defined, and the environment cache for the course is valid, it is
14800: returned in the returned hash.
14801:
14802: =item one_time
14803:
14804: If defined, the last cache time is set to _now_
14805:
14806: =item user
14807:
14808: If defined, the supplied username is used instead of the current user.
14809:
14810:
14811: =back
14812:
14813: =item *
14814:
14815: resdata($name,$domain,$type,@which) : request for current parameter
14816: setting for a specific $type, where $type is either 'course' or 'user',
14817: @what should be a list of parameters to ask about. This routine caches
14818: answers for 10 minutes.
14819:
14820: =item *
14821:
14822: get_courseresdata($courseid, $domain) : dump the entire course resource
14823: data base, returning a hash that is keyed by the resource name and has
14824: values that are the resource value. I believe that the timestamps and
14825: versions are also returned.
14826:
14827: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14828: supplemental content area. This routine caches the number of files for
14829: 10 minutes.
14830:
14831: =back
14832:
14833: =head2 Course Modification
14834:
14835: =over 4
14836:
14837: =item *
14838:
14839: writecoursepref($courseid,%prefs) : write preferences (environment
14840: database) for a course
14841:
14842: =item *
14843:
14844: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14845:
14846: =item *
14847:
14848: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14849:
14850: =item *
14851:
14852: is_course($courseid), is_course($cdom, $cnum)
14853:
14854: Accepts either a combined $courseid (in the form of domain_courseid) or the
14855: two component version $cdom, $cnum. It checks if the specified course exists.
14856:
14857: Returns:
14858: undef if the course doesn't exist, otherwise
14859: in scalar context the combined courseid.
14860: in list context the two components of the course identifier, domain and
14861: courseid.
14862:
14863: =back
14864:
14865: =head2 Bubblesheet Configuration
14866:
14867: =over 4
14868:
14869: =item *
14870:
14871: get_scantron_config($which)
14872:
14873: $which - the name of the configuration to parse from the file.
14874:
14875: Parses and returns the bubblesheet configuration line selected as a
14876: hash of configuration file fields.
14877:
14878:
14879: Returns:
14880: If the named configuration is not in the file, an empty
14881: hash is returned.
14882:
14883: a hash with the fields
14884: name - internal name for the this configuration setup
14885: description - text to display to operator that describes this config
14886: CODElocation - if 0 or the string 'none'
14887: - no CODE exists for this config
14888: if -1 || the string 'letter'
14889: - a CODE exists for this config and is
14890: a string of letters
14891: Unsupported value (but planned for future support)
14892: if a positive integer
14893: - The CODE exists as the first n items from
14894: the question section of the form
14895: if the string 'number'
14896: - The CODE exists for this config and is
14897: a string of numbers
14898: CODEstart - (only matter if a CODE exists) column in the line where
14899: the CODE starts
14900: CODElength - length of the CODE
14901: IDstart - column where the student/employee ID starts
14902: IDlength - length of the student/employee ID info
14903: Qstart - column where the information from the bubbled
14904: 'questions' start
14905: Qlength - number of columns comprising a single bubble line from
14906: the sheet. (usually either 1 or 10)
14907: Qon - either a single character representing the character used
14908: to signal a bubble was chosen in the positional setup, or
14909: the string 'letter' if the letter of the chosen bubble is
14910: in the final, or 'number' if a number representing the
14911: chosen bubble is in the file (1->A 0->J)
14912: Qoff - the character used to represent that a bubble was
14913: left blank
14914: PaperID - if the scanning process generates a unique number for each
14915: sheet scanned the column that this ID number starts in
14916: PaperIDlength - number of columns that comprise the unique ID number
14917: for the sheet of paper
14918: FirstName - column that the first name starts in
14919: FirstNameLength - number of columns that the first name spans
14920: LastName - column that the last name starts in
14921: LastNameLength - number of columns that the last name spans
14922: BubblesPerRow - number of bubbles available in each row used to
14923: bubble an answer. (If not specified, 10 assumed).
14924:
14925:
14926: =item *
14927:
14928: get_scantronformat_file($cdom)
14929:
14930: $cdom - the course's domain (optional); if not supplied, uses
14931: domain for current $env{'request.course.id'}.
14932:
14933: Returns an array containing lines from the scantron format file for
14934: the domain of the course.
14935:
14936: If a url for a custom.tab file is listed in domain's configuration.db,
14937: lines are from this file.
14938:
14939: Otherwise, if a default.tab has been published in RES space by the
14940: domainconfig user, lines are from this file.
14941:
14942: Otherwise, fall back to getting lines from the legacy file on the
14943: local server: /home/httpd/lonTabs/default_scantronformat.tab
14944:
14945: =back
14946:
14947: =head2 Resource Subroutines
14948:
14949: =over 4
14950:
14951: =item *
14952:
14953: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14954:
14955: =item *
14956:
14957: repcopy($filename) : subscribes to the requested file, and attempts to
14958: replicate from the owning library server, Might return
14959: 'unavailable', 'not_found', 'forbidden', 'ok', or
14960: 'bad_request', also attempts to grab the metadata for the
14961: resource. Expects the local filesystem pathname
14962: (/home/httpd/html/res/....)
14963:
14964: =back
14965:
14966: =head2 Resource Information
14967:
14968: =over 4
14969:
14970: =item *
14971:
14972: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14973: and returns the value of a variety of different possible values,
14974: $varname should be a request string, and the other parameters can be
14975: used to specify who and what one is asking about. Ordinarily, $cid
14976: does not need to be specified, as it is retrived from
14977: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14978: within lonuserstate::loadmap() when initializing a course, before
14979: $env{'request.course.id'} has been set, so it needs to be provided
14980: in that one case.
14981:
14982: Possible values for $varname are environment.lastname (or other item
14983: from the envirnment hash), user.name (or someother aspect about the
14984: user), resource.0.maxtries (or some other part and parameter of a
14985: resource)
14986:
14987: =item *
14988:
14989: directcondval($number) : get current value of a condition; reads from a state
14990: string
14991:
14992: =item *
14993:
14994: condval($condidx) : value of condition index based on state
14995:
14996: =item *
14997:
14998: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14999: resource's metadata, $what should be either a specific key, or either
15000: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15001: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15002:
15003: this function automatically caches all requests
15004:
15005: =item *
15006:
15007: metadata_query($query,$custom,$customshow) : make a metadata query against the
15008: network of library servers; returns file handle of where SQL and regex results
15009: will be stored for query
15010:
15011: =item *
15012:
15013: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15014: return symbolic list entry (all arguments optional).
15015:
15016: Args: filename is the filename (including path) for the file for which a symb
15017: is required; donotrecurse, if true will prevent calls to allowed() being made
15018: to check access status if more than one resource was found in the bighash
15019: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15020: a randompick); ignorecachednull, if true will prevent a symb of '' being
15021: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15022: cause possible symbs to be checked to determine if they are subject to content
15023: blocking, if so they will not be included as possible symbs; possibles is a
15024: ref to a hash, which, as a side effect, will be populated with all possible
15025: symbs (content blocking not tested).
15026:
15027: returns the data handle
15028:
15029: =item *
15030:
15031: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15032: and is a possible symb for the URL in $thisfn, and if is an encrypted
15033: resource that the user accessed using /enc/ returns a 1 on success, 0
15034: on failure, user must be in a course, as it assumes the existence of
15035: the course initial hash, and uses $env('request.course.id'}. The third
15036: arg is an optional reference to a scalar. If this arg is passed in the
15037: call to symbverify, it will be set to 1 if the symb has been set to be
15038: encrypted; otherwise it will be null.
15039:
15040: =item *
15041:
15042: symbclean($symb) : removes versions numbers from a symb, returns the
15043: cleaned symb
15044:
15045: =item *
15046:
15047: is_on_map($uri) : checks if the $uri is somewhere on the current
15048: course map, user must be in a course for it to work.
15049:
15050: =item *
15051:
15052: numval($salt) : return random seed value (addend for rndseed)
15053:
15054: =item *
15055:
15056: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15057: a random seed, all arguments are optional, if they aren't sent it uses the
15058: environment to derive them. Note: if symb isn't sent and it can't get one
15059: from &symbread it will use the current time as its return value
15060:
15061: =item *
15062:
15063: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15064: unfakeable, receipt
15065:
15066: =item *
15067:
15068: receipt() : API to ireceipt working off of env values; given out to users
15069:
15070: =item *
15071:
15072: countacc($url) : count the number of accesses to a given URL
15073:
15074: =item *
15075:
15076: 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
15077:
15078: =item *
15079:
15080: 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)
15081:
15082: =item *
15083:
15084: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15085:
15086: =item *
15087:
15088: devalidate($symb) : devalidate temporary spreadsheet calculations,
15089: forcing spreadsheet to reevaluate the resource scores next time.
15090:
15091: =item *
15092:
15093: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15094: when viewing in course context.
15095:
15096: input: six args -- filename (decluttered), course number, course domain,
15097: url, symb (if registered) and group (if this is a
15098: group item -- e.g., bulletin board, group page etc.).
15099:
15100: output: array of five scalars --
15101: $cfile -- url for file editing if editable on current server
15102: $home -- homeserver of resource (i.e., for author if published,
15103: or course if uploaded.).
15104: $switchserver -- 1 if server switch will be needed.
15105: $forceedit -- 1 if icon/link should be to go to edit mode
15106: $forceview -- 1 if icon/link should be to go to view mode
15107:
15108: =item *
15109:
15110: is_course_upload($file,$cnum,$cdom)
15111:
15112: Used in course context to determine if current file was uploaded to
15113: the course (i.e., would be found in /userfiles/docs on the course's
15114: homeserver.
15115:
15116: input: 3 args -- filename (decluttered), course number and course domain.
15117: output: boolean -- 1 if file was uploaded.
15118:
15119: =back
15120:
15121: =head2 Storing/Retreiving Data
15122:
15123: =over 4
15124:
15125: =item *
15126:
15127: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15128: permanently for this url; hashref needs to be given and should be a \%hashname;
15129: the remaining args aren't required and if they aren't passed or are '' they will
15130: be derived from the env (with the exception of $laststore, which is an
15131: optional arg used when a user's submission is stored in grading).
15132: $laststore is $version=$timestamp, where $version is the most recent version
15133: number retrieved for the corresponding $symb in the $namespace db file, and
15134: $timestamp is the timestamp for that transaction (UNIX time).
15135: $laststore is currently only passed when cstore() is called by
15136: structuretags::finalize_storage().
15137:
15138: =item *
15139:
15140: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15141: but uses critical subroutine
15142:
15143: =item *
15144:
15145: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15146: all args are optional
15147:
15148: =item *
15149:
15150: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15151: dumps the complete (or key matching regexp) namespace into a hash
15152: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15153: normally &store()ed into
15154:
15155: $range should be either an integer '100' (give me the first 100
15156: matching records)
15157: or be two integers sperated by a - with no spaces
15158: '30-50' (give me the 30th through the 50th matching
15159: records)
15160:
15161:
15162: =item *
15163:
15164: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15165: replaces a &store() version of data with a replacement set of data
15166: for a particular resource in a namespace passed in the $storehash hash
15167: reference. If $tolog is true, the transaction is logged in the courselog
15168: with an action=PUTSTORE.
15169:
15170: =item *
15171:
15172: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15173: works very similar to store/cstore, but all data is stored in a
15174: temporary location and can be reset using tmpreset, $storehash should
15175: be a hash reference, returns nothing on success
15176:
15177: =item *
15178:
15179: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15180: similar to restore, but all data is stored in a temporary location and
15181: can be reset using tmpreset. Returns a hash of values on success,
15182: error string otherwise.
15183:
15184: =item *
15185:
15186: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15187: deltes all keys for $symb form the temporary storage hash.
15188:
15189: =item *
15190:
15191: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15192: reference filled in from namesp ($udom and $uname are optional)
15193:
15194: =item *
15195:
15196: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15197: namesp ($udom and $uname are optional)
15198:
15199: =item *
15200:
15201: dump($namespace,$udom,$uname,$regexp,$range) :
15202: dumps the complete (or key matching regexp) namespace into a hash
15203: ($udom, $uname, $regexp, $range are optional)
15204:
15205: $range should be either an integer '100' (give me the first 100
15206: matching records)
15207: or be two integers sperated by a - with no spaces
15208: '30-50' (give me the 30th through the 50th matching
15209: records)
15210: =item *
15211:
15212: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15213: $store can be a scalar, an array reference, or if the amount to be
15214: incremented is > 1, a hash reference.
15215:
15216: ($udom and $uname are optional)
15217:
15218: =item *
15219:
15220: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15221: ($udom and $uname are optional)
15222:
15223: =item *
15224:
15225: cput($namespace,$storehash,$udom,$uname) : critical put
15226: ($udom and $uname are optional)
15227:
15228: =item *
15229:
15230: newput($namespace,$storehash,$udom,$uname) :
15231:
15232: Attempts to store the items in the $storehash, but only if they don't
15233: currently exist, if this succeeds you can be certain that you have
15234: successfully created a new key value pair in the $namespace db.
15235:
15236:
15237: Args:
15238: $namespace: name of database to store values to
15239: $storehash: hashref to store to the db
15240: $udom: (optional) domain of user containing the db
15241: $uname: (optional) name of user caontaining the db
15242:
15243: Returns:
15244: 'ok' -> succeeded in storing all keys of $storehash
15245: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15246: least <key> already existed in the db (other
15247: requested keys may also already exist)
15248: 'error: <msg>' -> unable to tie the DB or other error occurred
15249: 'con_lost' -> unable to contact request server
15250: 'refused' -> action was not allowed by remote machine
15251:
15252:
15253: =item *
15254:
15255: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15256: reference filled in from namesp (encrypts the return communication)
15257: ($udom and $uname are optional)
15258:
15259: =item *
15260:
15261: log($udom,$name,$home,$message) : write to permanent log for user; use
15262: critical subroutine
15263:
15264: =item *
15265:
15266: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15267: array reference filled in from namespace found in domain level on either
15268: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15269:
15270: =item *
15271:
15272: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15273: domain level either on specified domain server ($uhome) or primary domain
15274: server ($udom and $uhome are optional)
15275:
15276: =item *
15277:
15278: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15279: for: authentication, language, quotas, timezone, date locale, and portal URL in
15280: the target domain.
15281:
15282: May also include additional key => value pairs for the following groups:
15283:
15284: =over
15285:
15286: =item
15287: disk quotas (MB allocated by default to portfolios and authoring spaces).
15288:
15289: =over
15290:
15291: =item defaultquota, authorquota
15292:
15293: =back
15294:
15295: =item
15296: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15297: portfolio for users).
15298:
15299: =over
15300:
15301: =item
15302: aboutme, blog, webdav, portfolio
15303:
15304: =back
15305:
15306: =item
15307: requestcourses: ability to request courses, and how requests are processed.
15308:
15309: =over
15310:
15311: =item
15312: official, unofficial, community, textbook
15313:
15314: =back
15315:
15316: =item
15317: inststatus: types of institutional affiliation, and order in which they are displayed.
15318:
15319: =over
15320:
15321: =item
15322: inststatustypes, inststatusorder, inststatusguest
15323:
15324: =back
15325:
15326: =item
15327: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15328: for course's uploaded content.
15329:
15330: =over
15331:
15332: =item
15333: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15334: communityquota, textbookquota
15335:
15336: =back
15337:
15338: =item
15339: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15340: on your servers.
15341:
15342: =over
15343:
15344: =item
15345: remotesessions, hostedsessions
15346:
15347: =back
15348:
15349: =back
15350:
15351: In cases where a domain coordinator has never used the "Set Domain Configuration"
15352: utility to create a configuration.db file on a domain's primary library server
15353: only the following domain defaults: auth_def, auth_arg_def, lang_def
15354: -- corresponding values are authentication type (internal, krb4, krb5,
15355: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15356: will be available. Values are retrieved from cache (if current), unless the
15357: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15358: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15359:
15360: Typical usage:
15361:
15362: %domdefaults = &get_domain_defaults($target_domain);
15363:
15364: =back
15365:
15366: =head2 Network Status Functions
15367:
15368: =over 4
15369:
15370: =item *
15371:
15372: dirlist() : return directory list based on URI (first arg).
15373:
15374: Inputs: 1 required, 5 optional.
15375:
15376: =over
15377:
15378: =item
15379: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15380:
15381: =item
15382: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15383:
15384: =item
15385: $username - username of user/course to be listed. Extracted from $uri if absent.
15386:
15387: =item
15388: $getpropath - boolean: 1 if prepend path using &propath().
15389:
15390: =item
15391: $getuserdir - boolean: 1 if prepend path for "userfiles".
15392:
15393: =item
15394: $alternateRoot - path to prepend in place of path from $uri.
15395:
15396: =back
15397:
15398: Returns: Array of up to two items.
15399:
15400: =over
15401:
15402: a reference to an array of files/subdirectories
15403:
15404: =over
15405:
15406: Each element in the array of files/subdirectories is a & separated list of
15407: item name and the result of running stat on the item. If dirlist was requested
15408: for a file instead of a directory, the item name will be ''. For a directory
15409: listing, if the item is a metadata file, the element will end &N&M
15410: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15411: default copyright set (1).
15412:
15413: =back
15414:
15415: a scalar containing error condition (if encountered).
15416:
15417: =over
15418:
15419: =item
15420: no_host (no homeserver identified for $username:$domain).
15421:
15422: =item
15423: no_such_host (server contacted for listing not identified as valid host).
15424:
15425: =item
15426: con_lost (connection to remote server failed).
15427:
15428: =item
15429: refused (invalid $username:$domain received on lond side).
15430:
15431: =item
15432: no_such_dir (directory at specified path on lond side does not exist).
15433:
15434: =item
15435: empty (directory at specified path on lond side is empty).
15436:
15437: =over
15438:
15439: This is currently not encountered because the &ls3, &ls2,
15440: &ls (_handler) routines on the lond side do not filter out
15441: . and .. from a directory listing.
15442:
15443: =back
15444:
15445: =back
15446:
15447: =back
15448:
15449: =item *
15450:
15451: spareserver() : find server with least workload from spare.tab
15452:
15453:
15454: =item *
15455:
15456: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15457: if there is no corresponding loncapa host.
15458:
15459: =back
15460:
15461:
15462: =head2 Apache Request
15463:
15464: =over 4
15465:
15466: =item *
15467:
15468: ssi($url,%hash) : server side include, does a complete request cycle on url to
15469: localhost, posts hash
15470:
15471: =back
15472:
15473: =head2 Data to String to Data
15474:
15475: =over 4
15476:
15477: =item *
15478:
15479: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15480: and '&' separators, supports elements that are arrayrefs and hashrefs
15481:
15482: =item *
15483:
15484: hashref2str($hashref) : convert a hashref into a string complete with
15485: escaping and '=' and '&' separators, supports elements that are
15486: arrayrefs and hashrefs
15487:
15488: =item *
15489:
15490: arrayref2str($arrayref) : convert an arrayref into a string complete
15491: with escaping and '&' separators, supports elements that are arrayrefs
15492: and hashrefs
15493:
15494: =item *
15495:
15496: str2hash($string) : convert string to hash using unescaping and
15497: splitting on '=' and '&', supports elements that are arrayrefs and
15498: hashrefs
15499:
15500: =item *
15501:
15502: str2array($string) : convert string to hash using unescaping and
15503: splitting on '&', supports elements that are arrayrefs and hashrefs
15504:
15505: =back
15506:
15507: =head2 Logging Routines
15508:
15509:
15510: These routines allow one to make log messages in the lonnet.log and
15511: lonnet.perm logfiles.
15512:
15513: =over 4
15514:
15515: =item *
15516:
15517: logtouch() : make sure the logfile, lonnet.log, exists
15518:
15519: =item *
15520:
15521: logthis() : append message to the normal lonnet.log file, it gets
15522: preiodically rolled over and deleted.
15523:
15524: =item *
15525:
15526: logperm() : append a permanent message to lonnet.perm.log, this log
15527: file never gets deleted by any automated portion of the system, only
15528: messages of critical importance should go in here.
15529:
15530:
15531: =back
15532:
15533: =head2 General File Helper Routines
15534:
15535: =over 4
15536:
15537: =item *
15538:
15539: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15540: (a) files in /uploaded
15541: (i) If a local copy of the file exists -
15542: compares modification date of local copy with last-modified date for
15543: definitive version stored on home server for course. If local copy is
15544: stale, requests a new version from the home server and stores it.
15545: If the original has been removed from the home server, then local copy
15546: is unlinked.
15547: (ii) If local copy does not exist -
15548: requests the file from the home server and stores it.
15549:
15550: If $caller is 'uploadrep':
15551: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15552: for request for files originally uploaded via DOCS.
15553: - returns 'ok' if fresh local copy now available, -1 otherwise.
15554:
15555: Otherwise:
15556: This indicates a call from the content generation phase of the request.
15557: - returns the entire contents of the file or -1.
15558:
15559: (b) files in /res
15560: - returns the entire contents of a file or -1;
15561: it properly subscribes to and replicates the file if neccessary.
15562:
15563:
15564: =item *
15565:
15566: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15567: reference
15568:
15569: returns either a stat() list of data about the file or an empty list
15570: if the file doesn't exist or couldn't find out about it (connection
15571: problems or user unknown)
15572:
15573: =item *
15574:
15575: filelocation($dir,$file) : returns file system location of a file
15576: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15577: directory that relative $file lookups are to looked in ($dir of /a/dir
15578: and a file of ../bob will become /a/bob)
15579:
15580: =item *
15581:
15582: hreflocation($dir,$file) : returns file system location or a URL; same as
15583: filelocation except for hrefs
15584:
15585: =item *
15586:
15587: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15588: also removes beginning /home/httpd/html unless /priv/ follows it.
15589:
15590: =back
15591:
15592: =head2 Usererfile file routines (/uploaded*)
15593:
15594: =over 4
15595:
15596: =item *
15597:
15598: userfileupload(): main rotine for putting a file in a user or course's
15599: filespace, arguments are,
15600:
15601: formname - required - this is the name of the element in $env where the
15602: filename, and the contents of the file to create/modifed exist
15603: the filename is in $env{'form.'.$formname.'.filename'} and the
15604: contents of the file is located in $env{'form.'.$formname}
15605: context - if coursedoc, store the file in the course of the active role
15606: of the current user;
15607: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15608: if 'canceloverwrite': delete file in tmp/overwrites directory
15609: subdir - required - subdirectory to put the file in under ../userfiles/
15610: if undefined, it will be placed in "unknown"
15611:
15612: (This routine calls clean_filename() to remove any dangerous
15613: characters from the filename, and then calls finuserfileupload() to
15614: complete the transaction)
15615:
15616: returns either the url of the uploaded file (/uploaded/....) if successful
15617: and /adm/notfound.html if unsuccessful
15618:
15619: =item *
15620:
15621: clean_filename(): routine for cleaing a filename up for storage in
15622: userfile space, argument is:
15623:
15624: filename - proposed filename
15625:
15626: returns: the new clean filename
15627:
15628: =item *
15629:
15630: finishuserfileupload(): routine that creates and sends the file to
15631: userspace, probably shouldn't be called directly
15632:
15633: docuname: username or courseid of destination for the file
15634: docudom: domain of user/course of destination for the file
15635: formname: same as for userfileupload()
15636: fname: filename (including subdirectories) for the file
15637: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15638: if hashref, and context is scantron, will convert csv format to standard format
15639: allfiles: reference to hash used to store objects found by parser
15640: codebase: reference to hash used for codebases of java objects found by parser
15641: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15642: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15643: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15644: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15645: context: if 'overwrite', will move the uploaded file from its temporary location to
15646: userfiles to facilitate overwriting a previously uploaded file with same name.
15647: mimetype: reference to scalar to accommodate mime type determined
15648: from File::MMagic if $parser = parse.
15649:
15650: returns either the url of the uploaded file (/uploaded/....) if successful
15651: and /adm/notfound.html if unsuccessful (or an error message if context
15652: was 'overwrite').
15653:
15654:
15655: =item *
15656:
15657: renameuserfile(): renames an existing userfile to a new name
15658:
15659: Args:
15660: docuname: username or courseid of destination for the file
15661: docudom: domain of user/course of destination for the file
15662: old: current file name (including any subdirs under userfiles)
15663: new: desired file name (including any subdirs under userfiles)
15664:
15665: =item *
15666:
15667: mkdiruserfile(): creates a directory is a userfiles dir
15668:
15669: Args:
15670: docuname: username or courseid of destination for the file
15671: docudom: domain of user/course of destination for the file
15672: dir: dir to create (including any subdirs under userfiles)
15673:
15674: =item *
15675:
15676: removeuserfile(): removes a file that exists in userfiles
15677:
15678: Args:
15679: docuname: username or courseid of destination for the file
15680: docudom: domain of user/course of destination for the file
15681: fname: filname to delete (including any subdirs under userfiles)
15682:
15683: =item *
15684:
15685: removeuploadedurl(): convience function for removeuserfile()
15686:
15687: Args:
15688: url: a full /uploaded/... url to delete
15689:
15690: =item *
15691:
15692: get_portfile_permissions():
15693: Args:
15694: domain: domain of user or course contain the portfolio files
15695: user: name of user or num of course contain the portfolio files
15696: Returns:
15697: hashref of a dump of the proper file_permissions.db
15698:
15699:
15700: =item *
15701:
15702: get_access_controls():
15703:
15704: Args:
15705: current_permissions: the hash ref returned from get_portfile_permissions()
15706: group: (optional) the group you want the files associated with
15707: file: (optional) the file you want access info on
15708:
15709: Returns:
15710: a hash (keys are file names) of hashes containing
15711: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15712: values are XML containing access control settings (see below)
15713:
15714: Internal notes:
15715:
15716: access controls are stored in file_permissions.db as key=value pairs.
15717: key -> path to file/file_name\0uniqueID:scope_end_start
15718: where scope -> public,guest,course,group,domains or users.
15719: end -> UNIX time for end of access (0 -> no end date)
15720: start -> UNIX time for start of access
15721:
15722: value -> XML description of access control
15723: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15724: <start></start>
15725: <end></end>
15726:
15727: <password></password> for scope type = guest
15728:
15729: <domain></domain> for scope type = course or group
15730: <number></number>
15731: <roles id="">
15732: <role></role>
15733: <access></access>
15734: <section></section>
15735: <group></group>
15736: </roles>
15737:
15738: <dom></dom> for scope type = domains
15739:
15740: <users> for scope type = users
15741: <user>
15742: <uname></uname>
15743: <udom></udom>
15744: </user>
15745: </users>
15746: </scope>
15747:
15748: Access data is also aggregated for each file in an additional key=value pair:
15749: key -> path to file/file_name\0accesscontrol
15750: value -> reference to hash
15751: hash contains key = value pairs
15752: where key = uniqueID:scope_end_start
15753: value = UNIX time record was last updated
15754:
15755: Used to improve speed of look-ups of access controls for each file.
15756:
15757: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15758:
15759: =item *
15760:
15761: modify_access_controls():
15762:
15763: Modifies access controls for a portfolio file
15764: Args
15765: 1. file name
15766: 2. reference to hash of required changes,
15767: 3. domain
15768: 4. username
15769: where domain,username are the domain of the portfolio owner
15770: (either a user or a course)
15771:
15772: Returns:
15773: 1. result of additions or updates ('ok' or 'error', with error message).
15774: 2. result of deletions ('ok' or 'error', with error message).
15775: 3. reference to hash of any new or updated access controls.
15776: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15777: key = integer (inbound ID)
15778: value = uniqueID
15779:
15780: =item *
15781:
15782: get_timebased_id():
15783:
15784: Attempts to get a unique timestamp-based suffix for use with items added to a
15785: course via the Course Editor (e.g., folders, composite pages,
15786: group bulletin boards).
15787:
15788: Args: (first three required; six others optional)
15789:
15790: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15791: docssequence, or name of group
15792:
15793: 2. keyid (alphanumeric): name of temporary locking key in hash,
15794: e.g., num, boardids
15795:
15796: 3. namespace: name of gdbm file used to store suffixes already assigned;
15797: file will be named nohist_namespace.db
15798:
15799: 4. cdom: domain of course; default is current course domain from %env
15800:
15801: 5. cnum: course number; default is current course number from %env
15802:
15803: 6. idtype: set to concat if an additional digit is to be appended to the
15804: unix timestamp to form the suffix, if the plain timestamp is already
15805: in use. Default is to not do this, but simply increment the unix
15806: timestamp by 1 until a unique key is obtained.
15807:
15808: 7. who: holder of locking key; defaults to user:domain for user.
15809:
15810: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15811: retrying); default is 3.
15812:
15813: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15814:
15815: Returns:
15816:
15817: 1. suffix obtained (numeric)
15818:
15819: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15820:
15821: 3. error: contains (localized) error message if an error occurred.
15822:
15823:
15824: =back
15825:
15826: =head2 HTTP Helper Routines
15827:
15828: =over 4
15829:
15830: =item *
15831:
15832: escape() : unpack non-word characters into CGI-compatible hex codes
15833:
15834: =item *
15835:
15836: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15837:
15838: =back
15839:
15840: =head1 PRIVATE SUBROUTINES
15841:
15842: =head2 Underlying communication routines (Shouldn't call)
15843:
15844: =over 4
15845:
15846: =item *
15847:
15848: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15849:
15850: =item *
15851:
15852: reply() : uses subreply to send a message to remote machine, logs all failures
15853:
15854: =item *
15855:
15856: critical() : passes a critical message to another server; if cannot
15857: get through then place message in connection buffer directory and
15858: returns con_delayed, if incapable of saving message, returns
15859: con_failed
15860:
15861: =item *
15862:
15863: reconlonc() : tries to reconnect lonc client processes.
15864:
15865: =back
15866:
15867: =head2 Resource Access Logging
15868:
15869: =over 4
15870:
15871: =item *
15872:
15873: flushcourselogs() : flush (save) buffer logs and access logs
15874:
15875: =item *
15876:
15877: courselog($what) : save message for course in hash
15878:
15879: =item *
15880:
15881: courseacclog($what) : save message for course using &courselog(). Perform
15882: special processing for specific resource types (problems, exams, quizzes, etc).
15883:
15884: =item *
15885:
15886: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15887: as a PerlChildExitHandler
15888:
15889: =back
15890:
15891: =head2 Other
15892:
15893: =over 4
15894:
15895: =item *
15896:
15897: symblist($mapname,%newhash) : update symbolic storage links
15898:
15899: =back
15900:
15901: =cut
15902:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>