1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1172.2.140.2.1 2021/03/08 14:48:41 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: # Replace three or more adjacent underscores with one for consistency
3740: # with loncfile::filename_check() so complete url can be extracted by
3741: # lonnet::decode_symb()
3742: $fname=~s/_{3,}/_/g;
3743: return $fname;
3744: }
3745:
3746: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3747: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3748: # image with the same aspect ratio as the original, but with dimensions which do
3749: # not exceed $resizewidth and $resizeheight.
3750:
3751: sub resizeImage {
3752: my ($img_path,$resizewidth,$resizeheight) = @_;
3753: my $ima = Image::Magick->new;
3754: my $resized;
3755: if (-e $img_path) {
3756: $ima->Read($img_path);
3757: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3758: my $width = $ima->Get('width');
3759: my $height = $ima->Get('height');
3760: if ($width > $resizewidth) {
3761: my $factor = $width/$resizewidth;
3762: my $newheight = $height/$factor;
3763: $ima->Scale(width=>$resizewidth,height=>$newheight);
3764: $resized = 1;
3765: }
3766: }
3767: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3768: my $width = $ima->Get('width');
3769: my $height = $ima->Get('height');
3770: if ($height > $resizeheight) {
3771: my $factor = $height/$resizeheight;
3772: my $newwidth = $width/$factor;
3773: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3774: $resized = 1;
3775: }
3776: }
3777: if ($resized) {
3778: $ima->Write($img_path);
3779: }
3780: }
3781: return;
3782: }
3783:
3784: # --------------- Take an uploaded file and put it into the userfiles directory
3785: # input: $formname - the contents of the file are in $env{"form.$formname"}
3786: # the desired filename is in $env{"form.$formname.filename"}
3787: # $context - possible values: coursedoc, existingfile, overwrite,
3788: # canceloverwrite, scantron or ''.
3789: # if 'coursedoc': upload to the current course
3790: # if 'existingfile': write file to tmp/overwrites directory
3791: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3792: # $context is passed as argument to &finishuserfileupload
3793: # $subdir - directory in userfile to store the file into
3794: # $parser - instruction to parse file for objects ($parser = parse) or
3795: # if context is 'scantron', $parser is hashref of csv column mapping
3796: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3797: # Section => 4, CODE => 5, FirstQuestion => 9 }).
3798: # $allfiles - reference to hash for embedded objects
3799: # $codebase - reference to hash for codebase of java objects
3800: # $desuname - username for permanent storage of uploaded file
3801: # $dsetudom - domain for permanaent storage of uploaded file
3802: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3803: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3804: # $resizewidth - width (pixels) to which to resize uploaded image
3805: # $resizeheight - height (pixels) to which to resize uploaded image
3806: # $mimetype - reference to scalar to accommodate mime type determined
3807: # from File::MMagic.
3808: #
3809: # output: url of file in userspace, or error: <message>
3810: # or /adm/notfound.html if failure to upload occurse
3811:
3812: sub userfileupload {
3813: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3814: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3815: if (!defined($subdir)) { $subdir='unknown'; }
3816: my $fname=$env{'form.'.$formname.'.filename'};
3817: $fname=&clean_filename($fname);
3818: # See if there is anything left
3819: unless ($fname) { return 'error: no uploaded file'; }
3820: # If filename now begins with a . prepend unix timestamp _ milliseconds
3821: if ($fname =~ /^\./) {
3822: my ($s,$usec) = &gettimeofday();
3823: while (length($usec) < 6) {
3824: $usec = '0'.$usec;
3825: }
3826: $fname = $s.'_'.substr($usec,0,3).$fname;
3827: }
3828: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3829: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3830: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3831: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3832: my $now = time;
3833: my $filepath;
3834: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3835: $filepath = 'tmp/helprequests/'.$now;
3836: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3837: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3838: '_'.$env{'user.domain'}.'/pending';
3839: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3840: my ($docuname,$docudom);
3841: if ($destudom =~ /^$match_domain$/) {
3842: $docudom = $destudom;
3843: } else {
3844: $docudom = $env{'user.domain'};
3845: }
3846: if ($destuname =~ /^$match_username$/) {
3847: $docuname = $destuname;
3848: } else {
3849: $docuname = $env{'user.name'};
3850: }
3851: if (exists($env{'form.group'})) {
3852: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3853: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3854: }
3855: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3856: if ($context eq 'canceloverwrite') {
3857: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3858: if (-e $tempfile) {
3859: my @info = stat($tempfile);
3860: if ($info[9] eq $env{'form.timestamp'}) {
3861: unlink($tempfile);
3862: }
3863: }
3864: return;
3865: }
3866: }
3867: # Create the directory if not present
3868: my @parts=split(/\//,$filepath);
3869: my $fullpath = $perlvar{'lonDaemons'};
3870: for (my $i=0;$i<@parts;$i++) {
3871: $fullpath .= '/'.$parts[$i];
3872: if ((-e $fullpath)!=1) {
3873: mkdir($fullpath,0777);
3874: }
3875: }
3876: open(my $fh,'>',$fullpath.'/'.$fname);
3877: print $fh $env{'form.'.$formname};
3878: close($fh);
3879: if ($context eq 'existingfile') {
3880: my @info = stat($fullpath.'/'.$fname);
3881: return ($fullpath.'/'.$fname,$info[9]);
3882: } else {
3883: return $fullpath.'/'.$fname;
3884: }
3885: }
3886: if ($subdir eq 'scantron') {
3887: $fname = 'scantron_orig_'.$fname;
3888: } else {
3889: $fname="$subdir/$fname";
3890: }
3891: if ($context eq 'coursedoc') {
3892: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3893: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3894: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3895: return &finishuserfileupload($docuname,$docudom,
3896: $formname,$fname,$parser,$allfiles,
3897: $codebase,$thumbwidth,$thumbheight,
3898: $resizewidth,$resizeheight,$context,$mimetype);
3899: } else {
3900: if ($env{'form.folder'}) {
3901: $fname=$env{'form.folder'}.'/'.$fname;
3902: }
3903: return &process_coursefile('uploaddoc',$docuname,$docudom,
3904: $fname,$formname,$parser,
3905: $allfiles,$codebase,$mimetype);
3906: }
3907: } elsif (defined($destuname)) {
3908: my $docuname=$destuname;
3909: my $docudom=$destudom;
3910: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3911: $parser,$allfiles,$codebase,
3912: $thumbwidth,$thumbheight,
3913: $resizewidth,$resizeheight,$context,$mimetype);
3914: } else {
3915: my $docuname=$env{'user.name'};
3916: my $docudom=$env{'user.domain'};
3917: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3918: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3919: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3920: }
3921: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3922: $parser,$allfiles,$codebase,
3923: $thumbwidth,$thumbheight,
3924: $resizewidth,$resizeheight,$context,$mimetype);
3925: }
3926: }
3927:
3928: sub finishuserfileupload {
3929: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3930: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3931: my $path=$docudom.'/'.$docuname.'/';
3932: my $filepath=$perlvar{'lonDocRoot'};
3933:
3934: my ($fnamepath,$file,$fetchthumb);
3935: $file=$fname;
3936: if ($fname=~m|/|) {
3937: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3938: $path.=$fnamepath.'/';
3939: }
3940: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3941: my $count;
3942: for ($count=4;$count<=$#parts;$count++) {
3943: $filepath.="/$parts[$count]";
3944: if ((-e $filepath)!=1) {
3945: mkdir($filepath,0777);
3946: }
3947: }
3948:
3949: # Save the file
3950: {
3951: if (!open(FH,'>',$filepath.'/'.$file)) {
3952: &logthis('Failed to create '.$filepath.'/'.$file);
3953: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3954: return '/adm/notfound.html';
3955: }
3956: if ($context eq 'overwrite') {
3957: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3958: my $target = $filepath.'/'.$file;
3959: if (-e $source) {
3960: my @info = stat($source);
3961: if ($info[9] eq $env{'form.timestamp'}) {
3962: unless (&File::Copy::move($source,$target)) {
3963: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3964: return "Moving from $source failed";
3965: }
3966: } else {
3967: return "Temporary file: $source had unexpected date/time for last modification";
3968: }
3969: } else {
3970: return "Temporary file: $source missing";
3971: }
3972: } elsif (!print FH ($env{'form.'.$formname})) {
3973: &logthis('Failed to write to '.$filepath.'/'.$file);
3974: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3975: return '/adm/notfound.html';
3976: }
3977: close(FH);
3978: if ($resizewidth && $resizeheight) {
3979: my $mm = new File::MMagic;
3980: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3981: if ($mime_type =~ m{^image/}) {
3982: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3983: }
3984: }
3985: }
3986: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3987: if (ref($mimetype)) {
3988: if ($$mimetype eq '') {
3989: my $mm = new File::MMagic;
3990: my $type = $mm->checktype_filename($filepath.'/'.$file);
3991: $$mimetype = $type;
3992: }
3993: }
3994: }
3995: if (($context ne 'scantron') && ($parser eq 'parse')) {
3996: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3997: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3998: $allfiles,$codebase);
3999: unless ($parse_result eq 'ok') {
4000: &logthis('Failed to parse '.$filepath.$file.
4001: ' for embedded media: '.$parse_result);
4002: }
4003: }
4004: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
4005: my $format = $env{'form.scantron_format'};
4006: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
4007: }
4008: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
4009: my $input = $filepath.'/'.$file;
4010: my $output = $filepath.'/'.'tn-'.$file;
4011: my $thumbsize = $thumbwidth.'x'.$thumbheight;
4012: my @args = ('convert','-sample',$thumbsize,$input,$output);
4013: system({$args[0]} @args);
4014: if (-e $filepath.'/'.'tn-'.$file) {
4015: $fetchthumb = 1;
4016: }
4017: }
4018:
4019: # Notify homeserver to grep it
4020: #
4021: my $docuhome=&homeserver($docuname,$docudom);
4022: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
4023: if ($fetchresult eq 'ok') {
4024: if ($fetchthumb) {
4025: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
4026: if ($thumbresult ne 'ok') {
4027: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
4028: $docuhome.': '.$thumbresult);
4029: }
4030: }
4031: #
4032: # Return the URL to it
4033: return '/uploaded/'.$path.$file;
4034: } else {
4035: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
4036: ': '.$fetchresult);
4037: return '/adm/notfound.html';
4038: }
4039: }
4040:
4041: sub extract_embedded_items {
4042: my ($fullpath,$allfiles,$codebase,$content) = @_;
4043: my @state = ();
4044: my (%lastids,%related,%shockwave,%flashvars);
4045: my %javafiles = (
4046: codebase => '',
4047: code => '',
4048: archive => ''
4049: );
4050: my %mediafiles = (
4051: src => '',
4052: movie => '',
4053: );
4054: my $p;
4055: if ($content) {
4056: $p = HTML::LCParser->new($content);
4057: } else {
4058: $p = HTML::LCParser->new($fullpath);
4059: }
4060: while (my $t=$p->get_token()) {
4061: if ($t->[0] eq 'S') {
4062: my ($tagname, $attr) = ($t->[1],$t->[2]);
4063: push(@state, $tagname);
4064: if (lc($tagname) eq 'allow') {
4065: &add_filetype($allfiles,$attr->{'src'},'src');
4066: }
4067: if (lc($tagname) eq 'img') {
4068: &add_filetype($allfiles,$attr->{'src'},'src');
4069: }
4070: if (lc($tagname) eq 'a') {
4071: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4072: &add_filetype($allfiles,$attr->{'href'},'href');
4073: }
4074: }
4075: if (lc($tagname) eq 'script') {
4076: my $src;
4077: if ($attr->{'archive'} =~ /\.jar$/i) {
4078: &add_filetype($allfiles,$attr->{'archive'},'archive');
4079: } else {
4080: if ($attr->{'src'} ne '') {
4081: $src = $attr->{'src'};
4082: &add_filetype($allfiles,$src,'src');
4083: }
4084: }
4085: my $text = $p->get_trimmed_text();
4086: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4087: my @swfargs = split(/,/,$1);
4088: foreach my $item (@swfargs) {
4089: $item =~ s/["']//g;
4090: $item =~ s/^\s+//;
4091: $item =~ s/\s+$//;
4092: }
4093: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4094: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4095: push(@{$related{$swfargs[0]}},$swfargs[2]);
4096: } else {
4097: $related{$swfargs[0]} = [$swfargs[2]];
4098: }
4099: }
4100: }
4101: }
4102: if (lc($tagname) eq 'link') {
4103: if (lc($attr->{'rel'}) eq 'stylesheet') {
4104: &add_filetype($allfiles,$attr->{'href'},'href');
4105: }
4106: }
4107: if (lc($tagname) eq 'object' ||
4108: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4109: foreach my $item (keys(%javafiles)) {
4110: $javafiles{$item} = '';
4111: }
4112: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4113: $lastids{lc($tagname)} = $attr->{'id'};
4114: }
4115: }
4116: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4117: my $name = lc($attr->{'name'});
4118: foreach my $item (keys(%javafiles)) {
4119: if ($name eq $item) {
4120: $javafiles{$item} = $attr->{'value'};
4121: last;
4122: }
4123: }
4124: my $pathfrom;
4125: foreach my $item (keys(%mediafiles)) {
4126: if ($name eq $item) {
4127: $pathfrom = $attr->{'value'};
4128: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4129: &add_filetype($allfiles,$pathfrom,$name);
4130: last;
4131: }
4132: }
4133: if ($name eq 'flashvars') {
4134: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4135: }
4136: if ($pathfrom ne '') {
4137: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4138: $pathfrom);
4139: }
4140: }
4141: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4142: foreach my $item (keys(%javafiles)) {
4143: if ($attr->{$item}) {
4144: $javafiles{$item} = $attr->{$item};
4145: last;
4146: }
4147: }
4148: foreach my $item (keys(%mediafiles)) {
4149: if ($attr->{$item}) {
4150: &add_filetype($allfiles,$attr->{$item},$item);
4151: last;
4152: }
4153: }
4154: if (lc($tagname) eq 'embed') {
4155: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4156: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4157: $attr->{'src'});
4158: }
4159: }
4160: }
4161: if (lc($tagname) eq 'iframe') {
4162: my $src = $attr->{'src'} ;
4163: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4164: &add_filetype($allfiles,$src,'src');
4165: } elsif ($src =~ m{^/}) {
4166: if ($env{'request.course.id'}) {
4167: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4168: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4169: my $url = &hreflocation('',$fullpath);
4170: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4171: my $relpath = $1;
4172: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4173: &add_filetype($allfiles,$1,'src');
4174: }
4175: }
4176: }
4177: }
4178: }
4179: if ($t->[4] =~ m{/>$}) {
4180: pop(@state);
4181: }
4182: } elsif ($t->[0] eq 'E') {
4183: my ($tagname) = ($t->[1]);
4184: if ($javafiles{'codebase'} ne '') {
4185: $javafiles{'codebase'} .= '/';
4186: }
4187: if (lc($tagname) eq 'applet' ||
4188: lc($tagname) eq 'object' ||
4189: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4190: ) {
4191: foreach my $item (keys(%javafiles)) {
4192: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4193: my $file=$javafiles{'codebase'}.$javafiles{$item};
4194: &add_filetype($allfiles,$file,$item);
4195: }
4196: }
4197: }
4198: pop @state;
4199: }
4200: }
4201: foreach my $id (sort(keys(%flashvars))) {
4202: if ($shockwave{$id} ne '') {
4203: my @pairs = split(/\&/,$flashvars{$id});
4204: foreach my $pair (@pairs) {
4205: my ($key,$value) = split(/\=/,$pair);
4206: if ($key eq 'thumb') {
4207: &add_filetype($allfiles,$value,$key);
4208: } elsif ($key eq 'content') {
4209: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4210: my ($ext) = ($value =~ /\.([^.]+)$/);
4211: if ($ext ne '') {
4212: &add_filetype($allfiles,$path.$value,$ext);
4213: }
4214: }
4215: }
4216: }
4217: }
4218: return 'ok';
4219: }
4220:
4221: sub add_filetype {
4222: my ($allfiles,$file,$type)=@_;
4223: if (exists($allfiles->{$file})) {
4224: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4225: push(@{$allfiles->{$file}}, &escape($type));
4226: }
4227: } else {
4228: @{$allfiles->{$file}} = (&escape($type));
4229: }
4230: }
4231:
4232: sub embedded_dependency {
4233: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4234: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4235: if (($identifier ne '') &&
4236: (ref($related->{$identifier}) eq 'ARRAY') &&
4237: ($pathfrom ne '')) {
4238: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4239: foreach my $dep (@{$related->{$identifier}}) {
4240: &add_filetype($allfiles,$path.$dep,'object');
4241: }
4242: }
4243: }
4244: return;
4245: }
4246:
4247: sub bubblesheet_converter {
4248: my ($cdom,$fullpath,$config,$format) = @_;
4249: if ((&domain($cdom) ne '') &&
4250: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4251: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4252: my (%csvcols,%csvoptions);
4253: if (ref($config->{'fields'}) eq 'HASH') {
4254: %csvcols = %{$config->{'fields'}};
4255: }
4256: if (ref($config->{'options'}) eq 'HASH') {
4257: %csvoptions = %{$config->{'options'}};
4258: }
4259: my %csvbynum = reverse(%csvcols);
4260: my %scantronconf = &get_scantron_config($format,$cdom);
4261: if (keys(%scantronconf)) {
4262: my %bynum = (
4263: $scantronconf{CODEstart} => 'CODEstart',
4264: $scantronconf{IDstart} => 'IDstart',
4265: $scantronconf{PaperID} => 'PaperID',
4266: $scantronconf{FirstName} => 'FirstName',
4267: $scantronconf{LastName} => 'LastName',
4268: $scantronconf{Qstart} => 'Qstart',
4269: );
4270: my @ordered;
4271: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4272: push(@ordered,$bynum{$item});
4273: }
4274: my %mapstart = (
4275: CODEstart => 'CODE',
4276: IDstart => 'ID',
4277: PaperID => 'PaperID',
4278: FirstName => 'FirstName',
4279: LastName => 'LastName',
4280: Qstart => 'FirstQuestion',
4281: );
4282: my %maplength = (
4283: CODEstart => 'CODElength',
4284: IDstart => 'IDlength',
4285: PaperID => 'PaperIDlength',
4286: FirstName => 'FirstNamelength',
4287: LastName => 'LastNamelength',
4288: );
4289: if (open(my $fh,'<',$fullpath)) {
4290: my $output;
4291: my %lettdig = &letter_to_digits();
4292: my %diglett = reverse(%lettdig);
4293: my $numletts = scalar(keys(%lettdig));
4294: my $num = 0;
4295: while (my $line=<$fh>) {
4296: $num ++;
4297: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4298: $line =~ s{[\r\n]+$}{};
4299: my %found;
4300: my @values = split(/,/,$line);
4301: my ($qstart,$record);
4302: for (my $i=0; $i<@values; $i++) {
4303: if ((($qstart ne '') && ($i > $qstart)) ||
4304: ($csvbynum{$i} eq 'FirstQuestion')) {
4305: if ($values[$i] eq '') {
4306: $values[$i] = $scantronconf{'Qoff'};
4307: } elsif ($scantronconf{'Qon'} eq 'number') {
4308: if ($values[$i] =~ /^[A-Ja-j]$/) {
4309: $values[$i] = $lettdig{uc($values[$i])};
4310: }
4311: } elsif ($scantronconf{'Qon'} eq 'letter') {
4312: if ($values[$i] =~ /^[0-9]$/) {
4313: $values[$i] = $diglett{$values[$i]};
4314: }
4315: } else {
4316: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4317: my $digit;
4318: if ($values[$i] =~ /^[A-Ja-j]$/) {
4319: $digit = $lettdig{uc($values[$i])}-1;
4320: if ($values[$i] eq 'J') {
4321: $digit += $numletts;
4322: }
4323: } elsif ($values[$i] =~ /^[0-9]$/) {
4324: $digit = $values[$i]-1;
4325: if ($values[$i] eq '0') {
4326: $digit += $numletts;
4327: }
4328: }
4329: my $qval='';
4330: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4331: if ($j == $digit) {
4332: $qval .= $scantronconf{'Qon'};
4333: } else {
4334: $qval .= $scantronconf{'Qoff'};
4335: }
4336: }
4337: $values[$i] = $qval;
4338: }
4339: }
4340: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4341: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4342: }
4343: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4344: if ($numblank > 0) {
4345: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4346: }
4347: if ($csvbynum{$i} eq 'FirstQuestion') {
4348: $qstart = $i;
4349: $found{$csvbynum{$i}} = $values[$i];
4350: } else {
4351: $found{'FirstQuestion'} .= $values[$i];
4352: }
4353: } elsif (exists($csvbynum{$i})) {
4354: if ($csvoptions{'rem'}) {
4355: $values[$i] =~ s/^\s+//;
4356: }
4357: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4358: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4359: $values[$i] = '0'.$values[$i];
4360: }
4361: }
4362: $found{$csvbynum{$i}} = $values[$i];
4363: }
4364: }
4365: foreach my $item (@ordered) {
4366: my $currlength = 1+length($record);
4367: my $numspaces = $scantronconf{$item} - $currlength;
4368: if ($numspaces > 0) {
4369: $record .= (' ' x $numspaces);
4370: }
4371: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4372: unless ($item eq 'Qstart') {
4373: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4374: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4375: }
4376: }
4377: $record .= $found{$mapstart{$item}};
4378: }
4379: }
4380: $output .= "$record\n";
4381: }
4382: close($fh);
4383: if ($output) {
4384: if (open(my $fh,'>',$fullpath)) {
4385: print $fh $output;
4386: close($fh);
4387: }
4388: }
4389: }
4390: }
4391: return;
4392: }
4393: }
4394:
4395: sub letter_to_digits {
4396: my %lettdig = (
4397: A => 1,
4398: B => 2,
4399: C => 3,
4400: D => 4,
4401: E => 5,
4402: F => 6,
4403: G => 7,
4404: H => 8,
4405: I => 9,
4406: J => 0,
4407: );
4408: return %lettdig;
4409: }
4410:
4411: sub get_scantron_config {
4412: my ($which,$cdom) = @_;
4413: my @lines = &get_scantronformat_file($cdom);
4414: my %config;
4415: #FIXME probably should move to XML it has already gotten a bit much now
4416: foreach my $line (@lines) {
4417: my ($name,$descrip)=split(/:/,$line);
4418: if ($name ne $which ) { next; }
4419: chomp($line);
4420: my @config=split(/:/,$line);
4421: $config{'name'}=$config[0];
4422: $config{'description'}=$config[1];
4423: $config{'CODElocation'}=$config[2];
4424: $config{'CODEstart'}=$config[3];
4425: $config{'CODElength'}=$config[4];
4426: $config{'IDstart'}=$config[5];
4427: $config{'IDlength'}=$config[6];
4428: $config{'Qstart'}=$config[7];
4429: $config{'Qlength'}=$config[8];
4430: $config{'Qoff'}=$config[9];
4431: $config{'Qon'}=$config[10];
4432: $config{'PaperID'}=$config[11];
4433: $config{'PaperIDlength'}=$config[12];
4434: $config{'FirstName'}=$config[13];
4435: $config{'FirstNamelength'}=$config[14];
4436: $config{'LastName'}=$config[15];
4437: $config{'LastNamelength'}=$config[16];
4438: $config{'BubblesPerRow'}=$config[17];
4439: last;
4440: }
4441: return %config;
4442: }
4443:
4444: sub get_scantronformat_file {
4445: my ($cdom) = @_;
4446: if ($cdom eq '') {
4447: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4448: }
4449: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4450: my $gottab = 0;
4451: my @lines;
4452: if (ref($domconfig{'scantron'}) eq 'HASH') {
4453: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4454: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4455: if ($formatfile ne '-1') {
4456: @lines = split("\n",$formatfile,-1);
4457: $gottab = 1;
4458: }
4459: }
4460: }
4461: if (!$gottab) {
4462: my $confname = $cdom.'-domainconfig';
4463: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4464: my $formatfile = &getfile($default);
4465: if ($formatfile ne '-1') {
4466: @lines = split("\n",$formatfile,-1);
4467: $gottab = 1;
4468: }
4469: }
4470: if (!$gottab) {
4471: my @domains = ¤t_machine_domains();
4472: if (grep(/^\Q$cdom\E$/,@domains)) {
4473: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4474: @lines = <$fh>;
4475: close($fh);
4476: }
4477: } else {
4478: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4479: @lines = <$fh>;
4480: close($fh);
4481: }
4482: }
4483: }
4484: return @lines;
4485: }
4486:
4487: sub removeuploadedurl {
4488: my ($url)=@_;
4489: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4490: return &removeuserfile($uname,$udom,$fname);
4491: }
4492:
4493: sub removeuserfile {
4494: my ($docuname,$docudom,$fname)=@_;
4495: my $home=&homeserver($docuname,$docudom);
4496: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4497: if ($result eq 'ok') {
4498: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4499: my $metafile = $fname.'.meta';
4500: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4501: my $url = "/uploaded/$docudom/$docuname/$fname";
4502: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4503: my $sqlresult =
4504: &update_portfolio_table($docuname,$docudom,$file,
4505: 'portfolio_metadata',$group,
4506: 'delete');
4507: }
4508: }
4509: return $result;
4510: }
4511:
4512: sub mkdiruserfile {
4513: my ($docuname,$docudom,$dir)=@_;
4514: my $home=&homeserver($docuname,$docudom);
4515: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4516: }
4517:
4518: sub renameuserfile {
4519: my ($docuname,$docudom,$old,$new)=@_;
4520: my $home=&homeserver($docuname,$docudom);
4521: my $result = &reply("renameuserfile:$docudom:$docuname:".
4522: &escape("$old").':'.&escape("$new"),$home);
4523: if ($result eq 'ok') {
4524: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4525: my $oldmeta = $old.'.meta';
4526: my $newmeta = $new.'.meta';
4527: my $metaresult =
4528: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4529: my $url = "/uploaded/$docudom/$docuname/$old";
4530: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4531: my $sqlresult =
4532: &update_portfolio_table($docuname,$docudom,$file,
4533: 'portfolio_metadata',$group,
4534: 'delete');
4535: }
4536: }
4537: return $result;
4538: }
4539:
4540: # ------------------------------------------------------------------------- Log
4541:
4542: sub log {
4543: my ($dom,$nam,$hom,$what)=@_;
4544: return critical("log:$dom:$nam:$what",$hom);
4545: }
4546:
4547: # ------------------------------------------------------------------ Course Log
4548: #
4549: # This routine flushes several buffers of non-mission-critical nature
4550: #
4551:
4552: sub flushcourselogs {
4553: &logthis('Flushing log buffers');
4554: #
4555: # course logs
4556: # This is a log of all transactions in a course, which can be used
4557: # for data mining purposes
4558: #
4559: # It also collects the courseid database, which lists last transaction
4560: # times and course titles for all courseids
4561: #
4562: my %courseidbuffer=();
4563: foreach my $crsid (keys(%courselogs)) {
4564: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4565: &escape($courselogs{$crsid}),
4566: $coursehombuf{$crsid}) eq 'ok') {
4567: delete $courselogs{$crsid};
4568: } else {
4569: &logthis('Failed to flush log buffer for '.$crsid);
4570: if (length($courselogs{$crsid})>40000) {
4571: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4572: " exceeded maximum size, deleting.</font>");
4573: delete $courselogs{$crsid};
4574: }
4575: }
4576: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4577: 'description' => $coursedescrbuf{$crsid},
4578: 'inst_code' => $courseinstcodebuf{$crsid},
4579: 'type' => $coursetypebuf{$crsid},
4580: 'owner' => $courseownerbuf{$crsid},
4581: };
4582: }
4583: #
4584: # Write course id database (reverse lookup) to homeserver of courses
4585: # Is used in pickcourse
4586: #
4587: foreach my $crs_home (keys(%courseidbuffer)) {
4588: my $response = &courseidput(&host_domain($crs_home),
4589: $courseidbuffer{$crs_home},
4590: $crs_home,'timeonly');
4591: }
4592: #
4593: # File accesses
4594: # Writes to the dynamic metadata of resources to get hit counts, etc.
4595: #
4596: foreach my $entry (keys(%accesshash)) {
4597: if ($entry =~ /___count$/) {
4598: my ($dom,$name);
4599: ($dom,$name,undef)=
4600: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4601: if (! defined($dom) || $dom eq '' ||
4602: ! defined($name) || $name eq '') {
4603: my $cid = $env{'request.course.id'};
4604: $dom = $env{'request.'.$cid.'.domain'};
4605: $name = $env{'request.'.$cid.'.num'};
4606: }
4607: my $value = $accesshash{$entry};
4608: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4609: my %temphash=($url => $value);
4610: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4611: if ($result eq 'ok') {
4612: delete $accesshash{$entry};
4613: }
4614: } else {
4615: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4616: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4617: my %temphash=($entry => $accesshash{$entry});
4618: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4619: delete $accesshash{$entry};
4620: }
4621: }
4622: }
4623: #
4624: # Roles
4625: # Reverse lookup of user roles for course faculty/staff and co-authorship
4626: #
4627: foreach my $entry (keys(%userrolehash)) {
4628: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4629: split(/\:/,$entry);
4630: if (&Apache::lonnet::put('nohist_userroles',
4631: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4632: $rudom,$runame) eq 'ok') {
4633: delete $userrolehash{$entry};
4634: }
4635: }
4636: #
4637: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4638: #
4639: my %domrolebuffer = ();
4640: foreach my $entry (keys(%domainrolehash)) {
4641: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4642: if ($domrolebuffer{$rudom}) {
4643: $domrolebuffer{$rudom}.='&'.&escape($entry).
4644: '='.&escape($domainrolehash{$entry});
4645: } else {
4646: $domrolebuffer{$rudom}.=&escape($entry).
4647: '='.&escape($domainrolehash{$entry});
4648: }
4649: delete $domainrolehash{$entry};
4650: }
4651: foreach my $dom (keys(%domrolebuffer)) {
4652: my %servers;
4653: if (defined(&domain($dom,'primary'))) {
4654: my $primary=&domain($dom,'primary');
4655: my $hostname=&hostname($primary);
4656: $servers{$primary} = $hostname;
4657: } else {
4658: %servers = &get_servers($dom,'library');
4659: }
4660: foreach my $tryserver (keys(%servers)) {
4661: if (&reply('domroleput:'.$dom.':'.
4662: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4663: last;
4664: } else {
4665: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4666: }
4667: }
4668: }
4669: $dumpcount++;
4670: }
4671:
4672: sub courselog {
4673: my $what=shift;
4674: $what=time.':'.$what;
4675: unless ($env{'request.course.id'}) { return ''; }
4676: $coursedombuf{$env{'request.course.id'}}=
4677: $env{'course.'.$env{'request.course.id'}.'.domain'};
4678: $coursenumbuf{$env{'request.course.id'}}=
4679: $env{'course.'.$env{'request.course.id'}.'.num'};
4680: $coursehombuf{$env{'request.course.id'}}=
4681: $env{'course.'.$env{'request.course.id'}.'.home'};
4682: $coursedescrbuf{$env{'request.course.id'}}=
4683: $env{'course.'.$env{'request.course.id'}.'.description'};
4684: $courseinstcodebuf{$env{'request.course.id'}}=
4685: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4686: $courseownerbuf{$env{'request.course.id'}}=
4687: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
4688: $coursetypebuf{$env{'request.course.id'}}=
4689: $env{'course.'.$env{'request.course.id'}.'.type'};
4690: if (defined $courselogs{$env{'request.course.id'}}) {
4691: $courselogs{$env{'request.course.id'}}.='&'.$what;
4692: } else {
4693: $courselogs{$env{'request.course.id'}}.=$what;
4694: }
4695: if (length($courselogs{$env{'request.course.id'}})>4048) {
4696: &flushcourselogs();
4697: }
4698: }
4699:
4700: sub courseacclog {
4701: my $fnsymb=shift;
4702: unless ($env{'request.course.id'}) { return ''; }
4703: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
4704: if ($fnsymb=~/$LONCAPA::assess_re/) {
4705: $what.=':POST';
4706: # FIXME: Probably ought to escape things....
4707: foreach my $key (keys(%env)) {
4708: if ($key=~/^form\.(.*)/) {
4709: my $formitem = $1;
4710: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4711: $what.=':'.$formitem.'='.$env{$key};
4712: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4713: if ($formitem eq 'proctorpassword') {
4714: $what.=':'.$formitem.'=' . '*' x length($env{$key});
4715: } else {
4716: $what.=':'.$formitem.'='.$env{$key};
4717: }
4718: }
4719: }
4720: }
4721: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4722: # FIXME: We should not be depending on a form parameter that someone
4723: # editing lonsearchcat.pm might change in the future.
4724: if ($env{'form.phase'} eq 'course_search') {
4725: $what.= ':POST';
4726: # FIXME: Probably ought to escape things....
4727: foreach my $element ('courseexp','crsfulltext','crsrelated',
4728: 'crsdiscuss') {
4729: $what.=':'.$element.'='.$env{'form.'.$element};
4730: }
4731: }
4732: }
4733: &courselog($what);
4734: }
4735:
4736: sub countacc {
4737: my $url=&declutter(shift);
4738: return if (! defined($url) || $url eq '');
4739: unless ($env{'request.course.id'}) { return ''; }
4740: #
4741: # Mark that this url was used in this course
4742: #
4743: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
4744: #
4745: # Increase the access count for this resource in this child process
4746: #
4747: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
4748: $accesshash{$key}++;
4749: }
4750:
4751: sub linklog {
4752: my ($from,$to)=@_;
4753: $from=&declutter($from);
4754: $to=&declutter($to);
4755: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4756: $accesshash{$to.'___'.$from.'___goto'}=1;
4757: }
4758:
4759: sub statslog {
4760: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4761: if ($users<2) { return; }
4762: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4763: 'course' => $env{'request.course.id'},
4764: 'sections' => '"all"',
4765: 'num_students' => $users,
4766: 'part' => $part,
4767: 'symb' => $symb,
4768: 'mean_tries' => $av_attempts,
4769: 'deg_of_diff' => $degdiff});
4770: foreach my $key (keys(%dynstore)) {
4771: $accesshash{$key}=$dynstore{$key};
4772: }
4773: }
4774:
4775: sub userrolelog {
4776: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
4777: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
4778: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4779: $userrolehash
4780: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4781: =$tend.':'.$tstart;
4782: }
4783: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
4784: $userrolehash
4785: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4786: =$tend.':'.$tstart;
4787: }
4788: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
4789: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4790: $domainrolehash
4791: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4792: = $tend.':'.$tstart;
4793: }
4794: }
4795:
4796: sub courserolelog {
4797: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
4798: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4799: my $cdom = $1;
4800: my $cnum = $2;
4801: my $sec = $3;
4802: my $namespace = 'rolelog';
4803: my %storehash = (
4804: role => $trole,
4805: start => $tstart,
4806: end => $tend,
4807: selfenroll => $selfenroll,
4808: context => $context,
4809: );
4810: if ($trole eq 'gr') {
4811: $namespace = 'groupslog';
4812: $storehash{'group'} = $sec;
4813: } else {
4814: $storehash{'section'} = $sec;
4815: }
4816: &write_log('course',$namespace,\%storehash,$delflag,$username,
4817: $domain,$cnum,$cdom);
4818: if (($trole ne 'st') || ($sec ne '')) {
4819: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
4820: }
4821: }
4822: return;
4823: }
4824:
4825: sub domainrolelog {
4826: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4827: if ($area =~ m{^/($match_domain)/$}) {
4828: my $cdom = $1;
4829: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4830: my $namespace = 'rolelog';
4831: my %storehash = (
4832: role => $trole,
4833: start => $tstart,
4834: end => $tend,
4835: context => $context,
4836: );
4837: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4838: $domain,$domconfiguser,$cdom);
4839: }
4840: return;
4841:
4842: }
4843:
4844: sub coauthorrolelog {
4845: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4846: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4847: my $audom = $1;
4848: my $auname = $2;
4849: my $namespace = 'rolelog';
4850: my %storehash = (
4851: role => $trole,
4852: start => $tstart,
4853: end => $tend,
4854: context => $context,
4855: );
4856: &write_log('author',$namespace,\%storehash,$delflag,$username,
4857: $domain,$auname,$audom);
4858: }
4859: return;
4860: }
4861:
4862: sub get_course_adv_roles {
4863: my ($cid,$codes) = @_;
4864: $cid=$env{'request.course.id'} unless (defined($cid));
4865: my %coursehash=&coursedescription($cid);
4866: my $crstype = &Apache::loncommon::course_type($cid);
4867: my %nothide=();
4868: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4869: if ($user !~ /:/) {
4870: $nothide{join(':',split(/[\@]/,$user))}=1;
4871: } else {
4872: $nothide{$user}=1;
4873: }
4874: }
4875: my @possdoms = ($coursehash{'domain'});
4876: if ($coursehash{'checkforpriv'}) {
4877: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4878: }
4879: my %returnhash=();
4880: my %dumphash=
4881: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4882: my $now=time;
4883: my %privileged;
4884: foreach my $entry (keys(%dumphash)) {
4885: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4886: if (($tstart) && ($tstart<0)) { next; }
4887: if (($tend) && ($tend<$now)) { next; }
4888: if (($tstart) && ($now<$tstart)) { next; }
4889: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4890: if ($username eq '' || $domain eq '') { next; }
4891: if ((&privileged($username,$domain,\@possdoms)) &&
4892: (!$nothide{$username.':'.$domain})) { next; }
4893: if ($role eq 'cr') { next; }
4894: if ($codes) {
4895: if ($section) { $role .= ':'.$section; }
4896: if ($returnhash{$role}) {
4897: $returnhash{$role}.=','.$username.':'.$domain;
4898: } else {
4899: $returnhash{$role}=$username.':'.$domain;
4900: }
4901: } else {
4902: my $key=&plaintext($role,$crstype);
4903: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4904: if ($returnhash{$key}) {
4905: $returnhash{$key}.=','.$username.':'.$domain;
4906: } else {
4907: $returnhash{$key}=$username.':'.$domain;
4908: }
4909: }
4910: }
4911: return %returnhash;
4912: }
4913:
4914: sub get_my_roles {
4915: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4916: unless (defined($uname)) { $uname=$env{'user.name'}; }
4917: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4918: my (%dumphash,%nothide);
4919: if ($context eq 'userroles') {
4920: %dumphash = &dump('roles',$udom,$uname);
4921: } else {
4922: %dumphash = &dump('nohist_userroles',$udom,$uname);
4923: if ($hidepriv) {
4924: my %coursehash=&coursedescription($udom.'_'.$uname);
4925: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4926: if ($user !~ /:/) {
4927: $nothide{join(':',split(/[\@]/,$user))} = 1;
4928: } else {
4929: $nothide{$user} = 1;
4930: }
4931: }
4932: }
4933: }
4934: my %returnhash=();
4935: my $now=time;
4936: my %privileged;
4937: foreach my $entry (keys(%dumphash)) {
4938: my ($role,$tend,$tstart);
4939: if ($context eq 'userroles') {
4940: next if ($entry =~ /^rolesdef/);
4941: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4942: } else {
4943: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4944: }
4945: if (($tstart) && ($tstart<0)) { next; }
4946: my $status = 'active';
4947: if (($tend) && ($tend<=$now)) {
4948: $status = 'previous';
4949: }
4950: if (($tstart) && ($now<$tstart)) {
4951: $status = 'future';
4952: }
4953: if (ref($types) eq 'ARRAY') {
4954: if (!grep(/^\Q$status\E$/,@{$types})) {
4955: next;
4956: }
4957: } else {
4958: if ($status ne 'active') {
4959: next;
4960: }
4961: }
4962: my ($rolecode,$username,$domain,$section,$area);
4963: if ($context eq 'userroles') {
4964: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4965: (undef,$domain,$username,$section) = split(/\//,$area);
4966: } else {
4967: ($role,$username,$domain,$section) = split(/\:/,$entry);
4968: }
4969: if (ref($roledoms) eq 'ARRAY') {
4970: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4971: next;
4972: }
4973: }
4974: if (ref($roles) eq 'ARRAY') {
4975: if (!grep(/^\Q$role\E$/,@{$roles})) {
4976: if ($role =~ /^cr\//) {
4977: if (!grep(/^cr$/,@{$roles})) {
4978: next;
4979: }
4980: } elsif ($role =~ /^gr\//) {
4981: if (!grep(/^gr$/,@{$roles})) {
4982: next;
4983: }
4984: } else {
4985: next;
4986: }
4987: }
4988: }
4989: if ($hidepriv) {
4990: my @privroles = ('dc','su');
4991: if ($context eq 'userroles') {
4992: next if (grep(/^\Q$role\E$/,@privroles));
4993: } else {
4994: my $possdoms = [$domain];
4995: if (ref($roledoms) eq 'ARRAY') {
4996: push(@{$possdoms},@{$roledoms});
4997: }
4998: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4999: if (!$nothide{$username.':'.$domain}) {
5000: next;
5001: }
5002: }
5003: }
5004: }
5005: if ($withsec) {
5006: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
5007: $tstart.':'.$tend;
5008: } else {
5009: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
5010: }
5011: }
5012: return %returnhash;
5013: }
5014:
5015: sub get_all_adhocroles {
5016: my ($dom) = @_;
5017: my @roles_by_num = ();
5018: my %domdefaults = &get_domain_defaults($dom);
5019: my (%description,%access_in_dom,%access_info);
5020: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
5021: my $count = 0;
5022: my %domcurrent = %{$domdefaults{'adhocroles'}};
5023: my %ordered;
5024: foreach my $role (sort(keys(%domcurrent))) {
5025: my ($order,$desc,$access_in_dom);
5026: if (ref($domcurrent{$role}) eq 'HASH') {
5027: $order = $domcurrent{$role}{'order'};
5028: $desc = $domcurrent{$role}{'desc'};
5029: $access_in_dom{$role} = $domcurrent{$role}{'access'};
5030: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
5031: }
5032: if ($order eq '') {
5033: $order = $count;
5034: }
5035: $ordered{$order} = $role;
5036: if ($desc ne '') {
5037: $description{$role} = $desc;
5038: } else {
5039: $description{$role}= $role;
5040: }
5041: $count++;
5042: }
5043: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
5044: push(@roles_by_num,$ordered{$item});
5045: }
5046: }
5047: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
5048: }
5049:
5050: sub get_my_adhocroles {
5051: my ($cid,$checkreg) = @_;
5052: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
5053: if ($env{'request.course.id'} eq $cid) {
5054: $cdom = $env{'course.'.$cid.'.domain'};
5055: $cnum = $env{'course.'.$cid.'.num'};
5056: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
5057: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
5058: $cdom = $1;
5059: $cnum = $2;
5060: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
5061: $cdom,$cnum);
5062: }
5063: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
5064: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5065: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
5066: if ($rosterhash{$user} ne '') {
5067: my $type = (split(/:/,$rosterhash{$user}))[5];
5068: return ([],{}) if ($type eq 'auto');
5069: }
5070: }
5071: if (($cdom ne '') && ($cnum ne '')) {
5072: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
5073: my $then=$env{'user.login.time'};
5074: my $update=$env{'user.update.time'};
5075: if (!$update) {
5076: $update = $then;
5077: }
5078: my @liveroles;
5079: foreach my $role ('dh','da') {
5080: if ($env{"user.role.$role./$cdom/"}) {
5081: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5082: my $limit = $update;
5083: if ($env{'request.role'} eq "$role./$cdom/") {
5084: $limit = $then;
5085: }
5086: my $activerole = 1;
5087: if ($tstart && $tstart>$limit) { $activerole = 0; }
5088: if ($tend && $tend <$limit) { $activerole = 0; }
5089: if ($activerole) {
5090: push(@liveroles,$role);
5091: }
5092: }
5093: }
5094: if (@liveroles) {
5095: if (&homeserver($cnum,$cdom) ne 'no_host') {
5096: my ($accessref,$accessinfo,%access_in_dom);
5097: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5098: if (ref($roles_by_num) eq 'ARRAY') {
5099: if (@{$roles_by_num}) {
5100: my %settings;
5101: if ($env{'request.course.id'} eq $cid) {
5102: foreach my $envkey (keys(%env)) {
5103: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5104: $settings{$1} = $env{$envkey};
5105: }
5106: }
5107: } else {
5108: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5109: }
5110: my %setincrs;
5111: if ($settings{'internal.adhocaccess'}) {
5112: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5113: }
5114: my @statuses;
5115: if ($env{'environment.inststatus'}) {
5116: @statuses = split(/,/,$env{'environment.inststatus'});
5117: }
5118: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5119: if (ref($accessref) eq 'HASH') {
5120: %access_in_dom = %{$accessref};
5121: }
5122: foreach my $role (@{$roles_by_num}) {
5123: my ($curraccess,@okstatus,@personnel);
5124: if ($setincrs{$role}) {
5125: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5126: if ($curraccess eq 'status') {
5127: @okstatus = split(/\&/,$rest);
5128: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5129: @personnel = split(/\&/,$rest);
5130: }
5131: } else {
5132: $curraccess = $access_in_dom{$role};
5133: if (ref($accessinfo) eq 'HASH') {
5134: if ($curraccess eq 'status') {
5135: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5136: @okstatus = @{$accessinfo->{$role}};
5137: }
5138: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5139: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5140: @personnel = @{$accessinfo->{$role}};
5141: }
5142: }
5143: }
5144: }
5145: if ($curraccess eq 'none') {
5146: next;
5147: } elsif ($curraccess eq 'all') {
5148: push(@possroles,$role);
5149: } elsif ($curraccess eq 'dh') {
5150: if (grep(/^dh$/,@liveroles)) {
5151: push(@possroles,$role);
5152: } else {
5153: next;
5154: }
5155: } elsif ($curraccess eq 'da') {
5156: if (grep(/^da$/,@liveroles)) {
5157: push(@possroles,$role);
5158: } else {
5159: next;
5160: }
5161: } elsif ($curraccess eq 'status') {
5162: if (@okstatus) {
5163: if (!@statuses) {
5164: if (grep(/^default$/,@okstatus)) {
5165: push(@possroles,$role);
5166: }
5167: } else {
5168: foreach my $status (@okstatus) {
5169: if (grep(/^\Q$status\E$/,@statuses)) {
5170: push(@possroles,$role);
5171: last;
5172: }
5173: }
5174: }
5175: }
5176: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5177: if (grep(/^\Q$user\E$/,@personnel)) {
5178: if ($curraccess eq 'exc') {
5179: push(@possroles,$role);
5180: }
5181: } elsif ($curraccess eq 'inc') {
5182: push(@possroles,$role);
5183: }
5184: }
5185: }
5186: }
5187: }
5188: }
5189: }
5190: }
5191: }
5192: unless (ref($description) eq 'HASH') {
5193: if (ref($roles_by_num) eq 'ARRAY') {
5194: my %desc;
5195: map { $desc{$_} = $_; } (@{$roles_by_num});
5196: $description = \%desc;
5197: } else {
5198: $description = {};
5199: }
5200: }
5201: return (\@possroles,$description);
5202: }
5203:
5204: # ----------------------------------------------------- Frontpage Announcements
5205: #
5206: #
5207:
5208: sub postannounce {
5209: my ($server,$text)=@_;
5210: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
5211: unless ($text=~/\w/) { $text=''; }
5212: return &reply('setannounce:'.&escape($text),$server);
5213: }
5214:
5215: sub getannounce {
5216:
5217: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
5218: my $announcement='';
5219: while (my $line = <$fh>) { $announcement .= $line; }
5220: close($fh);
5221: if ($announcement=~/\w/) {
5222: return
5223: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
5224: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
5225: } else {
5226: return '';
5227: }
5228: } else {
5229: return '';
5230: }
5231: }
5232:
5233: # ---------------------------------------------------------- Course ID routines
5234: # Deal with domain's nohist_courseid.db files
5235: #
5236:
5237: sub courseidput {
5238: my ($domain,$storehash,$coursehome,$caller) = @_;
5239: return unless (ref($storehash) eq 'HASH');
5240: my $outcome;
5241: if ($caller eq 'timeonly') {
5242: my $cids = '';
5243: foreach my $item (keys(%$storehash)) {
5244: $cids.=&escape($item).'&';
5245: }
5246: $cids=~s/\&$//;
5247: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5248: $coursehome);
5249: } else {
5250: my $items = '';
5251: foreach my $item (keys(%$storehash)) {
5252: $items.= &escape($item).'='.
5253: &freeze_escape($$storehash{$item}).'&';
5254: }
5255: $items=~s/\&$//;
5256: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5257: $coursehome);
5258: }
5259: if ($outcome eq 'unknown_cmd') {
5260: my $what;
5261: foreach my $cid (keys(%$storehash)) {
5262: $what .= &escape($cid).'=';
5263: foreach my $item ('description','inst_code','owner','type') {
5264: $what .= &escape($storehash->{$cid}{$item}).':';
5265: }
5266: $what =~ s/\:$/&/;
5267: }
5268: $what =~ s/\&$//;
5269: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5270: } else {
5271: return $outcome;
5272: }
5273: }
5274:
5275: sub courseiddump {
5276: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
5277: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
5278: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
5279: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
5280: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
5281: my $as_hash = 1;
5282: my %returnhash;
5283: if (!$domfilter) { $domfilter=''; }
5284: my %libserv = &all_library();
5285: foreach my $tryserver (keys(%libserv)) {
5286: if ( ( $hostidflag == 1
5287: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5288: || (!defined($hostidflag)) ) {
5289:
5290: if (($domfilter eq '') ||
5291: (&host_domain($tryserver) eq $domfilter)) {
5292: my $rep;
5293: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5294: $rep = &LONCAPA::Lond::dump_course_id_handler(
5295: join(":", (&host_domain($tryserver), $sincefilter,
5296: &escape($descfilter), &escape($instcodefilter),
5297: &escape($ownerfilter), &escape($coursefilter),
5298: &escape($typefilter), &escape($regexp_ok),
5299: $as_hash, &escape($selfenrollonly),
5300: &escape($catfilter), $showhidden, $caller,
5301: &escape($cloner), &escape($cc_clone), $cloneonly,
5302: &escape($createdbefore), &escape($createdafter),
5303: &escape($creationcontext),$domcloner,$hasuniquecode,
5304: $reqcrsdom,&escape($reqinstcode))));
5305: } else {
5306: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5307: $sincefilter.':'.&escape($descfilter).':'.
5308: &escape($instcodefilter).':'.&escape($ownerfilter).
5309: ':'.&escape($coursefilter).':'.&escape($typefilter).
5310: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5311: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5312: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5313: &escape($cc_clone).':'.$cloneonly.':'.
5314: &escape($createdbefore).':'.&escape($createdafter).':'.
5315: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5316: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5317: }
5318:
5319: my @pairs=split(/\&/,$rep);
5320: foreach my $item (@pairs) {
5321: my ($key,$value)=split(/\=/,$item,2);
5322: $key = &unescape($key);
5323: next if ($key =~ /^error: 2 /);
5324: my $result = &thaw_unescape($value);
5325: if (ref($result) eq 'HASH') {
5326: $returnhash{$key}=$result;
5327: } else {
5328: my @responses = split(/:/,$value);
5329: my @items = ('description','inst_code','owner','type');
5330: for (my $i=0; $i<@responses; $i++) {
5331: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5332: }
5333: }
5334: }
5335: }
5336: }
5337: }
5338: return %returnhash;
5339: }
5340:
5341: sub courselastaccess {
5342: my ($cdom,$cnum,$hostidref) = @_;
5343: my %returnhash;
5344: if ($cdom && $cnum) {
5345: my $chome = &homeserver($cnum,$cdom);
5346: if ($chome ne 'no_host') {
5347: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5348: &extract_lastaccess(\%returnhash,$rep);
5349: }
5350: } else {
5351: if (!$cdom) { $cdom=''; }
5352: my %libserv = &all_library();
5353: foreach my $tryserver (keys(%libserv)) {
5354: if (ref($hostidref) eq 'ARRAY') {
5355: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5356: }
5357: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5358: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5359: &extract_lastaccess(\%returnhash,$rep);
5360: }
5361: }
5362: }
5363: return %returnhash;
5364: }
5365:
5366: sub extract_lastaccess {
5367: my ($returnhash,$rep) = @_;
5368: if (ref($returnhash) eq 'HASH') {
5369: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5370: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5371: $rep eq '') {
5372: my @pairs=split(/\&/,$rep);
5373: foreach my $item (@pairs) {
5374: my ($key,$value)=split(/\=/,$item,2);
5375: $key = &unescape($key);
5376: next if ($key =~ /^error: 2 /);
5377: $returnhash->{$key} = &thaw_unescape($value);
5378: }
5379: }
5380: }
5381: return;
5382: }
5383:
5384: # ---------------------------------------------------------- DC e-mail
5385:
5386: sub dcmailput {
5387: my ($domain,$msgid,$message,$server)=@_;
5388: my $status = &Apache::lonnet::critical(
5389: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5390: &escape($message),$server);
5391: return $status;
5392: }
5393:
5394: sub dcmaildump {
5395: my ($dom,$startdate,$enddate,$senders) = @_;
5396: my %returnhash=();
5397:
5398: if (defined(&domain($dom,'primary'))) {
5399: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5400: &escape($enddate).':';
5401: my @esc_senders=map { &escape($_)} @$senders;
5402: $cmd.=&escape(join('&',@esc_senders));
5403: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5404: my ($key,$value) = split(/\=/,$line,2);
5405: if (($key) && ($value)) {
5406: $returnhash{&unescape($key)} = &unescape($value);
5407: }
5408: }
5409: }
5410: return %returnhash;
5411: }
5412: # ---------------------------------------------------------- Domain roles
5413:
5414: sub get_domain_roles {
5415: my ($dom,$roles,$startdate,$enddate)=@_;
5416: if ((!defined($startdate)) || ($startdate eq '')) {
5417: $startdate = '.';
5418: }
5419: if ((!defined($enddate)) || ($enddate eq '')) {
5420: $enddate = '.';
5421: }
5422: my $rolelist;
5423: if (ref($roles) eq 'ARRAY') {
5424: $rolelist = join('&',@{$roles});
5425: }
5426: my %personnel = ();
5427:
5428: my %servers = &get_servers($dom,'library');
5429: foreach my $tryserver (keys(%servers)) {
5430: %{$personnel{$tryserver}}=();
5431: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5432: &escape($startdate).':'.
5433: &escape($enddate).':'.
5434: &escape($rolelist), $tryserver))) {
5435: my ($key,$value) = split(/\=/,$line,2);
5436: if (($key) && ($value)) {
5437: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5438: }
5439: }
5440: }
5441: return %personnel;
5442: }
5443:
5444: sub get_active_domroles {
5445: my ($dom,$roles) = @_;
5446: return () unless (ref($roles) eq 'ARRAY');
5447: my $now = time;
5448: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5449: my %domroles;
5450: foreach my $server (keys(%dompersonnel)) {
5451: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5452: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5453: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5454: }
5455: }
5456: return %domroles;
5457: }
5458:
5459: # ----------------------------------------------------------- Interval timing
5460:
5461: {
5462: # Caches needed for speedup of navmaps
5463: # We don't want to cache this for very long at all (5 seconds at most)
5464: #
5465: # The user for whom we cache
5466: my $cachedkey='';
5467: # The cached times for this user
5468: my %cachedtimes=();
5469: # When this was last done
5470: my $cachedtime='';
5471:
5472: sub load_all_first_access {
5473: my ($uname,$udom,$ignorecache)=@_;
5474: if (($cachedkey eq $uname.':'.$udom) &&
5475: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'}) &&
5476: (!$ignorecache)) {
5477: return;
5478: }
5479: $cachedtime=time;
5480: $cachedkey=$uname.':'.$udom;
5481: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5482: }
5483:
5484: sub get_first_access {
5485: my ($type,$argsymb,$argmap,$ignorecache)=@_;
5486: my ($symb,$courseid,$udom,$uname)=&whichuser();
5487: if ($argsymb) { $symb=$argsymb; }
5488: my ($map,$id,$res)=&decode_symb($symb);
5489: if ($argmap) { $map = $argmap; }
5490: if ($type eq 'course') {
5491: $res='course';
5492: } elsif ($type eq 'map') {
5493: $res=&symbread($map);
5494: } else {
5495: $res=$symb;
5496: }
5497: &load_all_first_access($uname,$udom,$ignorecache);
5498: return $cachedtimes{"$courseid\0$res"};
5499: }
5500:
5501: sub set_first_access {
5502: my ($type,$interval)=@_;
5503: my ($symb,$courseid,$udom,$uname)=&whichuser();
5504: my ($map,$id,$res)=&decode_symb($symb);
5505: if ($type eq 'course') {
5506: $res='course';
5507: } elsif ($type eq 'map') {
5508: $res=&symbread($map);
5509: } else {
5510: $res=$symb;
5511: }
5512: $cachedkey='';
5513: my $firstaccess=&get_first_access($type,$symb,$map);
5514: if ($firstaccess) {
5515: &logthis("First access time already set ($firstaccess) when attempting ".
5516: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5517: "in $courseid");
5518: return 'already_set';
5519: } else {
5520: my $start = time;
5521: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5522: $udom,$uname);
5523: if ($putres eq 'ok') {
5524: &put('timerinterval',{"$courseid\0$res"=>$interval},
5525: $udom,$uname);
5526: &appenv(
5527: {
5528: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5529: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5530: }
5531: );
5532: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5533: $cachedtimes{"$courseid\0$res"} = $start;
5534: }
5535: } elsif ($putres ne 'refused') {
5536: &logthis("Result: $putres when attempting to set first access time ".
5537: "(type: $type, extent: $res) for $uname:$udom in $courseid");
5538: }
5539: return $putres;
5540: }
5541: return 'already_set';
5542: }
5543: }
5544:
5545: sub checkout {
5546: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5547: my $now=time;
5548: my $lonhost=$perlvar{'lonHostID'};
5549: my $ip = &get_requestor_ip();
5550: my $infostr=&escape(
5551: 'CHECKOUTTOKEN&'.
5552: $tuname.'&'.
5553: $tudom.'&'.
5554: $tcrsid.'&'.
5555: $symb.'&'.
5556: $now.'&'.$ip);
5557: my $token=&reply('tmpput:'.$infostr,$lonhost);
5558: if ($token=~/^error\:/) {
5559: &logthis("<font color=\"blue\">WARNING: ".
5560: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5561: "</font>");
5562: return '';
5563: }
5564:
5565: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5566: $token=~tr/a-z/A-Z/;
5567:
5568: my %infohash=('resource.0.outtoken' => $token,
5569: 'resource.0.checkouttime' => $now,
5570: 'resource.0.outremote' => $ip);
5571:
5572: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5573: return '';
5574: } else {
5575: &logthis("<font color=\"blue\">WARNING: ".
5576: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5577: "</font>");
5578: }
5579:
5580: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5581: &escape('Checkout '.$infostr.' - '.
5582: $token)) ne 'ok') {
5583: return '';
5584: } else {
5585: &logthis("<font color=\"blue\">WARNING: ".
5586: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5587: "</font>");
5588: }
5589: return $token;
5590: }
5591:
5592: # ------------------------------------------------------------ Check in an item
5593:
5594: sub checkin {
5595: my $token=shift;
5596: my $now=time;
5597: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5598: $lonhost=~tr/A-Z/a-z/;
5599: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5600: $dtoken=~s/\W/\_/g;
5601: my $ip = &get_requestor_ip();
5602: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5603: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5604:
5605: unless (($tuname) && ($tudom)) {
5606: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5607: return '';
5608: }
5609:
5610: unless (&allowed('mgr',$tcrsid)) {
5611: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5612: $env{'user.name'}.' - '.$env{'user.domain'});
5613: return '';
5614: }
5615:
5616: my %infohash=('resource.0.intoken' => $token,
5617: 'resource.0.checkintime' => $now,
5618: 'resource.0.inremote' => $ip);
5619:
5620: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5621: return '';
5622: }
5623:
5624: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5625: &escape('Checkin - '.$token)) ne 'ok') {
5626: return '';
5627: }
5628:
5629: return ($symb,$tuname,$tudom,$tcrsid);
5630: }
5631:
5632: # --------------------------------------------- Set Expire Date for Spreadsheet
5633:
5634: sub expirespread {
5635: my ($uname,$udom,$stype,$usymb)=@_;
5636: my $cid=$env{'request.course.id'};
5637: if ($cid) {
5638: my $now=time;
5639: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5640: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5641: $env{'course.'.$cid.'.num'}.
5642: ':nohist_expirationdates:'.
5643: &escape($key).'='.$now,
5644: $env{'course.'.$cid.'.home'})
5645: }
5646: return 'ok';
5647: }
5648:
5649: # ----------------------------------------------------- Devalidate Spreadsheets
5650:
5651: sub devalidate {
5652: my ($symb,$uname,$udom)=@_;
5653: my $cid=$env{'request.course.id'};
5654: if ($cid) {
5655: # delete the stored spreadsheets for
5656: # - the student level sheet of this user in course's homespace
5657: # - the assessment level sheet for this resource
5658: # for this user in user's homespace
5659: # - current conditional state info
5660: my $key=$uname.':'.$udom.':';
5661: my $status=
5662: &del('nohist_calculatedsheets',
5663: [$key.'studentcalc:'],
5664: $env{'course.'.$cid.'.domain'},
5665: $env{'course.'.$cid.'.num'})
5666: .' '.
5667: &del('nohist_calculatedsheets_'.$cid,
5668: [$key.'assesscalc:'.$symb],$udom,$uname);
5669: unless ($status eq 'ok ok') {
5670: &logthis('Could not devalidate spreadsheet '.
5671: $uname.' at '.$udom.' for '.
5672: $symb.': '.$status);
5673: }
5674: &delenv('user.state.'.$cid);
5675: }
5676: }
5677:
5678: sub get_scalar {
5679: my ($string,$end) = @_;
5680: my $value;
5681: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5682: $value = $1;
5683: } elsif ($$string =~ s/^([^&]*?)&//) {
5684: $value = $1;
5685: }
5686: return &unescape($value);
5687: }
5688:
5689: sub array2str {
5690: my (@array) = @_;
5691: my $result=&arrayref2str(\@array);
5692: $result=~s/^__ARRAY_REF__//;
5693: $result=~s/__END_ARRAY_REF__$//;
5694: return $result;
5695: }
5696:
5697: sub arrayref2str {
5698: my ($arrayref) = @_;
5699: my $result='__ARRAY_REF__';
5700: foreach my $elem (@$arrayref) {
5701: if(ref($elem) eq 'ARRAY') {
5702: $result.=&arrayref2str($elem).'&';
5703: } elsif(ref($elem) eq 'HASH') {
5704: $result.=&hashref2str($elem).'&';
5705: } elsif(ref($elem)) {
5706: #print("Got a ref of ".(ref($elem))." skipping.");
5707: } else {
5708: $result.=&escape($elem).'&';
5709: }
5710: }
5711: $result=~s/\&$//;
5712: $result .= '__END_ARRAY_REF__';
5713: return $result;
5714: }
5715:
5716: sub hash2str {
5717: my (%hash) = @_;
5718: my $result=&hashref2str(\%hash);
5719: $result=~s/^__HASH_REF__//;
5720: $result=~s/__END_HASH_REF__$//;
5721: return $result;
5722: }
5723:
5724: sub hashref2str {
5725: my ($hashref)=@_;
5726: my $result='__HASH_REF__';
5727: foreach my $key (sort(keys(%$hashref))) {
5728: if (ref($key) eq 'ARRAY') {
5729: $result.=&arrayref2str($key).'=';
5730: } elsif (ref($key) eq 'HASH') {
5731: $result.=&hashref2str($key).'=';
5732: } elsif (ref($key)) {
5733: $result.='=';
5734: #print("Got a ref of ".(ref($key))." skipping.");
5735: } else {
5736: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5737: }
5738:
5739: if(ref($hashref->{$key}) eq 'ARRAY') {
5740: $result.=&arrayref2str($hashref->{$key}).'&';
5741: } elsif(ref($hashref->{$key}) eq 'HASH') {
5742: $result.=&hashref2str($hashref->{$key}).'&';
5743: } elsif(ref($hashref->{$key})) {
5744: $result.='&';
5745: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5746: } else {
5747: $result.=&escape($hashref->{$key}).'&';
5748: }
5749: }
5750: $result=~s/\&$//;
5751: $result .= '__END_HASH_REF__';
5752: return $result;
5753: }
5754:
5755: sub str2hash {
5756: my ($string)=@_;
5757: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5758: return %$hash;
5759: }
5760:
5761: sub str2hashref {
5762: my ($string) = @_;
5763:
5764: my %hash;
5765:
5766: if($string !~ /^__HASH_REF__/) {
5767: if (! ($string eq '' || !defined($string))) {
5768: $hash{'error'}='Not hash reference';
5769: }
5770: return (\%hash, $string);
5771: }
5772:
5773: $string =~ s/^__HASH_REF__//;
5774:
5775: while($string !~ /^__END_HASH_REF__/) {
5776: #key
5777: my $key='';
5778: if($string =~ /^__HASH_REF__/) {
5779: ($key, $string)=&str2hashref($string);
5780: if(defined($key->{'error'})) {
5781: $hash{'error'}='Bad data';
5782: return (\%hash, $string);
5783: }
5784: } elsif($string =~ /^__ARRAY_REF__/) {
5785: ($key, $string)=&str2arrayref($string);
5786: if($key->[0] eq 'Array reference error') {
5787: $hash{'error'}='Bad data';
5788: return (\%hash, $string);
5789: }
5790: } else {
5791: $string =~ s/^(.*?)=//;
5792: $key=&unescape($1);
5793: }
5794: $string =~ s/^=//;
5795:
5796: #value
5797: my $value='';
5798: if($string =~ /^__HASH_REF__/) {
5799: ($value, $string)=&str2hashref($string);
5800: if(defined($value->{'error'})) {
5801: $hash{'error'}='Bad data';
5802: return (\%hash, $string);
5803: }
5804: } elsif($string =~ /^__ARRAY_REF__/) {
5805: ($value, $string)=&str2arrayref($string);
5806: if($value->[0] eq 'Array reference error') {
5807: $hash{'error'}='Bad data';
5808: return (\%hash, $string);
5809: }
5810: } else {
5811: $value=&get_scalar(\$string,'__END_HASH_REF__');
5812: }
5813: $string =~ s/^&//;
5814:
5815: $hash{$key}=$value;
5816: }
5817:
5818: $string =~ s/^__END_HASH_REF__//;
5819:
5820: return (\%hash, $string);
5821: }
5822:
5823: sub str2array {
5824: my ($string)=@_;
5825: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5826: return @$array;
5827: }
5828:
5829: sub str2arrayref {
5830: my ($string) = @_;
5831: my @array;
5832:
5833: if($string !~ /^__ARRAY_REF__/) {
5834: if (! ($string eq '' || !defined($string))) {
5835: $array[0]='Array reference error';
5836: }
5837: return (\@array, $string);
5838: }
5839:
5840: $string =~ s/^__ARRAY_REF__//;
5841:
5842: while($string !~ /^__END_ARRAY_REF__/) {
5843: my $value='';
5844: if($string =~ /^__HASH_REF__/) {
5845: ($value, $string)=&str2hashref($string);
5846: if(defined($value->{'error'})) {
5847: $array[0] ='Array reference error';
5848: return (\@array, $string);
5849: }
5850: } elsif($string =~ /^__ARRAY_REF__/) {
5851: ($value, $string)=&str2arrayref($string);
5852: if($value->[0] eq 'Array reference error') {
5853: $array[0] ='Array reference error';
5854: return (\@array, $string);
5855: }
5856: } else {
5857: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5858: }
5859: $string =~ s/^&//;
5860:
5861: push(@array, $value);
5862: }
5863:
5864: $string =~ s/^__END_ARRAY_REF__//;
5865:
5866: return (\@array, $string);
5867: }
5868:
5869: # -------------------------------------------------------------------Temp Store
5870:
5871: sub tmpreset {
5872: my ($symb,$namespace,$domain,$stuname) = @_;
5873: if (!$symb) {
5874: $symb=&symbread();
5875: if (!$symb) { $symb= $env{'request.url'}; }
5876: }
5877: $symb=escape($symb);
5878:
5879: if (!$namespace) { $namespace=$env{'request.state'}; }
5880: $namespace=~s/\//\_/g;
5881: $namespace=~s/\W//g;
5882:
5883: if (!$domain) { $domain=$env{'user.domain'}; }
5884: if (!$stuname) { $stuname=$env{'user.name'}; }
5885: if ($domain eq 'public' && $stuname eq 'public') {
5886: $stuname=&get_requestor_ip();
5887: }
5888: my $path=LONCAPA::tempdir();
5889: my %hash;
5890: if (tie(%hash,'GDBM_File',
5891: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5892: &GDBM_WRCREAT(),0640)) {
5893: foreach my $key (keys(%hash)) {
5894: if ($key=~ /:$symb/) {
5895: delete($hash{$key});
5896: }
5897: }
5898: }
5899: }
5900:
5901: sub tmpstore {
5902: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5903:
5904: if (!$symb) {
5905: $symb=&symbread();
5906: if (!$symb) { $symb= $env{'request.url'}; }
5907: }
5908: $symb=escape($symb);
5909:
5910: if (!$namespace) {
5911: # I don't think we would ever want to store this for a course.
5912: # it seems this will only be used if we don't have a course.
5913: #$namespace=$env{'request.course.id'};
5914: #if (!$namespace) {
5915: $namespace=$env{'request.state'};
5916: #}
5917: }
5918: $namespace=~s/\//\_/g;
5919: $namespace=~s/\W//g;
5920: if (!$domain) { $domain=$env{'user.domain'}; }
5921: if (!$stuname) { $stuname=$env{'user.name'}; }
5922: if ($domain eq 'public' && $stuname eq 'public') {
5923: $stuname=&get_requestor_ip();
5924: }
5925: my $now=time;
5926: my %hash;
5927: my $path=LONCAPA::tempdir();
5928: if (tie(%hash,'GDBM_File',
5929: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5930: &GDBM_WRCREAT(),0640)) {
5931: $hash{"version:$symb"}++;
5932: my $version=$hash{"version:$symb"};
5933: my $allkeys='';
5934: foreach my $key (keys(%$storehash)) {
5935: $allkeys.=$key.':';
5936: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
5937: }
5938: $hash{"$version:$symb:timestamp"}=$now;
5939: $allkeys.='timestamp';
5940: $hash{"$version:keys:$symb"}=$allkeys;
5941: if (untie(%hash)) {
5942: return 'ok';
5943: } else {
5944: return "error:$!";
5945: }
5946: } else {
5947: return "error:$!";
5948: }
5949: }
5950:
5951: # -----------------------------------------------------------------Temp Restore
5952:
5953: sub tmprestore {
5954: my ($symb,$namespace,$domain,$stuname) = @_;
5955:
5956: if (!$symb) {
5957: $symb=&symbread();
5958: if (!$symb) { $symb= $env{'request.url'}; }
5959: }
5960: $symb=escape($symb);
5961:
5962: if (!$namespace) { $namespace=$env{'request.state'}; }
5963:
5964: if (!$domain) { $domain=$env{'user.domain'}; }
5965: if (!$stuname) { $stuname=$env{'user.name'}; }
5966: if ($domain eq 'public' && $stuname eq 'public') {
5967: $stuname=&get_requestor_ip();
5968: }
5969: my %returnhash;
5970: $namespace=~s/\//\_/g;
5971: $namespace=~s/\W//g;
5972: my %hash;
5973: my $path=LONCAPA::tempdir();
5974: if (tie(%hash,'GDBM_File',
5975: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5976: &GDBM_READER(),0640)) {
5977: my $version=$hash{"version:$symb"};
5978: $returnhash{'version'}=$version;
5979: my $scope;
5980: for ($scope=1;$scope<=$version;$scope++) {
5981: my $vkeys=$hash{"$scope:keys:$symb"};
5982: my @keys=split(/:/,$vkeys);
5983: my $key;
5984: $returnhash{"$scope:keys"}=$vkeys;
5985: foreach $key (@keys) {
5986: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5987: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5988: }
5989: }
5990: if (!(untie(%hash))) {
5991: return "error:$!";
5992: }
5993: } else {
5994: return "error:$!";
5995: }
5996: return %returnhash;
5997: }
5998:
5999: # ----------------------------------------------------------------------- Store
6000:
6001: sub store {
6002: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6003: my $home='';
6004:
6005: if ($stuname) { $home=&homeserver($stuname,$domain); }
6006:
6007: $symb=&symbclean($symb);
6008: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6009:
6010: if (!$domain) { $domain=$env{'user.domain'}; }
6011: if (!$stuname) { $stuname=$env{'user.name'}; }
6012:
6013: &devalidate($symb,$stuname,$domain);
6014:
6015: $symb=escape($symb);
6016: if (!$namespace) {
6017: unless ($namespace=$env{'request.course.id'}) {
6018: return '';
6019: }
6020: }
6021: if (!$home) { $home=$env{'user.home'}; }
6022:
6023: $$storehash{'ip'}=&get_requestor_ip();
6024: $$storehash{'host'}=$perlvar{'lonHostID'};
6025:
6026: my $namevalue='';
6027: foreach my $key (keys(%$storehash)) {
6028: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6029: }
6030: $namevalue=~s/\&$//;
6031: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
6032: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6033: }
6034:
6035: # -------------------------------------------------------------- Critical Store
6036:
6037: sub cstore {
6038: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
6039: my $home='';
6040:
6041: if ($stuname) { $home=&homeserver($stuname,$domain); }
6042:
6043: $symb=&symbclean($symb);
6044: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
6045:
6046: if (!$domain) { $domain=$env{'user.domain'}; }
6047: if (!$stuname) { $stuname=$env{'user.name'}; }
6048:
6049: &devalidate($symb,$stuname,$domain);
6050:
6051: $symb=escape($symb);
6052: if (!$namespace) {
6053: unless ($namespace=$env{'request.course.id'}) {
6054: return '';
6055: }
6056: }
6057: if (!$home) { $home=$env{'user.home'}; }
6058:
6059: $$storehash{'ip'}=&get_requestor_ip();
6060: $$storehash{'host'}=$perlvar{'lonHostID'};
6061:
6062: my $namevalue='';
6063: foreach my $key (keys(%$storehash)) {
6064: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6065: }
6066: $namevalue=~s/\&$//;
6067: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
6068: return critical
6069: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
6070: }
6071:
6072: # --------------------------------------------------------------------- Restore
6073:
6074: sub restore {
6075: my ($symb,$namespace,$domain,$stuname) = @_;
6076: my $home='';
6077:
6078: if ($stuname) { $home=&homeserver($stuname,$domain); }
6079:
6080: if (!$symb) {
6081: return if ($namespace eq 'courserequests');
6082: unless ($symb=escape(&symbread())) { return ''; }
6083: } else {
6084: unless ($namespace eq 'courserequests') {
6085: $symb=&escape(&symbclean($symb));
6086: }
6087: }
6088: if (!$namespace) {
6089: unless ($namespace=$env{'request.course.id'}) {
6090: return '';
6091: }
6092: }
6093: if (!$domain) { $domain=$env{'user.domain'}; }
6094: if (!$stuname) { $stuname=$env{'user.name'}; }
6095: if (!$home) { $home=$env{'user.home'}; }
6096: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6097:
6098: my %returnhash=();
6099: foreach my $line (split(/\&/,$answer)) {
6100: my ($name,$value)=split(/\=/,$line);
6101: $returnhash{&unescape($name)}=&thaw_unescape($value);
6102: }
6103: my $version;
6104: for ($version=1;$version<=$returnhash{'version'};$version++) {
6105: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6106: $returnhash{$item}=$returnhash{$version.':'.$item};
6107: }
6108: }
6109: return %returnhash;
6110: }
6111:
6112: # ---------------------------------------------------------- Course Description
6113: #
6114: #
6115:
6116: sub coursedescription {
6117: my ($courseid,$args)=@_;
6118: $courseid=~s/^\///;
6119: $courseid=~s/\_/\//g;
6120: my ($cdomain,$cnum)=split(/\//,$courseid);
6121: my $chome=&homeserver($cnum,$cdomain);
6122: my $normalid=$cdomain.'_'.$cnum;
6123: # need to always cache even if we get errors otherwise we keep
6124: # trying and trying and trying to get the course description.
6125: my %envhash=();
6126: my %returnhash=();
6127:
6128: my $expiretime=600;
6129: if ($env{'request.course.id'} eq $normalid) {
6130: $expiretime=120;
6131: }
6132:
6133: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6134: if (!$args->{'freshen_cache'}
6135: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6136: foreach my $key (keys(%env)) {
6137: next if ($key !~ /^\Q$prefix\E(.*)/);
6138: my ($setting) = $1;
6139: $returnhash{$setting} = $env{$key};
6140: }
6141: return %returnhash;
6142: }
6143:
6144: # get the data again
6145:
6146: if (!$args->{'one_time'}) {
6147: $envhash{'course.'.$normalid.'.last_cache'}=time;
6148: }
6149:
6150: if ($chome ne 'no_host') {
6151: %returnhash=&dump('environment',$cdomain,$cnum);
6152: if (!exists($returnhash{'con_lost'})) {
6153: my $username = $env{'user.name'}; # Defult username
6154: if(defined $args->{'user'}) {
6155: $username = $args->{'user'};
6156: }
6157: $returnhash{'home'}= $chome;
6158: $returnhash{'domain'} = $cdomain;
6159: $returnhash{'num'} = $cnum;
6160: if (!defined($returnhash{'type'})) {
6161: $returnhash{'type'} = 'Course';
6162: }
6163: while (my ($name,$value) = each %returnhash) {
6164: $envhash{'course.'.$normalid.'.'.$name}=$value;
6165: }
6166: $returnhash{'url'}=&clutter($returnhash{'url'});
6167: $returnhash{'fn'}=LONCAPA::tempdir() .
6168: $username.'_'.$cdomain.'_'.$cnum;
6169: $envhash{'course.'.$normalid.'.home'}=$chome;
6170: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6171: $envhash{'course.'.$normalid.'.num'}=$cnum;
6172: }
6173: }
6174: if (!$args->{'one_time'}) {
6175: &appenv(\%envhash);
6176: }
6177: return %returnhash;
6178: }
6179:
6180: sub update_released_required {
6181: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6182: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6183: $cid = $env{'request.course.id'};
6184: $cdom = $env{'course.'.$cid.'.domain'};
6185: $cnum = $env{'course.'.$cid.'.num'};
6186: $chome = $env{'course.'.$cid.'.home'};
6187: }
6188: if ($needsrelease) {
6189: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6190: my $needsupdate;
6191: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6192: $needsupdate = 1;
6193: } else {
6194: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6195: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6196: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6197: $needsupdate = 1;
6198: }
6199: }
6200: if ($needsupdate) {
6201: my %needshash = (
6202: 'internal.releaserequired' => $needsrelease,
6203: );
6204: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6205: if ($putresult eq 'ok') {
6206: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6207: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6208: if (ref($crsinfo{$cid}) eq 'HASH') {
6209: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6210: &courseidput($cdom,\%crsinfo,$chome,'notime');
6211: }
6212: }
6213: }
6214: }
6215: return;
6216: }
6217:
6218: # -------------------------------------------------See if a user is privileged
6219:
6220: sub privileged {
6221: my ($username,$domain,$possdomains,$possroles)=@_;
6222: my $now = time;
6223: my $roles;
6224: if (ref($possroles) eq 'ARRAY') {
6225: $roles = $possroles;
6226: } else {
6227: $roles = ['dc','su'];
6228: }
6229: if (ref($possdomains) eq 'ARRAY') {
6230: my %privileged = &privileged_by_domain($possdomains,$roles);
6231: foreach my $dom (@{$possdomains}) {
6232: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6233: (ref($privileged{$dom}) eq 'HASH')) {
6234: foreach my $role (@{$roles}) {
6235: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6236: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6237: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6238: return 1 unless (($end && $end < $now) ||
6239: ($start && $start > $now));
6240: }
6241: }
6242: }
6243: }
6244: }
6245: } else {
6246: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6247: my $now = time;
6248:
6249: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
6250: my ($trole, $tend, $tstart) = split(/_/, $role);
6251: if (grep(/^\Q$trole\E$/,@{$roles})) {
6252: return 1 unless ($tend && $tend < $now)
6253: or ($tstart && $tstart > $now);
6254: }
6255: }
6256: }
6257: return 0;
6258: }
6259:
6260: sub privileged_by_domain {
6261: my ($domains,$roles) = @_;
6262: my %privileged = ();
6263: my $cachetime = 60*60*24;
6264: my $now = time;
6265: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6266: return %privileged;
6267: }
6268: foreach my $dom (@{$domains}) {
6269: next if (ref($privileged{$dom}) eq 'HASH');
6270: my $needroles;
6271: foreach my $role (@{$roles}) {
6272: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6273: if (defined($cached)) {
6274: if (ref($result) eq 'HASH') {
6275: $privileged{$dom}{$role} = $result;
6276: }
6277: } else {
6278: $needroles = 1;
6279: }
6280: }
6281: if ($needroles) {
6282: my %dompersonnel = &get_domain_roles($dom,$roles);
6283: $privileged{$dom} = {};
6284: foreach my $server (keys(%dompersonnel)) {
6285: if (ref($dompersonnel{$server}) eq 'HASH') {
6286: foreach my $item (keys(%{$dompersonnel{$server}})) {
6287: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6288: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6289: next if ($end && $end < $now);
6290: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6291: $dompersonnel{$server}{$item};
6292: }
6293: }
6294: }
6295: if (ref($privileged{$dom}) eq 'HASH') {
6296: foreach my $role (@{$roles}) {
6297: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6298: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6299: } else {
6300: my %hash = ();
6301: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6302: }
6303: }
6304: }
6305: }
6306: }
6307: return %privileged;
6308: }
6309:
6310: # -------------------------------------------------------- Get user privileges
6311:
6312: sub rolesinit {
6313: my ($domain, $username) = @_;
6314: my %userroles = ('user.login.time' => time);
6315: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6316:
6317: # firstaccess and timerinterval are related to timed maps/resources.
6318: # also, blocking can be triggered by an activating timer
6319: # it's saved in the user's %env.
6320: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6321: my %timerinterval = &dump('timerinterval', $domain, $username);
6322: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6323: %timerintchk, %timerintenv);
6324:
6325: foreach my $key (keys(%firstaccess)) {
6326: my ($cid, $rest) = split(/\0/, $key);
6327: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6328: }
6329:
6330: foreach my $key (keys(%timerinterval)) {
6331: my ($cid,$rest) = split(/\0/,$key);
6332: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6333: }
6334:
6335: my %allroles=();
6336: my %allgroups=();
6337:
6338: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
6339: my $role = $rolesdump{$area};
6340: $area =~ s/\_\w\w$//;
6341:
6342: my ($trole, $tend, $tstart, $group_privs);
6343:
6344: if ($role =~ /^cr/) {
6345: # Custom role, defined by a user
6346: # e.g., user.role.cr/msu/smith/mynewrole
6347: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6348: $trole = $1;
6349: ($tend, $tstart) = split('_', $2);
6350: } else {
6351: $trole = $role;
6352: }
6353: } elsif ($role =~ m|^gr/|) {
6354: # Role of member in a group, defined within a course/community
6355: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6356: ($trole, $tend, $tstart) = split(/_/, $role);
6357: next if $tstart eq '-1';
6358: ($trole, $group_privs) = split(/\//, $trole);
6359: $group_privs = &unescape($group_privs);
6360: } else {
6361: # Just a normal role, defined in roles.tab
6362: ($trole, $tend, $tstart) = split(/_/,$role);
6363: }
6364:
6365: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6366: $username);
6367: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6368:
6369: # role expired or not available yet?
6370: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6371: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6372:
6373: next if $area eq '' or $trole eq '';
6374:
6375: my $spec = "$trole.$area";
6376: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6377:
6378: if ($trole =~ /^cr\//) {
6379: # Custom role, defined by a user
6380: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6381: } elsif ($trole eq 'gr') {
6382: # Role of a member in a group, defined within a course/community
6383: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6384: next;
6385: } else {
6386: # Normal role, defined in roles.tab
6387: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6388: }
6389:
6390: my $cid = $tdomain.'_'.$trest;
6391: unless ($firstaccchk{$cid}) {
6392: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6393: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6394: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6395: $coursetimerstarts{$cid}{$item};
6396: }
6397: }
6398: $firstaccchk{$cid} = 1;
6399: }
6400: unless ($timerintchk{$cid}) {
6401: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6402: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6403: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6404: $coursetimerintervals{$cid}{$item};
6405: }
6406: }
6407: $timerintchk{$cid} = 1;
6408: }
6409: }
6410:
6411: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6412: \%allroles, \%allgroups);
6413: $env{'user.adv'} = $userroles{'user.adv'};
6414: $env{'user.rar'} = $userroles{'user.rar'};
6415:
6416: return (\%userroles,\%firstaccenv,\%timerintenv);
6417: }
6418:
6419: sub set_arearole {
6420: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6421: unless ($nolog) {
6422: # log the associated role with the area
6423: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6424: }
6425: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6426: }
6427:
6428: sub custom_roleprivs {
6429: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6430: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6431: my $homsvr = &homeserver($rauthor,$rdomain);
6432: if (&hostname($homsvr) ne '') {
6433: my ($rdummy,$roledef)=
6434: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6435: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6436: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6437: if (defined($syspriv)) {
6438: if ($trest =~ /^$match_community$/) {
6439: $syspriv =~ s/bre\&S//;
6440: }
6441: $$allroles{'cm./'}.=':'.$syspriv;
6442: $$allroles{$spec.'./'}.=':'.$syspriv;
6443: }
6444: if ($tdomain ne '') {
6445: if (defined($dompriv)) {
6446: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6447: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6448: }
6449: if (($trest ne '') && (defined($coursepriv))) {
6450: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6451: my $rolename = $1;
6452: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6453: }
6454: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6455: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6456: }
6457: }
6458: }
6459: }
6460: }
6461:
6462: sub course_adhocrole_privs {
6463: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6464: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6465: if ($overrides{"internal.adhocpriv.$rolename"}) {
6466: my (%currprivs,%storeprivs);
6467: foreach my $item (split(/:/,$coursepriv)) {
6468: my ($priv,$restrict) = split(/\&/,$item);
6469: $currprivs{$priv} = $restrict;
6470: }
6471: my (%possadd,%possremove,%full);
6472: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6473: my ($priv,$restrict)=split(/\&/,$item);
6474: $full{$priv} = $restrict;
6475: }
6476: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6477: next if ($item eq '');
6478: my ($rule,$rest) = split(/=/,$item);
6479: next unless (($rule eq 'off') || ($rule eq 'on'));
6480: foreach my $priv (split(/:/,$rest)) {
6481: if ($priv ne '') {
6482: if ($rule eq 'off') {
6483: $possremove{$priv} = 1;
6484: } else {
6485: $possadd{$priv} = 1;
6486: }
6487: }
6488: }
6489: }
6490: foreach my $priv (sort(keys(%full))) {
6491: if (exists($currprivs{$priv})) {
6492: unless (exists($possremove{$priv})) {
6493: $storeprivs{$priv} = $currprivs{$priv};
6494: }
6495: } elsif (exists($possadd{$priv})) {
6496: $storeprivs{$priv} = $full{$priv};
6497: }
6498: }
6499: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6500: }
6501: return $coursepriv;
6502: }
6503:
6504: sub group_roleprivs {
6505: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6506: my $access = 1;
6507: my $now = time;
6508: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6509: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6510: if ($access) {
6511: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6512: $$allgroups{$course}{$group} .=':'.$group_privs;
6513: }
6514: }
6515:
6516: sub standard_roleprivs {
6517: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6518: if (defined($pr{$trole.':s'})) {
6519: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6520: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6521: }
6522: if ($tdomain ne '') {
6523: if (defined($pr{$trole.':d'})) {
6524: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6525: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6526: }
6527: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6528: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6529: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6530: }
6531: }
6532: }
6533:
6534: sub set_userprivs {
6535: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6536: my $author=0;
6537: my $adv=0;
6538: my $rar=0;
6539: my %grouproles = ();
6540: if (keys(%{$allgroups}) > 0) {
6541: my @groupkeys;
6542: foreach my $role (keys(%{$allroles})) {
6543: push(@groupkeys,$role);
6544: }
6545: if (ref($groups_roles) eq 'HASH') {
6546: foreach my $key (keys(%{$groups_roles})) {
6547: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6548: push(@groupkeys,$key);
6549: }
6550: }
6551: }
6552: if (@groupkeys > 0) {
6553: foreach my $role (@groupkeys) {
6554: my ($trole,$area,$sec,$extendedarea);
6555: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6556: $trole = $1;
6557: $area = $2;
6558: $sec = $3;
6559: $extendedarea = $area.$sec;
6560: if (exists($$allgroups{$area})) {
6561: foreach my $group (keys(%{$$allgroups{$area}})) {
6562: my $spec = $trole.'.'.$extendedarea;
6563: $grouproles{$spec.'.'.$area.'/'.$group} =
6564: $$allgroups{$area}{$group};
6565: }
6566: }
6567: }
6568: }
6569: }
6570: }
6571: foreach my $group (keys(%grouproles)) {
6572: $$allroles{$group} = $grouproles{$group};
6573: }
6574: foreach my $role (keys(%{$allroles})) {
6575: my %thesepriv;
6576: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6577: foreach my $item (split(/:/,$$allroles{$role})) {
6578: if ($item ne '') {
6579: my ($privilege,$restrictions)=split(/&/,$item);
6580: if ($restrictions eq '') {
6581: $thesepriv{$privilege}='F';
6582: } elsif ($thesepriv{$privilege} ne 'F') {
6583: $thesepriv{$privilege}.=$restrictions;
6584: }
6585: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6586: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6587: }
6588: }
6589: my $thesestr='';
6590: foreach my $priv (sort(keys(%thesepriv))) {
6591: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6592: }
6593: $userroles->{'user.priv.'.$role} = $thesestr;
6594: }
6595: return ($author,$adv,$rar);
6596: }
6597:
6598: sub role_status {
6599: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6600: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6601: my ($one,$two) = split(m{\./},$rolekey,2);
6602: (undef,undef,$$role) = split(/\./,$one,3);
6603: unless (!defined($$role) || $$role eq '') {
6604: $$where = '/'.$two;
6605: $$trolecode=$$role.'.'.$$where;
6606: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6607: $$tstatus='is';
6608: if ($$tstart && $$tstart>$update) {
6609: $$tstatus='future';
6610: if ($$tstart<$now) {
6611: if ($$tstart && $$tstart>$refresh) {
6612: if (($$where ne '') && ($$role ne '')) {
6613: my (%allroles,%allgroups,$group_privs,
6614: %groups_roles,@rolecodes);
6615: my %userroles = (
6616: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6617: );
6618: @rolecodes = ('cm');
6619: my $spec=$$role.'.'.$$where;
6620: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6621: if ($$role =~ /^cr\//) {
6622: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6623: push(@rolecodes,'cr');
6624: } elsif ($$role eq 'gr') {
6625: push(@rolecodes,$$role);
6626: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6627: $env{'user.name'});
6628: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6629: (undef,my $group_privs) = split(/\//,$trole);
6630: $group_privs = &unescape($group_privs);
6631: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6632: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6633: &get_groups_roles($tdomain,$trest,
6634: \%course_roles,\@rolecodes,
6635: \%groups_roles);
6636: } else {
6637: push(@rolecodes,$$role);
6638: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6639: }
6640: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6641: \%groups_roles);
6642: &appenv(\%userroles,\@rolecodes);
6643: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6644: }
6645: }
6646: $$tstatus = 'is';
6647: }
6648: }
6649: if ($$tend) {
6650: if ($$tend<$update) {
6651: $$tstatus='expired';
6652: } elsif ($$tend<$now) {
6653: $$tstatus='will_not';
6654: }
6655: }
6656: }
6657: }
6658: }
6659:
6660: sub get_groups_roles {
6661: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6662: return unless((ref($cdom_courseroles) eq 'HASH') &&
6663: (ref($rolecodes) eq 'ARRAY') &&
6664: (ref($groups_roles) eq 'HASH'));
6665: if (keys(%{$cdom_courseroles}) > 0) {
6666: my ($cnum) = ($rest =~ /^($match_courseid)/);
6667: if ($cdom ne '' && $cnum ne '') {
6668: foreach my $key (keys(%{$cdom_courseroles})) {
6669: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6670: my $crsrole = $1;
6671: my $crssec = $2;
6672: if ($crsrole =~ /^cr/) {
6673: unless (grep(/^cr$/,@{$rolecodes})) {
6674: push(@{$rolecodes},'cr');
6675: }
6676: } else {
6677: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6678: push(@{$rolecodes},$crsrole);
6679: }
6680: }
6681: my $rolekey = "$crsrole./$cdom/$cnum";
6682: if ($crssec ne '') {
6683: $rolekey .= "/$crssec";
6684: }
6685: $rolekey .= './';
6686: $groups_roles->{$rolekey} = $rolecodes;
6687: }
6688: }
6689: }
6690: }
6691: return;
6692: }
6693:
6694: sub delete_env_groupprivs {
6695: my ($where,$courseroles,$possroles) = @_;
6696: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6697: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6698: unless (ref($courseroles->{$udom}) eq 'HASH') {
6699: %{$courseroles->{$udom}} =
6700: &get_my_roles('','','userroles',['active'],
6701: $possroles,[$udom],1);
6702: }
6703: if (ref($courseroles->{$udom}) eq 'HASH') {
6704: foreach my $item (keys(%{$courseroles->{$udom}})) {
6705: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6706: my $area = '/'.$cdom.'/'.$cnum;
6707: my $privkey = "user.priv.$crsrole.$area";
6708: if ($crssec ne '') {
6709: $privkey .= '/'.$crssec;
6710: }
6711: $privkey .= ".$area/$group";
6712: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6713: }
6714: }
6715: return;
6716: }
6717:
6718: sub check_adhoc_privs {
6719: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6720: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6721: if ($sec) {
6722: $cckey .= '/'.$sec;
6723: }
6724: my $setprivs;
6725: if ($env{$cckey}) {
6726: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6727: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6728: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6729: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6730: $setprivs = 1;
6731: }
6732: } else {
6733: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6734: $setprivs = 1;
6735: }
6736: return $setprivs;
6737: }
6738:
6739: sub set_adhoc_privileges {
6740: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6741: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6742: my $area = '/'.$dcdom.'/'.$pickedcourse;
6743: if ($sec ne '') {
6744: $area .= '/'.$sec;
6745: }
6746: my $spec = $role.'.'.$area;
6747: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6748: $env{'user.name'},1);
6749: my %rolehash = ();
6750: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6751: my $rolename = $1;
6752: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
6753: my %domdef = &get_domain_defaults($dcdom);
6754: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6755: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6756: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6757: }
6758: }
6759: } else {
6760: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6761: }
6762: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
6763: &appenv(\%userroles,[$role,'cm']);
6764: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6765: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6766: &appenv( {'request.role' => $spec,
6767: 'request.role.domain' => $dcdom,
6768: 'request.course.sec' => $sec,
6769: }
6770: );
6771: my $tadv=0;
6772: if (&allowed('adv') eq 'F') { $tadv=1; }
6773: &appenv({'request.role.adv' => $tadv});
6774: }
6775: }
6776:
6777: # --------------------------------------------------------------- get interface
6778:
6779: sub get {
6780: my ($namespace,$storearr,$udomain,$uname)=@_;
6781: my $items='';
6782: foreach my $item (@$storearr) {
6783: $items.=&escape($item).'&';
6784: }
6785: $items=~s/\&$//;
6786: if (!$udomain) { $udomain=$env{'user.domain'}; }
6787: if (!$uname) { $uname=$env{'user.name'}; }
6788: my $uhome=&homeserver($uname,$udomain);
6789:
6790: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
6791: my @pairs=split(/\&/,$rep);
6792: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6793: return @pairs;
6794: }
6795: my %returnhash=();
6796: my $i=0;
6797: foreach my $item (@$storearr) {
6798: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6799: $i++;
6800: }
6801: return %returnhash;
6802: }
6803:
6804: # --------------------------------------------------------------- del interface
6805:
6806: sub del {
6807: my ($namespace,$storearr,$udomain,$uname)=@_;
6808: my $items='';
6809: foreach my $item (@$storearr) {
6810: $items.=&escape($item).'&';
6811: }
6812:
6813: $items=~s/\&$//;
6814: if (!$udomain) { $udomain=$env{'user.domain'}; }
6815: if (!$uname) { $uname=$env{'user.name'}; }
6816: my $uhome=&homeserver($uname,$udomain);
6817: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
6818: }
6819:
6820: # -------------------------------------------------------------- dump interface
6821:
6822: sub unserialize {
6823: my ($rep, $escapedkeys) = @_;
6824:
6825: return {} if $rep =~ /^error/;
6826:
6827: my %returnhash=();
6828: foreach my $item (split(/\&/,$rep)) {
6829: my ($key, $value) = split(/=/, $item, 2);
6830: $key = unescape($key) unless $escapedkeys;
6831: next if $key =~ /^error: 2 /;
6832: $returnhash{$key} = &thaw_unescape($value);
6833: }
6834: return \%returnhash;
6835: }
6836:
6837: # see Lond::dump_with_regexp
6838: # if $escapedkeys hash keys won't get unescaped.
6839: sub dump {
6840: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
6841: if (!$udomain) { $udomain=$env{'user.domain'}; }
6842: if (!$uname) { $uname=$env{'user.name'}; }
6843: my $uhome=&homeserver($uname,$udomain);
6844:
6845: if ($regexp) {
6846: $regexp=&escape($regexp);
6847: } else {
6848: $regexp='.';
6849: }
6850: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6851: # user is hosted on this machine
6852: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
6853: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
6854: return %{&unserialize($reply, $escapedkeys)};
6855: }
6856: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
6857: my @pairs=split(/\&/,$rep);
6858: my %returnhash=();
6859: if (!($rep =~ /^error/ )) {
6860: foreach my $item (@pairs) {
6861: my ($key,$value)=split(/=/,$item,2);
6862: $key = &unescape($key) unless ($escapedkeys);
6863: next if ($key =~ /^error: 2 /);
6864: $returnhash{$key}=&thaw_unescape($value);
6865: }
6866: }
6867: return %returnhash;
6868: }
6869:
6870:
6871: # --------------------------------------------------------- dumpstore interface
6872:
6873: sub dumpstore {
6874: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
6875: # same as dump but keys must be escaped. They may contain colon separated
6876: # lists of values that may themself contain colons (e.g. symbs).
6877: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
6878: }
6879:
6880: # -------------------------------------------------------------- keys interface
6881:
6882: sub getkeys {
6883: my ($namespace,$udomain,$uname)=@_;
6884: if (!$udomain) { $udomain=$env{'user.domain'}; }
6885: if (!$uname) { $uname=$env{'user.name'}; }
6886: my $uhome=&homeserver($uname,$udomain);
6887: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6888: my @keyarray=();
6889: foreach my $key (split(/\&/,$rep)) {
6890: next if ($key =~ /^error: 2 /);
6891: push(@keyarray,&unescape($key));
6892: }
6893: return @keyarray;
6894: }
6895:
6896: # --------------------------------------------------------------- currentdump
6897: sub currentdump {
6898: my ($courseid,$sdom,$sname)=@_;
6899: $courseid = $env{'request.course.id'} if (! defined($courseid));
6900: $sdom = $env{'user.domain'} if (! defined($sdom));
6901: $sname = $env{'user.name'} if (! defined($sname));
6902: my $uhome = &homeserver($sname,$sdom);
6903: my $rep;
6904:
6905: if (grep { $_ eq $uhome } current_machine_ids()) {
6906: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6907: $courseid)));
6908: } else {
6909: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6910: }
6911:
6912: return if ($rep =~ /^(error:|no_such_host)/);
6913: #
6914: my %returnhash=();
6915: #
6916: if ($rep eq "unknown_cmd") {
6917: # an old lond will not know currentdump
6918: # Do a dump and make it look like a currentdump
6919: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
6920: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6921: my %hash = @tmp;
6922: @tmp=();
6923: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
6924: } else {
6925: my @pairs=split(/\&/,$rep);
6926: foreach my $pair (@pairs) {
6927: my ($key,$value)=split(/=/,$pair,2);
6928: my ($symb,$param) = split(/:/,$key);
6929: $returnhash{&unescape($symb)}->{&unescape($param)} =
6930: &thaw_unescape($value);
6931: }
6932: }
6933: return %returnhash;
6934: }
6935:
6936: sub convert_dump_to_currentdump{
6937: my %hash = %{shift()};
6938: my %returnhash;
6939: # Code ripped from lond, essentially. The only difference
6940: # here is the unescaping done by lonnet::dump(). Conceivably
6941: # we might run in to problems with parameter names =~ /^v\./
6942: while (my ($key,$value) = each(%hash)) {
6943: my ($v,$symb,$param) = split(/:/,$key);
6944: $symb = &unescape($symb);
6945: $param = &unescape($param);
6946: next if ($v eq 'version' || $symb eq 'keys');
6947: next if (exists($returnhash{$symb}) &&
6948: exists($returnhash{$symb}->{$param}) &&
6949: $returnhash{$symb}->{'v.'.$param} > $v);
6950: $returnhash{$symb}->{$param}=$value;
6951: $returnhash{$symb}->{'v.'.$param}=$v;
6952: }
6953: #
6954: # Remove all of the keys in the hashes which keep track of
6955: # the version of the parameter.
6956: while (my ($symb,$param_hash) = each(%returnhash)) {
6957: # use a foreach because we are going to delete from the hash.
6958: foreach my $key (keys(%$param_hash)) {
6959: delete($param_hash->{$key}) if ($key =~ /^v\./);
6960: }
6961: }
6962: return \%returnhash;
6963: }
6964:
6965: # ------------------------------------------------------ critical inc interface
6966:
6967: sub cinc {
6968: return &inc(@_,'critical');
6969: }
6970:
6971: # --------------------------------------------------------------- inc interface
6972:
6973: sub inc {
6974: my ($namespace,$store,$udomain,$uname,$critical) = @_;
6975: if (!$udomain) { $udomain=$env{'user.domain'}; }
6976: if (!$uname) { $uname=$env{'user.name'}; }
6977: my $uhome=&homeserver($uname,$udomain);
6978: my $items='';
6979: if (! ref($store)) {
6980: # got a single value, so use that instead
6981: $items = &escape($store).'=&';
6982: } elsif (ref($store) eq 'SCALAR') {
6983: $items = &escape($$store).'=&';
6984: } elsif (ref($store) eq 'ARRAY') {
6985: $items = join('=&',map {&escape($_);} @{$store});
6986: } elsif (ref($store) eq 'HASH') {
6987: while (my($key,$value) = each(%{$store})) {
6988: $items.= &escape($key).'='.&escape($value).'&';
6989: }
6990: }
6991: $items=~s/\&$//;
6992: if ($critical) {
6993: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6994: } else {
6995: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6996: }
6997: }
6998:
6999: # --------------------------------------------------------------- put interface
7000:
7001: sub put {
7002: my ($namespace,$storehash,$udomain,$uname)=@_;
7003: if (!$udomain) { $udomain=$env{'user.domain'}; }
7004: if (!$uname) { $uname=$env{'user.name'}; }
7005: my $uhome=&homeserver($uname,$udomain);
7006: my $items='';
7007: foreach my $item (keys(%$storehash)) {
7008: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7009: }
7010: $items=~s/\&$//;
7011: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7012: }
7013:
7014: # ------------------------------------------------------------ newput interface
7015:
7016: sub newput {
7017: my ($namespace,$storehash,$udomain,$uname)=@_;
7018: if (!$udomain) { $udomain=$env{'user.domain'}; }
7019: if (!$uname) { $uname=$env{'user.name'}; }
7020: my $uhome=&homeserver($uname,$udomain);
7021: my $items='';
7022: foreach my $key (keys(%$storehash)) {
7023: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7024: }
7025: $items=~s/\&$//;
7026: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
7027: }
7028:
7029: # --------------------------------------------------------- putstore interface
7030:
7031: sub putstore {
7032: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
7033: if (!$udomain) { $udomain=$env{'user.domain'}; }
7034: if (!$uname) { $uname=$env{'user.name'}; }
7035: my $uhome=&homeserver($uname,$udomain);
7036: my $items='';
7037: foreach my $key (keys(%$storehash)) {
7038: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7039: }
7040: $items=~s/\&$//;
7041: my $esc_symb=&escape($symb);
7042: my $esc_v=&escape($version);
7043: my $reply =
7044: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
7045: $uhome);
7046: if (($tolog) && ($reply eq 'ok')) {
7047: my $namevalue='';
7048: foreach my $key (keys(%{$storehash})) {
7049: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
7050: }
7051: my $ip = &get_requestor_ip();
7052: $namevalue .= 'ip='.&escape($ip).
7053: '&host='.&escape($perlvar{'lonHostID'}).
7054: '&version='.$esc_v.
7055: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
7056: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
7057: }
7058: if ($reply eq 'unknown_cmd') {
7059: # gfall back to way things use to be done
7060: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
7061: $uname);
7062: }
7063: return $reply;
7064: }
7065:
7066: sub old_putstore {
7067: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
7068: if (!$udomain) { $udomain=$env{'user.domain'}; }
7069: if (!$uname) { $uname=$env{'user.name'}; }
7070: my $uhome=&homeserver($uname,$udomain);
7071: my %newstorehash;
7072: foreach my $item (keys(%$storehash)) {
7073: my $key = $version.':'.&escape($symb).':'.$item;
7074: $newstorehash{$key} = $storehash->{$item};
7075: }
7076: my $items='';
7077: my %allitems = ();
7078: foreach my $item (keys(%newstorehash)) {
7079: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
7080: my $key = $1.':keys:'.$2;
7081: $allitems{$key} .= $3.':';
7082: }
7083: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
7084: }
7085: foreach my $item (keys(%allitems)) {
7086: $allitems{$item} =~ s/\:$//;
7087: $items.= $item.'='.$allitems{$item}.'&';
7088: }
7089: $items=~s/\&$//;
7090: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7091: }
7092:
7093: # ------------------------------------------------------ critical put interface
7094:
7095: sub cput {
7096: my ($namespace,$storehash,$udomain,$uname)=@_;
7097: if (!$udomain) { $udomain=$env{'user.domain'}; }
7098: if (!$uname) { $uname=$env{'user.name'}; }
7099: my $uhome=&homeserver($uname,$udomain);
7100: my $items='';
7101: foreach my $item (keys(%$storehash)) {
7102: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7103: }
7104: $items=~s/\&$//;
7105: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
7106: }
7107:
7108: # -------------------------------------------------------------- eget interface
7109:
7110: sub eget {
7111: my ($namespace,$storearr,$udomain,$uname)=@_;
7112: my $items='';
7113: foreach my $item (@$storearr) {
7114: $items.=&escape($item).'&';
7115: }
7116: $items=~s/\&$//;
7117: if (!$udomain) { $udomain=$env{'user.domain'}; }
7118: if (!$uname) { $uname=$env{'user.name'}; }
7119: my $uhome=&homeserver($uname,$udomain);
7120: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
7121: my @pairs=split(/\&/,$rep);
7122: my %returnhash=();
7123: my $i=0;
7124: foreach my $item (@$storearr) {
7125: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7126: $i++;
7127: }
7128: return %returnhash;
7129: }
7130:
7131: # ------------------------------------------------------------ tmpput interface
7132: sub tmpput {
7133: my ($storehash,$server,$context)=@_;
7134: my $items='';
7135: foreach my $item (keys(%$storehash)) {
7136: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7137: }
7138: $items=~s/\&$//;
7139: if (defined($context)) {
7140: $items .= ':'.&escape($context);
7141: }
7142: return &reply("tmpput:$items",$server);
7143: }
7144:
7145: # ------------------------------------------------------------ tmpget interface
7146: sub tmpget {
7147: my ($token,$server)=@_;
7148: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7149: my $rep=&reply("tmpget:$token",$server);
7150: my %returnhash;
7151: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7152: return %returnhash;
7153: }
7154: foreach my $item (split(/\&/,$rep)) {
7155: my ($key,$value)=split(/=/,$item);
7156: $returnhash{&unescape($key)}=&thaw_unescape($value);
7157: }
7158: return %returnhash;
7159: }
7160:
7161: # ------------------------------------------------------------ tmpdel interface
7162: sub tmpdel {
7163: my ($token,$server)=@_;
7164: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7165: return &reply("tmpdel:$token",$server);
7166: }
7167:
7168: # ------------------------------------------------------------ get_timebased_id
7169:
7170: sub get_timebased_id {
7171: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7172: $maxtries) = @_;
7173: my ($newid,$error,$dellock);
7174: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7175: return ('','ok','invalid call to get suffix');
7176: }
7177:
7178: # set defaults for any optional args for which values were not supplied
7179: if ($who eq '') {
7180: $who = $env{'user.name'}.':'.$env{'user.domain'};
7181: }
7182: if (!$locktries) {
7183: $locktries = 3;
7184: }
7185: if (!$maxtries) {
7186: $maxtries = 10;
7187: }
7188:
7189: if (($cdom eq '') || ($cnum eq '')) {
7190: if ($env{'request.course.id'}) {
7191: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7192: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7193: }
7194: if (($cdom eq '') || ($cnum eq '')) {
7195: return ('','ok','call to get suffix not in course context');
7196: }
7197: }
7198:
7199: # construct locking item
7200: my $lockhash = {
7201: $prefix."\0".'locked_'.$keyid => $who,
7202: };
7203: my $tries = 0;
7204:
7205: # attempt to get lock on nohist_$namespace file
7206: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7207: while (($gotlock ne 'ok') && $tries <$locktries) {
7208: $tries ++;
7209: sleep 1;
7210: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7211: }
7212:
7213: # attempt to get unique identifier, based on current timestamp
7214: if ($gotlock eq 'ok') {
7215: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7216: my $id = time;
7217: $newid = $id;
7218: if ($idtype eq 'addcode') {
7219: $newid .= &sixnum_code();
7220: }
7221: my $idtries = 0;
7222: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7223: if ($idtype eq 'concat') {
7224: $newid = $id.$idtries;
7225: } elsif ($idtype eq 'addcode') {
7226: $newid = $newid.&sixnum_code();
7227: } else {
7228: $newid ++;
7229: }
7230: $idtries ++;
7231: }
7232: if (!exists($inuse{$prefix."\0".$newid})) {
7233: my %new_item = (
7234: $prefix."\0".$newid => $who,
7235: );
7236: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7237: $cdom,$cnum);
7238: if ($putresult ne 'ok') {
7239: undef($newid);
7240: $error = 'error saving new item: '.$putresult;
7241: }
7242: } else {
7243: undef($newid);
7244: $error = ('error: no unique suffix available for the new item ');
7245: }
7246: # remove lock
7247: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7248: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7249: } else {
7250: $error = "error: could not obtain lockfile\n";
7251: $dellock = 'ok';
7252: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7253: $dellock = 'nolock';
7254: }
7255: }
7256: return ($newid,$dellock,$error);
7257: }
7258:
7259: sub sixnum_code {
7260: my $code;
7261: for (0..6) {
7262: $code .= int( rand(9) );
7263: }
7264: return $code;
7265: }
7266:
7267: # -------------------------------------------------- portfolio access checking
7268:
7269: sub portfolio_access {
7270: my ($requrl,$clientip) = @_;
7271: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
7272: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
7273: if ($result) {
7274: my %setters;
7275: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7276: my ($startblock,$endblock) =
7277: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7278: if ($startblock && $endblock) {
7279: return 'B';
7280: }
7281: } else {
7282: my ($startblock,$endblock) =
7283: &Apache::loncommon::blockcheck(\%setters,'port');
7284: if ($startblock && $endblock) {
7285: return 'B';
7286: }
7287: }
7288: }
7289: if ($result eq 'ok') {
7290: return 'F';
7291: } elsif ($result =~ /^[^:]+:guest_/) {
7292: return 'A';
7293: }
7294: return '';
7295: }
7296:
7297: sub get_portfolio_access {
7298: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
7299:
7300: if (!ref($access_hash)) {
7301: my $current_perms = &get_portfile_permissions($udom,$unum);
7302: my %access_controls = &get_access_controls($current_perms,$group,
7303: $file_name);
7304: $access_hash = $access_controls{$file_name};
7305: }
7306:
7307: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
7308: my $now = time;
7309: if (ref($access_hash) eq 'HASH') {
7310: foreach my $key (keys(%{$access_hash})) {
7311: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7312: if ($start > $now) {
7313: next;
7314: }
7315: if ($end && $end<$now) {
7316: next;
7317: }
7318: if ($scope eq 'public') {
7319: $public = $key;
7320: last;
7321: } elsif ($scope eq 'guest') {
7322: $guest = $key;
7323: } elsif ($scope eq 'domains') {
7324: push(@domains,$key);
7325: } elsif ($scope eq 'users') {
7326: push(@users,$key);
7327: } elsif ($scope eq 'course') {
7328: push(@courses,$key);
7329: } elsif ($scope eq 'group') {
7330: push(@groups,$key);
7331: } elsif ($scope eq 'ip') {
7332: push(@ips,$key);
7333: }
7334: }
7335: if ($public) {
7336: return 'ok';
7337: } elsif (@ips > 0) {
7338: my $allowed;
7339: foreach my $ipkey (@ips) {
7340: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7341: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7342: $allowed = 1;
7343: last;
7344: }
7345: }
7346: }
7347: if ($allowed) {
7348: return 'ok';
7349: }
7350: }
7351: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7352: if ($guest) {
7353: return $guest;
7354: }
7355: } else {
7356: if (@domains > 0) {
7357: foreach my $domkey (@domains) {
7358: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7359: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7360: return 'ok';
7361: }
7362: }
7363: }
7364: }
7365: if (@users > 0) {
7366: foreach my $userkey (@users) {
7367: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7368: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7369: if (ref($item) eq 'HASH') {
7370: if (($item->{'uname'} eq $env{'user.name'}) &&
7371: ($item->{'udom'} eq $env{'user.domain'})) {
7372: return 'ok';
7373: }
7374: }
7375: }
7376: }
7377: }
7378: }
7379: my %roleshash;
7380: my @courses_and_groups = @courses;
7381: push(@courses_and_groups,@groups);
7382: if (@courses_and_groups > 0) {
7383: my (%allgroups,%allroles);
7384: my ($start,$end,$role,$sec,$group);
7385: foreach my $envkey (%env) {
7386: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
7387: my $cid = $2.'_'.$3;
7388: if ($1 eq 'gr') {
7389: $group = $4;
7390: $allgroups{$cid}{$group} = $env{$envkey};
7391: } else {
7392: if ($4 eq '') {
7393: $sec = 'none';
7394: } else {
7395: $sec = $4;
7396: }
7397: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7398: }
7399: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7400: my $cid = $2.'_'.$3;
7401: if ($4 eq '') {
7402: $sec = 'none';
7403: } else {
7404: $sec = $4;
7405: }
7406: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7407: }
7408: }
7409: if (keys(%allroles) == 0) {
7410: return;
7411: }
7412: foreach my $key (@courses_and_groups) {
7413: my %content = %{$$access_hash{$key}};
7414: my $cnum = $content{'number'};
7415: my $cdom = $content{'domain'};
7416: my $cid = $cdom.'_'.$cnum;
7417: if (!exists($allroles{$cid})) {
7418: next;
7419: }
7420: foreach my $role_id (keys(%{$content{'roles'}})) {
7421: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7422: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7423: my @status = @{$content{'roles'}{$role_id}{'access'}};
7424: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7425: foreach my $role (keys(%{$allroles{$cid}})) {
7426: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7427: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7428: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7429: if (grep/^all$/,@sections) {
7430: return 'ok';
7431: } else {
7432: if (grep/^$sec$/,@sections) {
7433: return 'ok';
7434: }
7435: }
7436: }
7437: }
7438: if (keys(%{$allgroups{$cid}}) == 0) {
7439: if (grep/^none$/,@groups) {
7440: return 'ok';
7441: }
7442: } else {
7443: if (grep/^all$/,@groups) {
7444: return 'ok';
7445: }
7446: foreach my $group (keys(%{$allgroups{$cid}})) {
7447: if (grep/^$group$/,@groups) {
7448: return 'ok';
7449: }
7450: }
7451: }
7452: }
7453: }
7454: }
7455: }
7456: }
7457: if ($guest) {
7458: return $guest;
7459: }
7460: }
7461: }
7462: return;
7463: }
7464:
7465: sub course_group_datechecker {
7466: my ($dates,$now,$status) = @_;
7467: my ($start,$end) = split(/\./,$dates);
7468: if (!$start && !$end) {
7469: return 'ok';
7470: }
7471: if (grep/^active$/,@{$status}) {
7472: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7473: return 'ok';
7474: }
7475: }
7476: if (grep/^previous$/,@{$status}) {
7477: if ($end > $now ) {
7478: return 'ok';
7479: }
7480: }
7481: if (grep/^future$/,@{$status}) {
7482: if ($start > $now) {
7483: return 'ok';
7484: }
7485: }
7486: return;
7487: }
7488:
7489: sub parse_portfolio_url {
7490: my ($url) = @_;
7491:
7492: my ($type,$udom,$unum,$group,$file_name);
7493:
7494: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7495: $type = 1;
7496: $udom = $1;
7497: $unum = $2;
7498: $file_name = $3;
7499: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7500: $type = 2;
7501: $udom = $1;
7502: $unum = $2;
7503: $group = $3;
7504: $file_name = $3.'/'.$4;
7505: }
7506: if (wantarray) {
7507: return ($type,$udom,$unum,$file_name,$group);
7508: }
7509: return $type;
7510: }
7511:
7512: sub is_portfolio_url {
7513: my ($url) = @_;
7514: return scalar(&parse_portfolio_url($url));
7515: }
7516:
7517: sub is_portfolio_file {
7518: my ($file) = @_;
7519: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7520: return 1;
7521: }
7522: return;
7523: }
7524:
7525: sub usertools_access {
7526: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7527: my ($access,%tools);
7528: if ($context eq '') {
7529: $context = 'tools';
7530: }
7531: if ($context eq 'requestcourses') {
7532: %tools = (
7533: official => 1,
7534: unofficial => 1,
7535: community => 1,
7536: textbook => 1,
7537: );
7538: } elsif ($context eq 'requestauthor') {
7539: %tools = (
7540: requestauthor => 1,
7541: );
7542: } else {
7543: %tools = (
7544: aboutme => 1,
7545: blog => 1,
7546: webdav => 1,
7547: portfolio => 1,
7548: );
7549: }
7550: return if (!defined($tools{$tool}));
7551:
7552: if (($udom eq '') || ($uname eq '')) {
7553: $udom = $env{'user.domain'};
7554: $uname = $env{'user.name'};
7555: }
7556:
7557: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7558: if ($action ne 'reload') {
7559: if ($context eq 'requestcourses') {
7560: return $env{'environment.canrequest.'.$tool};
7561: } elsif ($context eq 'requestauthor') {
7562: return $env{'environment.canrequest.author'};
7563: } else {
7564: return $env{'environment.availabletools.'.$tool};
7565: }
7566: }
7567: }
7568:
7569: my ($toolstatus,$inststatus,$envkey);
7570: if ($context eq 'requestauthor') {
7571: $envkey = $context;
7572: } else {
7573: $envkey = $context.'.'.$tool;
7574: }
7575:
7576: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7577: ($action ne 'reload')) {
7578: $toolstatus = $env{'environment.'.$envkey};
7579: $inststatus = $env{'environment.inststatus'};
7580: } else {
7581: if (ref($userenvref) eq 'HASH') {
7582: $toolstatus = $userenvref->{$envkey};
7583: $inststatus = $userenvref->{'inststatus'};
7584: } else {
7585: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7586: $toolstatus = $userenv{$envkey};
7587: $inststatus = $userenv{'inststatus'};
7588: }
7589: }
7590:
7591: if ($toolstatus ne '') {
7592: if ($toolstatus) {
7593: $access = 1;
7594: } else {
7595: $access = 0;
7596: }
7597: return $access;
7598: }
7599:
7600: my ($is_adv,%domdef);
7601: if (ref($is_advref) eq 'HASH') {
7602: $is_adv = $is_advref->{'is_adv'};
7603: } else {
7604: $is_adv = &is_advanced_user($udom,$uname);
7605: }
7606: if (ref($domdefref) eq 'HASH') {
7607: %domdef = %{$domdefref};
7608: } else {
7609: %domdef = &get_domain_defaults($udom);
7610: }
7611: if (ref($domdef{$tool}) eq 'HASH') {
7612: if ($is_adv) {
7613: if ($domdef{$tool}{'_LC_adv'} ne '') {
7614: if ($domdef{$tool}{'_LC_adv'}) {
7615: $access = 1;
7616: } else {
7617: $access = 0;
7618: }
7619: return $access;
7620: }
7621: }
7622: if ($inststatus ne '') {
7623: my ($hasaccess,$hasnoaccess);
7624: foreach my $affiliation (split(/:/,$inststatus)) {
7625: if ($domdef{$tool}{$affiliation} ne '') {
7626: if ($domdef{$tool}{$affiliation}) {
7627: $hasaccess = 1;
7628: } else {
7629: $hasnoaccess = 1;
7630: }
7631: }
7632: }
7633: if ($hasaccess || $hasnoaccess) {
7634: if ($hasaccess) {
7635: $access = 1;
7636: } elsif ($hasnoaccess) {
7637: $access = 0;
7638: }
7639: return $access;
7640: }
7641: } else {
7642: if ($domdef{$tool}{'default'} ne '') {
7643: if ($domdef{$tool}{'default'}) {
7644: $access = 1;
7645: } elsif ($domdef{$tool}{'default'} == 0) {
7646: $access = 0;
7647: }
7648: return $access;
7649: }
7650: }
7651: } else {
7652: if (($context eq 'tools') && ($tool ne 'webdav')) {
7653: $access = 1;
7654: } else {
7655: $access = 0;
7656: }
7657: return $access;
7658: }
7659: }
7660:
7661: sub is_course_owner {
7662: my ($cdom,$cnum,$udom,$uname) = @_;
7663: if (($udom eq '') || ($uname eq '')) {
7664: $udom = $env{'user.domain'};
7665: $uname = $env{'user.name'};
7666: }
7667: unless (($udom eq '') || ($uname eq '')) {
7668: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7669: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7670: return 1;
7671: } else {
7672: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7673: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7674: return 1;
7675: }
7676: }
7677: }
7678: }
7679: return;
7680: }
7681:
7682: sub is_advanced_user {
7683: my ($udom,$uname) = @_;
7684: if ($udom ne '' && $uname ne '') {
7685: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7686: if (wantarray) {
7687: return ($env{'user.adv'},$env{'user.author'});
7688: } else {
7689: return $env{'user.adv'};
7690: }
7691: }
7692: }
7693: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7694: my %allroles;
7695: my ($is_adv,$is_author);
7696: foreach my $role (keys(%roleshash)) {
7697: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7698: my $area = '/'.$tdomain.'/'.$trest;
7699: if ($sec ne '') {
7700: $area .= '/'.$sec;
7701: }
7702: if (($area ne '') && ($trole ne '')) {
7703: my $spec=$trole.'.'.$area;
7704: if ($trole =~ /^cr\//) {
7705: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7706: } elsif ($trole ne 'gr') {
7707: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7708: }
7709: if ($trole eq 'au') {
7710: $is_author = 1;
7711: }
7712: }
7713: }
7714: foreach my $role (keys(%allroles)) {
7715: last if ($is_adv);
7716: foreach my $item (split(/:/,$allroles{$role})) {
7717: if ($item ne '') {
7718: my ($privilege,$restrictions)=split(/&/,$item);
7719: if ($privilege eq 'adv') {
7720: $is_adv = 1;
7721: last;
7722: }
7723: }
7724: }
7725: }
7726: if (wantarray) {
7727: return ($is_adv,$is_author);
7728: }
7729: return $is_adv;
7730: }
7731:
7732: sub check_can_request {
7733: my ($dom,$can_request,$request_domains) = @_;
7734: my $canreq = 0;
7735: my ($types,$typename) = &Apache::loncommon::course_types();
7736: my @options = ('approval','validate','autolimit');
7737: my $optregex = join('|',@options);
7738: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7739: foreach my $type (@{$types}) {
7740: if (&usertools_access($env{'user.name'},
7741: $env{'user.domain'},
7742: $type,undef,'requestcourses')) {
7743: $canreq ++;
7744: if (ref($request_domains) eq 'HASH') {
7745: push(@{$request_domains->{$type}},$env{'user.domain'});
7746: }
7747: if ($dom eq $env{'user.domain'}) {
7748: $can_request->{$type} = 1;
7749: }
7750: }
7751: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7752: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7753: if (@curr > 0) {
7754: foreach my $item (@curr) {
7755: if (ref($request_domains) eq 'HASH') {
7756: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7757: if ($otherdom ne '') {
7758: if (ref($request_domains->{$type}) eq 'ARRAY') {
7759: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7760: push(@{$request_domains->{$type}},$otherdom);
7761: }
7762: } else {
7763: push(@{$request_domains->{$type}},$otherdom);
7764: }
7765: }
7766: }
7767: }
7768: unless($dom eq $env{'user.domain'}) {
7769: $canreq ++;
7770: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7771: $can_request->{$type} = 1;
7772: }
7773: }
7774: }
7775: }
7776: }
7777: }
7778: return $canreq;
7779: }
7780:
7781: # ---------------------------------------------- Custom access rule evaluation
7782:
7783: sub customaccess {
7784: my ($priv,$uri)=@_;
7785: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
7786: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
7787: $udom = &LONCAPA::clean_domain($udom);
7788: $ucrs = &LONCAPA::clean_username($ucrs);
7789: my $access=0;
7790: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
7791: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7792: if ($type eq 'user') {
7793: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7794: my ($tdom,$tuname)=split(m{/},$scope);
7795: if ($tdom) {
7796: if ($tdom ne $env{'user.domain'}) { next; }
7797: }
7798: if ($tuname) {
7799: if ($tuname ne $env{'user.name'}) { next; }
7800: }
7801: $access=($effect eq 'allow');
7802: last;
7803: }
7804: } else {
7805: if ($role) {
7806: if ($role ne $urole) { next; }
7807: }
7808: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7809: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7810: if ($tdom) {
7811: if ($tdom ne $udom) { next; }
7812: }
7813: if ($tcrs) {
7814: if ($tcrs ne $ucrs) { next; }
7815: }
7816: if ($tsec) {
7817: if ($tsec ne $usec) { next; }
7818: }
7819: $access=($effect eq 'allow');
7820: last;
7821: }
7822: if ($realm eq '' && $role eq '') {
7823: $access=($effect eq 'allow');
7824: }
7825: }
7826: }
7827: return $access;
7828: }
7829:
7830: # ------------------------------------------------- Check for a user privilege
7831:
7832: sub allowed {
7833: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck,$ignorecache)=@_;
7834: my $ver_orguri=$uri;
7835: $uri=&deversion($uri);
7836: my $orguri=$uri;
7837: $uri=&declutter($uri);
7838:
7839: if ($priv eq 'evb') {
7840: # Evade communication block restrictions for specified role in a course
7841: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7842: return $1;
7843: } else {
7844: return;
7845: }
7846: }
7847:
7848: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
7849: # Free bre access to adm and meta resources
7850: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard|viewclasslist|aboutme)$}))
7851: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7852: && ($priv eq 'bre')) {
7853: return 'F';
7854: }
7855:
7856: # Free bre access to user's own portfolio contents
7857: my ($space,$domain,$name,@dir)=split('/',$uri);
7858: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
7859: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
7860: my %setters;
7861: my ($startblock,$endblock) =
7862: &Apache::loncommon::blockcheck(\%setters,'port');
7863: if ($startblock && $endblock) {
7864: return 'B';
7865: } else {
7866: return 'F';
7867: }
7868: }
7869:
7870: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
7871: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7872: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7873: if (exists($env{'request.course.id'})) {
7874: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7875: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7876: if (($domain eq $cdom) && ($name eq $cnum)) {
7877: my $courseprivid=$env{'request.course.id'};
7878: $courseprivid=~s/\_/\//;
7879: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7880: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7881: return $1;
7882: } else {
7883: if ($env{'request.course.sec'}) {
7884: $courseprivid.='/'.$env{'request.course.sec'};
7885: }
7886: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7887: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7888: return $2;
7889: }
7890: }
7891: }
7892: }
7893: }
7894:
7895: # Free bre to public access
7896:
7897: if ($priv eq 'bre') {
7898: my $copyright=&metadata($uri,'copyright');
7899: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
7900: return 'F';
7901: }
7902: if ($copyright eq 'priv') {
7903: $uri=~/([^\/]+)\/([^\/]+)\//;
7904: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
7905: return '';
7906: }
7907: }
7908: if ($copyright eq 'domain') {
7909: $uri=~/([^\/]+)\/([^\/]+)\//;
7910: unless (($env{'user.domain'} eq $1) ||
7911: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
7912: return '';
7913: }
7914: }
7915: if ($env{'request.role'}=~ /li\.\//) {
7916: # Library role, so allow browsing of resources in this domain.
7917: return 'F';
7918: }
7919: if ($copyright eq 'custom') {
7920: unless (&customaccess($priv,$uri)) { return ''; }
7921: }
7922: }
7923: # Domain coordinator is trying to create a course
7924: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
7925: # uri is the requested domain in this case.
7926: # comparison to 'request.role.domain' shows if the user has selected
7927: # a role of dc for the domain in question.
7928: return 'F' if ($uri eq $env{'request.role.domain'});
7929: }
7930:
7931: my $thisallowed='';
7932: my $statecond=0;
7933: my $courseprivid='';
7934:
7935: my $ownaccess;
7936: # Community Coordinator or Assistant Co-author browsing resource space.
7937: if (($priv eq 'bro') && ($env{'user.author'})) {
7938: if ($uri eq '') {
7939: $ownaccess = 1;
7940: } else {
7941: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7942: my $udom = $env{'user.domain'};
7943: my $uname = $env{'user.name'};
7944: if ($uri =~ m{^\Q$udom\E/?$}) {
7945: $ownaccess = 1;
7946: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
7947: unless ($uri =~ m{\.\./}) {
7948: $ownaccess = 1;
7949: }
7950: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7951: my $now = time;
7952: if ($uri =~ m{^([^/]+)/?$}) {
7953: my $adom = $1;
7954: foreach my $key (keys(%env)) {
7955: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
7956: my ($start,$end) = split('.',$env{$key});
7957: if (($now >= $start) && (!$end || $end < $now)) {
7958: $ownaccess = 1;
7959: last;
7960: }
7961: }
7962: }
7963: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7964: my $adom = $1;
7965: my $aname = $2;
7966: foreach my $role ('ca','aa') {
7967: if ($env{"user.role.$role./$adom/$aname"}) {
7968: my ($start,$end) =
7969: split('.',$env{"user.role.$role./$adom/$aname"});
7970: if (($now >= $start) && (!$end || $end < $now)) {
7971: $ownaccess = 1;
7972: last;
7973: }
7974: }
7975: }
7976: }
7977: }
7978: }
7979: }
7980: }
7981:
7982: # Course
7983:
7984: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
7985: unless (($priv eq 'bro') && (!$ownaccess)) {
7986: $thisallowed.=$1;
7987: }
7988: }
7989:
7990: # Domain
7991:
7992: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
7993: =~/\Q$priv\E\&([^\:]*)/) {
7994: unless (($priv eq 'bro') && (!$ownaccess)) {
7995: $thisallowed.=$1;
7996: }
7997: }
7998:
7999: # User who is not author or co-author might still be able to edit
8000: # resource of an author in the domain (e.g., if Domain Coordinator).
8001: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
8002: (&allowed('mdc',$env{'request.course.id'}))) {
8003: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
8004: $thisallowed.=$1;
8005: }
8006: }
8007:
8008: # Course: uri itself is a course
8009: my $courseuri=$uri;
8010: $courseuri=~s/\_(\d)/\/$1/;
8011: $courseuri=~s/^([^\/])/\/$1/;
8012:
8013: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
8014: =~/\Q$priv\E\&([^\:]*)/) {
8015: if ($priv eq 'mip') {
8016: my $rem = $1;
8017: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
8018: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
8019: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8020: if ($cdom ne '') {
8021: my %passwdconf = &get_passwdconf($cdom);
8022: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
8023: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
8024: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
8025: my @inststatuses = split(':',$env{'environment.inststatus'});
8026: unless (@inststatuses) {
8027: @inststatuses = ('default');
8028: }
8029: foreach my $status (@inststatuses) {
8030: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
8031: $thisallowed.=$rem;
8032: }
8033: }
8034: }
8035: }
8036: }
8037: }
8038: }
8039: } else {
8040: unless (($priv eq 'bro') && (!$ownaccess)) {
8041: $thisallowed.=$1;
8042: }
8043: }
8044: }
8045:
8046: # URI is an uploaded document for this course, default permissions don't matter
8047: # not allowing 'edit' access (editupload) to uploaded course docs
8048: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
8049: $thisallowed='';
8050: my ($match)=&is_on_map($uri);
8051: if ($match) {
8052: if ($env{'user.priv.'.$env{'request.role'}.'./'}
8053: =~/\Q$priv\E\&([^\:]*)/) {
8054: my $value = $1;
8055: if ($noblockcheck) {
8056: $thisallowed.=$value;
8057: } else {
8058: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8059: if (@blockers > 0) {
8060: $thisallowed = 'B';
8061: } else {
8062: $thisallowed.=$value;
8063: }
8064: }
8065: }
8066: } else {
8067: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
8068: if ($refuri) {
8069: if ($refuri =~ m|^/adm/|) {
8070: $thisallowed='F';
8071: } else {
8072: $refuri=&declutter($refuri);
8073: my ($match) = &is_on_map($refuri);
8074: if ($match) {
8075: if ($noblockcheck) {
8076: $thisallowed='F';
8077: } else {
8078: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8079: if (@blockers > 0) {
8080: $thisallowed = 'B';
8081: } else {
8082: $thisallowed='F';
8083: }
8084: }
8085: }
8086: }
8087: }
8088: }
8089: }
8090:
8091: if ($priv eq 'bre'
8092: && $thisallowed ne 'F'
8093: && $thisallowed ne '2'
8094: && &is_portfolio_url($uri)) {
8095: $thisallowed = &portfolio_access($uri,$clientip);
8096: }
8097:
8098: # Full access at system, domain or course-wide level? Exit.
8099: if ($thisallowed=~/F/) {
8100: return 'F';
8101: }
8102:
8103: # If this is generating or modifying users, exit with special codes
8104:
8105: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8106: if (($priv eq 'cca') || ($priv eq 'caa')) {
8107: my ($audom,$auname)=split('/',$uri);
8108: # no author name given, so this just checks on the general right to make a co-author in this domain
8109: unless ($auname) { return $thisallowed; }
8110: # an author name is given, so we are about to actually make a co-author for a certain account
8111: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8112: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8113: ($audom ne $env{'request.role.domain'}))) { return ''; }
8114: }
8115: return $thisallowed;
8116: }
8117: #
8118: # Gathered so far: system, domain and course wide privileges
8119: #
8120: # Course: See if uri or referer is an individual resource that is part of
8121: # the course
8122:
8123: if ($env{'request.course.id'}) {
8124:
8125: # If this is modifying password (internal auth) domains must match for user and user's role.
8126:
8127: if ($priv eq 'mip') {
8128: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8129: return $thisallowed;
8130: } else {
8131: return '';
8132: }
8133: }
8134:
8135: $courseprivid=$env{'request.course.id'};
8136: if ($env{'request.course.sec'}) {
8137: $courseprivid.='/'.$env{'request.course.sec'};
8138: }
8139: $courseprivid=~s/\_/\//;
8140: my $checkreferer=1;
8141: my ($match,$cond)=&is_on_map($uri);
8142: if ($match) {
8143: $statecond=$cond;
8144: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8145: =~/\Q$priv\E\&([^\:]*)/) {
8146: my $value = $1;
8147: if ($priv eq 'bre') {
8148: if ($noblockcheck) {
8149: $thisallowed.=$value;
8150: } else {
8151: my @blockers = &has_comm_blocking($priv,$symb,$uri,$ignorecache);
8152: if (@blockers > 0) {
8153: $thisallowed = 'B';
8154: } else {
8155: $thisallowed.=$value;
8156: }
8157: }
8158: } else {
8159: $thisallowed.=$value;
8160: }
8161: $checkreferer=0;
8162: }
8163: }
8164:
8165: if ($checkreferer) {
8166: my $refuri=$env{'httpref.'.$orguri};
8167: unless ($refuri) {
8168: foreach my $key (keys(%env)) {
8169: if ($key=~/^httpref\..*\*/) {
8170: my $pattern=$key;
8171: $pattern=~s/^httpref\.\/res\///;
8172: $pattern=~s/\*/\[\^\/\]\+/g;
8173: $pattern=~s/\//\\\//g;
8174: if ($orguri=~/$pattern/) {
8175: $refuri=$env{$key};
8176: }
8177: }
8178: }
8179: }
8180:
8181: if ($refuri) {
8182: $refuri=&declutter($refuri);
8183: my ($match,$cond)=&is_on_map($refuri);
8184: if ($match) {
8185: my $refstatecond=$cond;
8186: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8187: =~/\Q$priv\E\&([^\:]*)/) {
8188: my $value = $1;
8189: if ($priv eq 'bre') {
8190: if ($noblockcheck) {
8191: $thisallowed.=$value;
8192: } else {
8193: my @blockers = &has_comm_blocking($priv,'',$refuri,'',1);
8194: if (@blockers > 0) {
8195: $thisallowed = 'B';
8196: } else {
8197: $thisallowed.=$value;
8198: }
8199: }
8200: } else {
8201: $thisallowed.=$value;
8202: }
8203: $uri=$refuri;
8204: $statecond=$refstatecond;
8205: }
8206: }
8207: }
8208: }
8209: }
8210:
8211: #
8212: # Gathered now: all privileges that could apply, and condition number
8213: #
8214: #
8215: # Full or no access?
8216: #
8217:
8218: if ($thisallowed=~/F/) {
8219: return 'F';
8220: }
8221:
8222: unless ($thisallowed) {
8223: return '';
8224: }
8225:
8226: # Restrictions exist, deal with them
8227: #
8228: # C:according to course preferences
8229: # R:according to resource settings
8230: # L:unless locked
8231: # X:according to user session state
8232: #
8233:
8234: # Possibly locked functionality, check all courses
8235: # Locks might take effect only after 10 minutes cache expiration for other
8236: # courses, and 2 minutes for current course
8237:
8238: my $envkey;
8239: if ($thisallowed=~/L/) {
8240: foreach $envkey (keys(%env)) {
8241: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8242: my $courseid=$2;
8243: my $roleid=$1.'.'.$2;
8244: $courseid=~s/^\///;
8245: my $expiretime=600;
8246: if ($env{'request.role'} eq $roleid) {
8247: $expiretime=120;
8248: }
8249: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8250: my $prefix='course.'.$cdom.'_'.$cnum.'.';
8251: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
8252: &coursedescription($courseid,{'freshen_cache' => 1});
8253: }
8254: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8255: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8256: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8257: &log($env{'user.domain'},$env{'user.name'},
8258: $env{'user.home'},
8259: 'Locked by res: '.$priv.' for '.$uri.' due to '.
8260: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8261: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8262: return '';
8263: }
8264: }
8265: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8266: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8267: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8268: &log($env{'user.domain'},$env{'user.name'},
8269: $env{'user.home'},
8270: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
8271: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8272: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8273: return '';
8274: }
8275: }
8276: }
8277: }
8278: }
8279:
8280: #
8281: # Rest of the restrictions depend on selected course
8282: #
8283:
8284: unless ($env{'request.course.id'}) {
8285: if ($thisallowed eq 'A') {
8286: return 'A';
8287: } elsif ($thisallowed eq 'B') {
8288: return 'B';
8289: } else {
8290: return '1';
8291: }
8292: }
8293:
8294: #
8295: # Now user is definitely in a course
8296: #
8297:
8298:
8299: # Course preferences
8300:
8301: if ($thisallowed=~/C/) {
8302: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8303: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8304: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
8305: =~/\Q$rolecode\E/) {
8306: if (($priv ne 'pch') && ($priv ne 'plc')) {
8307: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8308: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8309: $env{'request.course.id'});
8310: }
8311: return '';
8312: }
8313:
8314: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
8315: =~/\Q$unamedom\E/) {
8316: if (($priv ne 'pch') && ($priv ne 'plc')) {
8317: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8318: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8319: $env{'request.course.id'});
8320: }
8321: return '';
8322: }
8323: }
8324:
8325: # Resource preferences
8326:
8327: if ($thisallowed=~/R/) {
8328: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8329: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
8330: if (($priv ne 'pch') && ($priv ne 'plc')) {
8331: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8332: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8333: }
8334: return '';
8335: }
8336: }
8337:
8338: # Restricted by state or randomout?
8339:
8340: if ($thisallowed=~/X/) {
8341: if ($env{'acc.randomout'}) {
8342: if (!$symb) { $symb=&symbread($uri,1); }
8343: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
8344: return '';
8345: }
8346: }
8347: if (&condval($statecond)) {
8348: return '2';
8349: } else {
8350: return '';
8351: }
8352: }
8353:
8354: if ($thisallowed eq 'A') {
8355: return 'A';
8356: } elsif ($thisallowed eq 'B') {
8357: return 'B';
8358: }
8359: return 'F';
8360: }
8361:
8362: # ------------------------------------------- Check construction space access
8363:
8364: sub constructaccess {
8365: my ($url,$setpriv)=@_;
8366:
8367: # We do not allow editing of previous versions of files
8368: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8369:
8370: # Get username and domain from URL
8371: my ($ownername,$ownerdomain,$ownerhome);
8372:
8373: ($ownerdomain,$ownername) =
8374: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
8375:
8376: # The URL does not really point to any authorspace, forget it
8377: unless (($ownername) && ($ownerdomain)) { return ''; }
8378:
8379: # Now we need to see if the user has access to the authorspace of
8380: # $ownername at $ownerdomain
8381:
8382: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8383: # Real author for this?
8384: $ownerhome = $env{'user.home'};
8385: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8386: return ($ownername,$ownerdomain,$ownerhome);
8387: }
8388: } else {
8389: # Co-author for this?
8390: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8391: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8392: $ownerhome = &homeserver($ownername,$ownerdomain);
8393: return ($ownername,$ownerdomain,$ownerhome);
8394: }
8395: }
8396:
8397: # We don't have any access right now. If we are not possibly going to do anything about this,
8398: # we might as well leave
8399: unless ($setpriv) { return ''; }
8400:
8401: # Backdoor access?
8402: my $allowed=&allowed('eco',$ownerdomain);
8403: # Nope
8404: unless ($allowed) { return ''; }
8405: # Looks like we may have access, but could be locked by the owner of the construction space
8406: if ($allowed eq 'U') {
8407: my %blocked=&get('environment',['domcoord.author'],
8408: $ownerdomain,$ownername);
8409: # Is blocked by owner
8410: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8411: }
8412: if (($allowed eq 'F') || ($allowed eq 'U')) {
8413: # Grant temporary access
8414: my $then=$env{'user.login.time'};
8415: my $update=$env{'user.update.time'};
8416: if (!$update) { $update = $then; }
8417: my $refresh=$env{'user.refresh.time'};
8418: if (!$refresh) { $refresh = $update; }
8419: my $now = time;
8420: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8421: $now,'ca','constructaccess');
8422: $ownerhome = &homeserver($ownername,$ownerdomain);
8423: return($ownername,$ownerdomain,$ownerhome);
8424: }
8425: # No business here
8426: return '';
8427: }
8428:
8429: # ----------------------------------------------------------- Content Blocking
8430:
8431: {
8432: # Caches for faster Course Contents display where content blocking
8433: # is in operation (i.e., interval param set) for timed quiz.
8434: #
8435: # User for whom data are being temporarily cached.
8436: my $cacheduser='';
8437: # Course for which data are being temporarily cached.
8438: my $cachedcid='';
8439: # Cached blockers for this user (a hash of blocking items).
8440: my %cachedblockers=();
8441: # When the data were last cached.
8442: my $cachedlast='';
8443:
8444: sub load_all_blockers {
8445: my ($uname,$udom)=@_;
8446: if (($uname ne '') && ($udom ne '')) {
8447: if (($cacheduser eq $uname.':'.$udom) &&
8448: ($cachedcid eq $env{'request.course.id'}) &&
8449: (abs($cachedlast-time)<5)) {
8450: return;
8451: }
8452: }
8453: $cachedlast=time;
8454: $cacheduser=$uname.':'.$udom;
8455: $cachedcid=$env{'request.course.id'};
8456: %cachedblockers = &get_commblock_resources();
8457: return;
8458: }
8459:
8460: sub get_comm_blocks {
8461: my ($cdom,$cnum) = @_;
8462: if ($cdom eq '' || $cnum eq '') {
8463: return unless ($env{'request.course.id'});
8464: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8465: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8466: }
8467: my %commblocks;
8468: my $hashid=$cdom.'_'.$cnum;
8469: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8470: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8471: %commblocks = %{$blocksref};
8472: } else {
8473: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8474: my $cachetime = 600;
8475: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8476: }
8477: return %commblocks;
8478: }
8479:
8480: sub get_commblock_resources {
8481: my ($blocks) = @_;
8482: my %blockers = ();
8483: return %blockers unless ($env{'request.course.id'});
8484: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8485: my %commblocks;
8486: if (ref($blocks) eq 'HASH') {
8487: %commblocks = %{$blocks};
8488: } else {
8489: %commblocks = &get_comm_blocks();
8490: }
8491: return %blockers unless (keys(%commblocks) > 0);
8492: my $navmap = Apache::lonnavmaps::navmap->new();
8493: return %blockers unless (ref($navmap));
8494: my $now = time;
8495: foreach my $block (keys(%commblocks)) {
8496: if ($block =~ /^(\d+)____(\d+)$/) {
8497: my ($start,$end) = ($1,$2);
8498: if ($start <= $now && $end >= $now) {
8499: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8500: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8501: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8502: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8503: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8504: }
8505: }
8506: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8507: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8508: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8509: }
8510: }
8511: }
8512: }
8513: }
8514: } elsif ($block =~ /^firstaccess____(.+)$/) {
8515: my $item = $1;
8516: my @to_test;
8517: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8518: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8519: my @interval;
8520: my $type = 'map';
8521: if ($item eq 'course') {
8522: $type = 'course';
8523: @interval=&EXT("resource.0.interval");
8524: } else {
8525: if ($item =~ /___\d+___/) {
8526: $type = 'resource';
8527: @interval=&EXT("resource.0.interval",$item);
8528: if (ref($navmap)) {
8529: my $res = $navmap->getBySymb($item);
8530: push(@to_test,$res);
8531: }
8532: } else {
8533: my $mapsymb = &symbread($item,1);
8534: if ($mapsymb) {
8535: if (ref($navmap)) {
8536: my $mapres = $navmap->getBySymb($mapsymb);
8537: if (ref($mapres)) {
8538: my $first = $mapres->map_start();
8539: my $finish = $mapres->map_finish();
8540: my $it = $navmap->getIterator($first,$finish,undef,0,0);
8541: if (ref($it)) {
8542: my $res;
8543: while ($res = $it->next(undef,1)) {
8544: next unless (ref($res));
8545: my $symb = $res->symb();
8546: next if (($symb eq $mapsymb) || ($symb eq ''));
8547: @interval=&EXT("resource.0.interval",$symb);
8548: if ($interval[1] eq 'map') {
8549: if ($res->answerable()) {
8550: push(@to_test,$res);
8551: last;
8552: }
8553: }
8554: }
8555: }
8556: }
8557: }
8558: }
8559: }
8560: }
8561: if ($interval[0] =~ /^(\d+)/) {
8562: my $timelimit = $1;
8563: my $first_access;
8564: if ($type eq 'resource') {
8565: $first_access=&get_first_access($interval[1],$item);
8566: } elsif ($type eq 'map') {
8567: $first_access=&get_first_access($interval[1],undef,$item);
8568: } else {
8569: $first_access=&get_first_access($interval[1]);
8570: }
8571: if ($first_access) {
8572: my $timesup = $first_access+$timelimit;
8573: if ($timesup > $now) {
8574: my $activeblock;
8575: foreach my $res (@to_test) {
8576: if ($res->answerable()) {
8577: $activeblock = 1;
8578: last;
8579: }
8580: }
8581: if ($activeblock) {
8582: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8583: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8584: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8585: }
8586: }
8587: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8588: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8589: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8590: }
8591: }
8592: }
8593: }
8594: }
8595: }
8596: }
8597: }
8598: }
8599: }
8600: return %blockers;
8601: }
8602:
8603: sub has_comm_blocking {
8604: my ($priv,$symb,$uri,$ignoresymbdb,$noenccheck,$blocked,$blocks) = @_;
8605: my @blockers;
8606: return unless ($env{'request.course.id'});
8607: return unless ($priv eq 'bre');
8608: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8609: return if ($env{'request.state'} eq 'construct');
8610: my %blockinfo;
8611: if (ref($blocks) eq 'HASH') {
8612: %blockinfo = &get_commblock_resources($blocks);
8613: } else {
8614: &load_all_blockers($env{'user.name'},$env{'user.domain'});
8615: %blockinfo = %cachedblockers;
8616: }
8617: return unless (keys(%blockinfo) > 0);
8618: my (%possibles,@symbs);
8619: if (!$symb) {
8620: $symb = &symbread($uri,1,1,1,\%possibles,$ignoresymbdb,$noenccheck);
8621: }
8622: if ($symb) {
8623: @symbs = ($symb);
8624: } elsif (keys(%possibles)) {
8625: @symbs = keys(%possibles);
8626: }
8627: my $noblock;
8628: foreach my $symb (@symbs) {
8629: last if ($noblock);
8630: my ($map,$resid,$resurl)=&decode_symb($symb);
8631: foreach my $block (keys(%blockinfo)) {
8632: if ($block =~ /^firstaccess____(.+)$/) {
8633: my $item = $1;
8634: unless ($blocked) {
8635: if (($item eq $map) || ($item eq $symb)) {
8636: $noblock = 1;
8637: last;
8638: }
8639: }
8640: }
8641: if (ref($blockinfo{$block}) eq 'HASH') {
8642: if (ref($blockinfo{$block}{'resources'}) eq 'HASH') {
8643: if ($blockinfo{$block}{'resources'}{$symb}) {
8644: unless (grep(/^\Q$block\E$/,@blockers)) {
8645: push(@blockers,$block);
8646: }
8647: }
8648: }
8649: if (ref($blockinfo{$block}{'maps'}) eq 'HASH') {
8650: if ($blockinfo{$block}{'maps'}{$map}) {
8651: unless (grep(/^\Q$block\E$/,@blockers)) {
8652: push(@blockers,$block);
8653: }
8654: }
8655: }
8656: }
8657: }
8658: }
8659: unless ($noblock) {
8660: return @blockers;
8661: }
8662: return;
8663: }
8664: }
8665:
8666: # -------------------------------- Deversion and split uri into path an filename
8667:
8668: #
8669: # Removes the version from a URI and
8670: # splits it in to its filename and path to the filename.
8671: # Seems like File::Basename could have done this more clearly.
8672: # Parameters:
8673: # $uri - input URI
8674: # Returns:
8675: # Two element list consisting of
8676: # $pathname - the URI up to and excluding the trailing /
8677: # $filename - The part of the URI following the last /
8678: # NOTE:
8679: # Another realization of this is simply:
8680: # use File::Basename;
8681: # ...
8682: # $uri = shift;
8683: # $filename = basename($uri);
8684: # $path = dirname($uri);
8685: # return ($filename, $path);
8686: #
8687: # The implementation below is probably faster however.
8688: #
8689: sub split_uri_for_cond {
8690: my $uri=&deversion(&declutter(shift));
8691: my @uriparts=split(/\//,$uri);
8692: my $filename=pop(@uriparts);
8693: my $pathname=join('/',@uriparts);
8694: return ($pathname,$filename);
8695: }
8696: # --------------------------------------------------- Is a resource on the map?
8697:
8698: sub is_on_map {
8699: my ($pathname,$filename) = &split_uri_for_cond(shift);
8700: #Trying to find the conditional for the file
8701: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
8702: /\&\Q$filename\E\:([\d\|]+)\&/);
8703: if ($match) {
8704: return (1,$1);
8705: } else {
8706: return (0,0);
8707: }
8708: }
8709:
8710: # --------------------------------------------------------- Get symb from alias
8711:
8712: sub get_symb_from_alias {
8713: my $symb=shift;
8714: my ($map,$resid,$url)=&decode_symb($symb);
8715: # Already is a symb
8716: if ($url) { return $symb; }
8717: # Must be an alias
8718: my $aliassymb='';
8719: my %bighash;
8720: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8721: &GDBM_READER(),0640)) {
8722: my $rid=$bighash{'mapalias_'.$symb};
8723: if ($rid) {
8724: my ($mapid,$resid)=split(/\./,$rid);
8725: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8726: $resid,$bighash{'src_'.$rid});
8727: }
8728: untie %bighash;
8729: }
8730: return $aliassymb;
8731: }
8732:
8733: # ----------------------------------------------------------------- Define Role
8734:
8735: sub definerole {
8736: if (allowed('mcr','/')) {
8737: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
8738: foreach my $role (split(':',$sysrole)) {
8739: my ($crole,$cqual)=split(/\&/,$role);
8740: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8741: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8742: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8743: return "refused:s:$crole&$cqual";
8744: }
8745: }
8746: }
8747: foreach my $role (split(':',$domrole)) {
8748: my ($crole,$cqual)=split(/\&/,$role);
8749: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8750: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8751: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
8752: return "refused:d:$crole&$cqual";
8753: }
8754: }
8755: }
8756: foreach my $role (split(':',$courole)) {
8757: my ($crole,$cqual)=split(/\&/,$role);
8758: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8759: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8760: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8761: return "refused:c:$crole&$cqual";
8762: }
8763: }
8764: }
8765: my $uhome;
8766: if (($uname ne '') && ($udom ne '')) {
8767: $uhome = &homeserver($uname,$udom);
8768: return $uhome if ($uhome eq 'no_host');
8769: } else {
8770: $uname = $env{'user.name'};
8771: $udom = $env{'user.domain'};
8772: $uhome = $env{'user.home'};
8773: }
8774: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8775: "$udom:$uname:rolesdef_$rolename=".
8776: escape($sysrole.'_'.$domrole.'_'.$courole);
8777: return reply($command,$uhome);
8778: } else {
8779: return 'refused';
8780: }
8781: }
8782:
8783: # ---------------- Make a metadata query against the network of library servers
8784:
8785: sub metadata_query {
8786: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
8787: my %rhash;
8788: my %libserv = &all_library();
8789: my @server_list = (defined($server_array) ? @$server_array
8790: : keys(%libserv) );
8791: for my $server (@server_list) {
8792: my $domains = '';
8793: if (ref($domains_hash) eq 'HASH') {
8794: $domains = $domains_hash->{$server};
8795: }
8796: unless ($custom or $customshow) {
8797: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
8798: $rhash{$server}=$reply;
8799: }
8800: else {
8801: my $reply=&reply("querysend:".&escape($query).':'.
8802: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
8803: $server);
8804: $rhash{$server}=$reply;
8805: }
8806: }
8807: return \%rhash;
8808: }
8809:
8810: # ----------------------------------------- Send log queries and wait for reply
8811:
8812: sub log_query {
8813: my ($uname,$udom,$query,%filters)=@_;
8814: my $uhome=&homeserver($uname,$udom);
8815: if ($uhome eq 'no_host') { return 'error: no_host'; }
8816: my $uhost=&hostname($uhome);
8817: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
8818: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8819: $uhome);
8820: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
8821: return get_query_reply($queryid);
8822: }
8823:
8824: # -------------------------- Update MySQL table for portfolio file
8825:
8826: sub update_portfolio_table {
8827: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
8828: if ($group ne '') {
8829: $file_name =~s /^\Q$group\E//;
8830: }
8831: my $homeserver = &homeserver($uname,$udom);
8832: my $queryid=
8833: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8834: ':'.&escape($file_name).':'.$action,$homeserver);
8835: my $reply = &get_query_reply($queryid);
8836: return $reply;
8837: }
8838:
8839: # -------------------------- Update MySQL allusers table
8840:
8841: sub update_allusers_table {
8842: my ($uname,$udom,$names) = @_;
8843: my $homeserver = &homeserver($uname,$udom);
8844: my $queryid=
8845: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8846: 'lastname='.&escape($names->{'lastname'}).'%%'.
8847: 'firstname='.&escape($names->{'firstname'}).'%%'.
8848: 'middlename='.&escape($names->{'middlename'}).'%%'.
8849: 'generation='.&escape($names->{'generation'}).'%%'.
8850: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8851: 'id='.&escape($names->{'id'}),$homeserver);
8852: return;
8853: }
8854:
8855: # ------- Request retrieval of institutional classlists for course(s)
8856:
8857: sub fetch_enrollment_query {
8858: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
8859: my ($homeserver,$sleep,$loopmax);
8860: my $maxtries = 1;
8861: if ($context eq 'automated') {
8862: $homeserver = $perlvar{'lonHostID'};
8863: $sleep = 2;
8864: $loopmax = 100;
8865: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
8866: } else {
8867: $homeserver = &homeserver($cnum,$dom);
8868: }
8869: my $host=&hostname($homeserver);
8870: my $cmd = '';
8871: foreach my $affiliate (keys(%{$affiliatesref})) {
8872: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8873: }
8874: $cmd =~ s/%%$//;
8875: $cmd = &escape($cmd);
8876: my $query = 'fetchenrollment';
8877: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
8878: unless ($queryid=~/^\Q$host\E\_/) {
8879: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8880: return 'error: '.$queryid;
8881: }
8882: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
8883: my $tries = 1;
8884: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8885: $reply = &get_query_reply($queryid,$sleep,$loopmax);
8886: $tries ++;
8887: }
8888: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8889: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8890: } else {
8891: my @responses = split(/:/,$reply);
8892: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
8893: foreach my $line (@responses) {
8894: my ($key,$value) = split(/=/,$line,2);
8895: $$replyref{$key} = $value;
8896: }
8897: } else {
8898: my $pathname = LONCAPA::tempdir();
8899: foreach my $line (@responses) {
8900: my ($key,$value) = split(/=/,$line);
8901: $$replyref{$key} = $value;
8902: if ($value > 0) {
8903: foreach my $item (@{$$affiliatesref{$key}}) {
8904: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
8905: my $destname = $pathname.'/'.$filename;
8906: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
8907: if ($xml_classlist =~ /^error/) {
8908: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8909: } else {
8910: if ( open(FILE,">",$destname) ) {
8911: print FILE &unescape($xml_classlist);
8912: close(FILE);
8913: } else {
8914: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
8915: }
8916: }
8917: }
8918: }
8919: }
8920: }
8921: return 'ok';
8922: }
8923: return 'error';
8924: }
8925:
8926: sub get_query_reply {
8927: my ($queryid,$sleep,$loopmax) = @_;
8928: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8929: $sleep = 0.2;
8930: }
8931: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8932: $loopmax = 100;
8933: }
8934: my $replyfile=LONCAPA::tempdir().$queryid;
8935: my $reply='';
8936: for (1..$loopmax) {
8937: sleep($sleep);
8938: if (-e $replyfile.'.end') {
8939: if (open(my $fh,"<",$replyfile)) {
8940: $reply = join('',<$fh>);
8941: close($fh);
8942: } else { return 'error: reply_file_error'; }
8943: return &unescape($reply);
8944: }
8945: }
8946: return 'timeout:'.$queryid;
8947: }
8948:
8949: sub courselog_query {
8950: #
8951: # possible filters:
8952: # url: url or symb
8953: # username
8954: # domain
8955: # action: view, submit, grade
8956: # start: timestamp
8957: # end: timestamp
8958: #
8959: my (%filters)=@_;
8960: unless ($env{'request.course.id'}) { return 'no_course'; }
8961: if ($filters{'url'}) {
8962: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8963: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8964: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8965: }
8966: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8967: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8968: return &log_query($cname,$cdom,'courselog',%filters);
8969: }
8970:
8971: sub userlog_query {
8972: #
8973: # possible filters:
8974: # action: log check role
8975: # start: timestamp
8976: # end: timestamp
8977: #
8978: my ($uname,$udom,%filters)=@_;
8979: return &log_query($uname,$udom,'userlog',%filters);
8980: }
8981:
8982: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8983:
8984: sub auto_run {
8985: my ($cnum,$cdom) = @_;
8986: my $response = 0;
8987: my $settings;
8988: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8989: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8990: $settings = $domconfig{'autoenroll'};
8991: if ($settings->{'run'} eq '1') {
8992: $response = 1;
8993: }
8994: } else {
8995: my $homeserver;
8996: if (&is_course($cdom,$cnum)) {
8997: $homeserver = &homeserver($cnum,$cdom);
8998: } else {
8999: $homeserver = &domain($cdom,'primary');
9000: }
9001: if ($homeserver ne 'no_host') {
9002: $response = &reply('autorun:'.$cdom,$homeserver);
9003: }
9004: }
9005: return $response;
9006: }
9007:
9008: sub auto_get_sections {
9009: my ($cnum,$cdom,$inst_coursecode) = @_;
9010: my $homeserver;
9011: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9012: $homeserver = &homeserver($cnum,$cdom);
9013: }
9014: if (!defined($homeserver)) {
9015: if ($cdom =~ /^$match_domain$/) {
9016: $homeserver = &domain($cdom,'primary');
9017: }
9018: }
9019: my @secs;
9020: if (defined($homeserver)) {
9021: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
9022: unless ($response eq 'refused') {
9023: @secs = split(/:/,$response);
9024: }
9025: }
9026: return @secs;
9027: }
9028:
9029: sub auto_new_course {
9030: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
9031: my $homeserver = &homeserver($cnum,$cdom);
9032: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
9033: return $response;
9034: }
9035:
9036: sub auto_validate_courseID {
9037: my ($cnum,$cdom,$inst_course_id) = @_;
9038: my $homeserver = &homeserver($cnum,$cdom);
9039: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
9040: return $response;
9041: }
9042:
9043: sub auto_validate_instcode {
9044: my ($cnum,$cdom,$instcode,$owner) = @_;
9045: my ($homeserver,$response);
9046: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9047: $homeserver = &homeserver($cnum,$cdom);
9048: }
9049: if (!defined($homeserver)) {
9050: if ($cdom =~ /^$match_domain$/) {
9051: $homeserver = &domain($cdom,'primary');
9052: }
9053: }
9054: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
9055: &escape($instcode).':'.&escape($owner),$homeserver));
9056: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
9057: return ($outcome,$description,$defaultcredits);
9058: }
9059:
9060: sub auto_create_password {
9061: my ($cnum,$cdom,$authparam,$udom) = @_;
9062: my ($homeserver,$response);
9063: my $create_passwd = 0;
9064: my $authchk = '';
9065: if ($udom =~ /^$match_domain$/) {
9066: $homeserver = &domain($udom,'primary');
9067: }
9068: if ($homeserver eq '') {
9069: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
9070: $homeserver = &homeserver($cnum,$cdom);
9071: }
9072: }
9073: if ($homeserver eq '') {
9074: $authchk = 'nodomain';
9075: } else {
9076: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
9077: if ($response eq 'refused') {
9078: $authchk = 'refused';
9079: } else {
9080: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
9081: }
9082: }
9083: return ($authparam,$create_passwd,$authchk);
9084: }
9085:
9086: sub auto_photo_permission {
9087: my ($cnum,$cdom,$students) = @_;
9088: my $homeserver = &homeserver($cnum,$cdom);
9089: my ($outcome,$perm_reqd,$conditions) =
9090: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
9091: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9092: return (undef,undef);
9093: }
9094: return ($outcome,$perm_reqd,$conditions);
9095: }
9096:
9097: sub auto_checkphotos {
9098: my ($uname,$udom,$pid) = @_;
9099: my $homeserver = &homeserver($uname,$udom);
9100: my ($result,$resulttype);
9101: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
9102: &escape($uname).':'.&escape($pid),
9103: $homeserver));
9104: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9105: return (undef,undef);
9106: }
9107: if ($outcome) {
9108: ($result,$resulttype) = split(/:/,$outcome);
9109: }
9110: return ($result,$resulttype);
9111: }
9112:
9113: sub auto_photochoice {
9114: my ($cnum,$cdom) = @_;
9115: my $homeserver = &homeserver($cnum,$cdom);
9116: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
9117: &escape($cdom),
9118: $homeserver)));
9119: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9120: return (undef,undef);
9121: }
9122: return ($update,$comment);
9123: }
9124:
9125: sub auto_photoupdate {
9126: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9127: my $homeserver = &homeserver($cnum,$dom);
9128: my $host=&hostname($homeserver);
9129: my $cmd = '';
9130: my $maxtries = 1;
9131: foreach my $affiliate (keys(%{$affiliatesref})) {
9132: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9133: }
9134: $cmd =~ s/%%$//;
9135: $cmd = &escape($cmd);
9136: my $query = 'institutionalphotos';
9137: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9138: unless ($queryid=~/^\Q$host\E\_/) {
9139: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9140: return 'error: '.$queryid;
9141: }
9142: my $reply = &get_query_reply($queryid);
9143: my $tries = 1;
9144: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9145: $reply = &get_query_reply($queryid);
9146: $tries ++;
9147: }
9148: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9149: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9150: } else {
9151: my @responses = split(/:/,$reply);
9152: my $outcome = shift(@responses);
9153: foreach my $item (@responses) {
9154: my ($key,$value) = split(/=/,$item);
9155: $$photo{$key} = $value;
9156: }
9157: return $outcome;
9158: }
9159: return 'error';
9160: }
9161:
9162: sub auto_instcode_format {
9163: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9164: $cat_order) = @_;
9165: my $courses = '';
9166: my @homeservers;
9167: if ($caller eq 'global') {
9168: my %servers = &get_servers($codedom,'library');
9169: foreach my $tryserver (keys(%servers)) {
9170: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9171: push(@homeservers,$tryserver);
9172: }
9173: }
9174: } elsif ($caller eq 'requests') {
9175: if ($codedom =~ /^$match_domain$/) {
9176: my $chome = &domain($codedom,'primary');
9177: unless ($chome eq 'no_host') {
9178: push(@homeservers,$chome);
9179: }
9180: }
9181: } else {
9182: push(@homeservers,&homeserver($caller,$codedom));
9183: }
9184: foreach my $code (keys(%{$instcodes})) {
9185: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
9186: }
9187: chop($courses);
9188: my $ok_response = 0;
9189: my $response;
9190: while (@homeservers > 0 && $ok_response == 0) {
9191: my $server = shift(@homeservers);
9192: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9193: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9194: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
9195: split(/:/,$response);
9196: %{$codes} = (%{$codes},&str2hash($codes_str));
9197: push(@{$codetitles},&str2array($codetitles_str));
9198: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9199: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9200: $ok_response = 1;
9201: }
9202: }
9203: if ($ok_response) {
9204: return 'ok';
9205: } else {
9206: return $response;
9207: }
9208: }
9209:
9210: sub auto_instcode_defaults {
9211: my ($domain,$returnhash,$code_order) = @_;
9212: my @homeservers;
9213:
9214: my %servers = &get_servers($domain,'library');
9215: foreach my $tryserver (keys(%servers)) {
9216: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9217: push(@homeservers,$tryserver);
9218: }
9219: }
9220:
9221: my $response;
9222: foreach my $server (@homeservers) {
9223: $response=&reply('autoinstcodedefaults:'.$domain,$server);
9224: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9225:
9226: foreach my $pair (split(/\&/,$response)) {
9227: my ($name,$value)=split(/\=/,$pair);
9228: if ($name eq 'code_order') {
9229: @{$code_order} = split(/\&/,&unescape($value));
9230: } else {
9231: $returnhash->{&unescape($name)}=&unescape($value);
9232: }
9233: }
9234: return 'ok';
9235: }
9236:
9237: return $response;
9238: }
9239:
9240: sub auto_possible_instcodes {
9241: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9242: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9243: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9244: return;
9245: }
9246: my (@homeservers,$uhome);
9247: if (defined(&domain($domain,'primary'))) {
9248: $uhome=&domain($domain,'primary');
9249: push(@homeservers,&domain($domain,'primary'));
9250: } else {
9251: my %servers = &get_servers($domain,'library');
9252: foreach my $tryserver (keys(%servers)) {
9253: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9254: push(@homeservers,$tryserver);
9255: }
9256: }
9257: }
9258: my $response;
9259: foreach my $server (@homeservers) {
9260: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9261: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9262: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9263: split(':',$response);
9264: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9265: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
9266: foreach my $item (split('&',$cat_title)) {
9267: my ($name,$value)=split('=',$item);
9268: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
9269: }
9270: foreach my $item (split('&',$cat_order)) {
9271: my ($name,$value)=split('=',$item);
9272: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
9273: }
9274: return 'ok';
9275: }
9276: return $response;
9277: }
9278:
9279: sub auto_courserequest_checks {
9280: my ($dom) = @_;
9281: my ($homeserver,%validations);
9282: if ($dom =~ /^$match_domain$/) {
9283: $homeserver = &domain($dom,'primary');
9284: }
9285: unless ($homeserver eq 'no_host') {
9286: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9287: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9288: my @items = split(/&/,$response);
9289: foreach my $item (@items) {
9290: my ($key,$value) = split('=',$item);
9291: $validations{&unescape($key)} = &thaw_unescape($value);
9292: }
9293: }
9294: }
9295: return %validations;
9296: }
9297:
9298: sub auto_courserequest_validation {
9299: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
9300: my ($homeserver,$response);
9301: if ($dom =~ /^$match_domain$/) {
9302: $homeserver = &domain($dom,'primary');
9303: }
9304: unless ($homeserver eq 'no_host') {
9305: my $customdata;
9306: if (ref($custominfo) eq 'HASH') {
9307: $customdata = &freeze_escape($custominfo);
9308: }
9309: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
9310: ':'.&escape($crstype).':'.&escape($inststatuslist).
9311: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9312: $customdata,$homeserver));
9313: }
9314: return $response;
9315: }
9316:
9317: sub auto_validate_class_sec {
9318: my ($cdom,$cnum,$owners,$inst_class) = @_;
9319: my $homeserver = &homeserver($cnum,$cdom);
9320: my $ownerlist;
9321: if (ref($owners) eq 'ARRAY') {
9322: $ownerlist = join(',',@{$owners});
9323: } else {
9324: $ownerlist = $owners;
9325: }
9326: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
9327: &escape($ownerlist).':'.$cdom,$homeserver);
9328: return $response;
9329: }
9330:
9331: sub auto_validate_instclasses {
9332: my ($cdom,$cnum,$owners,$classesref) = @_;
9333: my ($homeserver,%validations);
9334: $homeserver = &homeserver($cnum,$cdom);
9335: unless ($homeserver eq 'no_host') {
9336: my $ownerlist;
9337: if (ref($owners) eq 'ARRAY') {
9338: $ownerlist = join(',',@{$owners});
9339: } else {
9340: $ownerlist = $owners;
9341: }
9342: if (ref($classesref) eq 'HASH') {
9343: my $classes = &freeze_escape($classesref);
9344: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9345: ':'.$cdom.':'.$classes,$homeserver);
9346: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9347: my @items = split(/&/,$response);
9348: foreach my $item (@items) {
9349: my ($key,$value) = split('=',$item);
9350: $validations{&unescape($key)} = &thaw_unescape($value);
9351: }
9352: }
9353: }
9354: }
9355: return %validations;
9356: }
9357:
9358: sub auto_crsreq_update {
9359: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
9360: $code,$accessstart,$accessend,$inbound) = @_;
9361: my ($homeserver,%crsreqresponse);
9362: if ($cdom =~ /^$match_domain$/) {
9363: $homeserver = &domain($cdom,'primary');
9364: }
9365: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9366: my $info;
9367: if (ref($inbound) eq 'HASH') {
9368: $info = &freeze_escape($inbound);
9369: }
9370: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9371: ':'.&escape($action).':'.&escape($ownername).':'.
9372: &escape($ownerdomain).':'.&escape($fullname).':'.
9373: &escape($title).':'.&escape($code).':'.
9374: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
9375: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9376: my @items = split(/&/,$response);
9377: foreach my $item (@items) {
9378: my ($key,$value) = split('=',$item);
9379: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9380: }
9381: }
9382: }
9383: return \%crsreqresponse;
9384: }
9385:
9386: sub auto_export_grades {
9387: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9388: my ($homeserver,%exportresponse);
9389: if ($cdom =~ /^$match_domain$/) {
9390: $homeserver = &domain($cdom,'primary');
9391: }
9392: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9393: my $info;
9394: if (ref($inforef) eq 'HASH') {
9395: $info = &freeze_escape($inforef);
9396: }
9397: if (ref($gradesref) eq 'HASH') {
9398: my $grades = &freeze_escape($gradesref);
9399: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9400: $info.':'.$grades,$homeserver);
9401: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9402: my @items = split(/&/,$response);
9403: foreach my $item (@items) {
9404: my ($key,$value) = split('=',$item);
9405: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9406: }
9407: }
9408: }
9409: }
9410: return \%exportresponse;
9411: }
9412:
9413: sub check_instcode_cloning {
9414: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9415: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9416: return;
9417: }
9418: my $canclone;
9419: if (@{$code_order} > 0) {
9420: my $instcoderegexp ='^';
9421: my @clonecodes = split(/\&/,$cloner);
9422: foreach my $item (@{$code_order}) {
9423: if (grep(/^\Q$item\E=/,@clonecodes)) {
9424: foreach my $pair (@clonecodes) {
9425: my ($key,$val) = split(/\=/,$pair,2);
9426: $val = &unescape($val);
9427: if ($key eq $item) {
9428: $instcoderegexp .= '('.$val.')';
9429: last;
9430: }
9431: }
9432: } else {
9433: $instcoderegexp .= $codedefaults->{$item};
9434: }
9435: }
9436: $instcoderegexp .= '$';
9437: my (@from,@to);
9438: eval {
9439: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9440: (@to) = ($clonetocode =~ /$instcoderegexp/);
9441: };
9442: if ((@from > 0) && (@to > 0)) {
9443: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9444: if (!@diffs) {
9445: $canclone = 1;
9446: }
9447: }
9448: }
9449: return $canclone;
9450: }
9451:
9452: sub default_instcode_cloning {
9453: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9454: my (%codedefaults,@code_order,$canclone);
9455: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9456: %codedefaults = %{$codedefaultsref};
9457: @code_order = @{$codeorderref};
9458: } elsif ($clonedom) {
9459: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9460: }
9461: if (($domdefclone) && (@code_order)) {
9462: my @clonecodes = split(/\+/,$domdefclone);
9463: my $instcoderegexp ='^';
9464: foreach my $item (@code_order) {
9465: if (grep(/^\Q$item\E$/,@clonecodes)) {
9466: $instcoderegexp .= '('.$codedefaults{$item}.')';
9467: } else {
9468: $instcoderegexp .= $codedefaults{$item};
9469: }
9470: }
9471: $instcoderegexp .= '$';
9472: my (@from,@to);
9473: eval {
9474: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9475: (@to) = ($clonetocode =~ /$instcoderegexp/);
9476: };
9477: if ((@from > 0) && (@to > 0)) {
9478: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9479: if (!@diffs) {
9480: $canclone = 1;
9481: }
9482: }
9483: }
9484: return $canclone;
9485: }
9486:
9487: # ------------------------------------------------------- Course Group routines
9488:
9489: sub get_coursegroups {
9490: my ($cdom,$cnum,$group,$namespace) = @_;
9491: return(&dump($namespace,$cdom,$cnum,$group));
9492: }
9493:
9494: sub modify_coursegroup {
9495: my ($cdom,$cnum,$groupsettings) = @_;
9496: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9497: }
9498:
9499: sub toggle_coursegroup_status {
9500: my ($cdom,$cnum,$group,$action) = @_;
9501: my ($from_namespace,$to_namespace);
9502: if ($action eq 'delete') {
9503: $from_namespace = 'coursegroups';
9504: $to_namespace = 'deleted_groups';
9505: } else {
9506: $from_namespace = 'deleted_groups';
9507: $to_namespace = 'coursegroups';
9508: }
9509: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
9510: if (my $tmp = &error(%curr_group)) {
9511: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9512: return ('read error',$tmp);
9513: } else {
9514: my %savedsettings = %curr_group;
9515: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
9516: my $deloutcome;
9517: if ($result eq 'ok') {
9518: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
9519: } else {
9520: return ('write error',$result);
9521: }
9522: if ($deloutcome eq 'ok') {
9523: return 'ok';
9524: } else {
9525: return ('delete error',$deloutcome);
9526: }
9527: }
9528: }
9529:
9530: sub modify_group_roles {
9531: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9532: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9533: my $role = 'gr/'.&escape($userprivs);
9534: my ($uname,$udom) = split(/:/,$user);
9535: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9536: if ($result eq 'ok') {
9537: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9538: }
9539: return $result;
9540: }
9541:
9542: sub modify_coursegroup_membership {
9543: my ($cdom,$cnum,$membership) = @_;
9544: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9545: return $result;
9546: }
9547:
9548: sub get_active_groups {
9549: my ($udom,$uname,$cdom,$cnum) = @_;
9550: my $now = time;
9551: my %groups = ();
9552: foreach my $key (keys(%env)) {
9553: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9554: my ($start,$end) = split(/\./,$env{$key});
9555: if (($end!=0) && ($end<$now)) { next; }
9556: if (($start!=0) && ($start>$now)) { next; }
9557: if ($1 eq $cdom && $2 eq $cnum) {
9558: $groups{$3} = $env{$key} ;
9559: }
9560: }
9561: }
9562: return %groups;
9563: }
9564:
9565: sub get_group_membership {
9566: my ($cdom,$cnum,$group) = @_;
9567: return(&dump('groupmembership',$cdom,$cnum,$group));
9568: }
9569:
9570: sub get_users_groups {
9571: my ($udom,$uname,$courseid) = @_;
9572: my @usersgroups;
9573: my $cachetime=1800;
9574:
9575: my $hashid="$udom:$uname:$courseid";
9576: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9577: if (defined($cached)) {
9578: @usersgroups = split(/:/,$grouplist);
9579: } else {
9580: $grouplist = '';
9581: my $courseurl = &courseid_to_courseurl($courseid);
9582: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9583: my $access_end = $env{'course.'.$courseid.
9584: '.default_enrollment_end_date'};
9585: my $now = time;
9586: foreach my $key (keys(%roleshash)) {
9587: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9588: my $group = $1;
9589: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9590: my $start = $2;
9591: my $end = $1;
9592: if ($start == -1) { next; } # deleted from group
9593: if (($start!=0) && ($start>$now)) { next; }
9594: if (($end!=0) && ($end<$now)) {
9595: if ($access_end && $access_end < $now) {
9596: if ($access_end - $end < 86400) {
9597: push(@usersgroups,$group);
9598: }
9599: }
9600: next;
9601: }
9602: push(@usersgroups,$group);
9603: }
9604: }
9605: }
9606: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9607: $grouplist = join(':',@usersgroups);
9608: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9609: }
9610: return @usersgroups;
9611: }
9612:
9613: sub devalidate_getgroups_cache {
9614: my ($udom,$uname,$cdom,$cnum)=@_;
9615: my $courseid = $cdom.'_'.$cnum;
9616:
9617: my $hashid="$udom:$uname:$courseid";
9618: &devalidate_cache_new('getgroups',$hashid);
9619: }
9620:
9621: # ------------------------------------------------------------------ Plain Text
9622:
9623: sub plaintext {
9624: my ($short,$type,$cid,$forcedefault) = @_;
9625: if ($short =~ m{^cr/}) {
9626: return (split('/',$short))[-1];
9627: }
9628: if (!defined($cid)) {
9629: $cid = $env{'request.course.id'};
9630: }
9631: my %rolenames = (
9632: Course => 'std',
9633: Community => 'alt1',
9634: );
9635: if ($cid ne '') {
9636: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9637: unless ($forcedefault) {
9638: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9639: &Apache::lonlocal::mt_escape(\$roletext);
9640: return &Apache::lonlocal::mt($roletext);
9641: }
9642: }
9643: }
9644: if ((defined($type)) && (defined($rolenames{$type})) &&
9645: (defined($rolenames{$type})) &&
9646: (defined($prp{$short}{$rolenames{$type}}))) {
9647: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
9648: } elsif ($cid ne '') {
9649: my $crstype = $env{'course.'.$cid.'.type'};
9650: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9651: (defined($prp{$short}{$rolenames{$crstype}}))) {
9652: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9653: }
9654: }
9655: return &Apache::lonlocal::mt($prp{$short}{'std'});
9656: }
9657:
9658: # ----------------------------------------------------------------- Assign Role
9659:
9660: sub assignrole {
9661: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9662: $context)=@_;
9663: my $mrole;
9664: if ($role =~ /^cr\//) {
9665: my $cwosec=$url;
9666: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9667: unless (&allowed('ccr',$cwosec)) {
9668: my $refused = 1;
9669: if ($context eq 'requestcourses') {
9670: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9671: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9672: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9673: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9674: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9675: if ($crsenv{'internal.courseowner'} eq
9676: $env{'user.name'}.':'.$env{'user.domain'}) {
9677: $refused = '';
9678: }
9679: }
9680: }
9681: }
9682: }
9683: if ($refused) {
9684: &logthis('Refused custom assignrole: '.
9685: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9686: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9687: return 'refused';
9688: }
9689: }
9690: $mrole='cr';
9691: } elsif ($role =~ /^gr\//) {
9692: my $cwogrp=$url;
9693: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
9694: unless (&allowed('mdg',$cwogrp)) {
9695: &logthis('Refused group assignrole: '.
9696: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9697: $env{'user.name'}.' at '.$env{'user.domain'});
9698: return 'refused';
9699: }
9700: $mrole='gr';
9701: } else {
9702: my $cwosec=$url;
9703: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9704: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9705: my $refused;
9706: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9707: if (!(&allowed('c'.$role,$url))) {
9708: $refused = 1;
9709: }
9710: } else {
9711: $refused = 1;
9712: }
9713: if ($refused) {
9714: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9715: if (!$selfenroll && $context eq 'course') {
9716: my %crsenv;
9717: if ($role eq 'cc' || $role eq 'co') {
9718: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9719: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9720: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9721: if ($crsenv{'internal.courseowner'} eq
9722: $env{'user.name'}.':'.$env{'user.domain'}) {
9723: $refused = '';
9724: }
9725: }
9726: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9727: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9728: if ($crsenv{'internal.courseowner'} eq
9729: $env{'user.name'}.':'.$env{'user.domain'}) {
9730: $refused = '';
9731: }
9732: }
9733: }
9734: }
9735: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9736: $refused = '';
9737: } elsif ($context eq 'requestcourses') {
9738: my @possroles = ('st','ta','ep','in','cc','co');
9739: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
9740: my $wrongcc;
9741: if ($cnum =~ /^$match_community$/) {
9742: $wrongcc = 1 if ($role eq 'cc');
9743: } else {
9744: $wrongcc = 1 if ($role eq 'co');
9745: }
9746: unless ($wrongcc) {
9747: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9748: if ($crsenv{'internal.courseowner'} eq
9749: $env{'user.name'}.':'.$env{'user.domain'}) {
9750: $refused = '';
9751: }
9752: }
9753: }
9754: } elsif ($context eq 'requestauthor') {
9755: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9756: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9757: if ($env{'environment.requestauthor'} eq 'automatic') {
9758: $refused = '';
9759: } else {
9760: my %domdefaults = &get_domain_defaults($udom);
9761: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9762: my $checkbystatus;
9763: if ($env{'user.adv'}) {
9764: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9765: if ($disposition eq 'automatic') {
9766: $refused = '';
9767: } elsif ($disposition eq '') {
9768: $checkbystatus = 1;
9769: }
9770: } else {
9771: $checkbystatus = 1;
9772: }
9773: if ($checkbystatus) {
9774: if ($env{'environment.inststatus'}) {
9775: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9776: foreach my $type (@inststatuses) {
9777: if (($type ne '') &&
9778: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9779: $refused = '';
9780: }
9781: }
9782: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9783: $refused = '';
9784: }
9785: }
9786: }
9787: }
9788: }
9789: }
9790: if ($refused) {
9791: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9792: ' '.$role.' '.$end.' '.$start.' by '.
9793: $env{'user.name'}.' at '.$env{'user.domain'});
9794: return 'refused';
9795: }
9796: }
9797: } elsif ($role eq 'au') {
9798: if ($url ne '/'.$udom.'/') {
9799: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9800: ' to assign author role for '.$uname.':'.$udom.
9801: ' in domain: '.$url.' refused (wrong domain).');
9802: return 'refused';
9803: }
9804: }
9805: $mrole=$role;
9806: }
9807: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9808: "$udom:$uname:$url".'_'."$mrole=$role";
9809: if ($end) { $command.='_'.$end; }
9810: if ($start) {
9811: if ($end) {
9812: $command.='_'.$start;
9813: } else {
9814: $command.='_0_'.$start;
9815: }
9816: }
9817: my $origstart = $start;
9818: my $origend = $end;
9819: my $delflag;
9820: # actually delete
9821: if ($deleteflag) {
9822: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
9823: # modify command to delete the role
9824: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
9825: "$udom:$uname:$url".'_'."$mrole";
9826: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
9827: # set start and finish to negative values for userrolelog
9828: $start=-1;
9829: $end=-1;
9830: $delflag = 1;
9831: }
9832: }
9833: # send command
9834: my $answer=&reply($command,&homeserver($uname,$udom));
9835: # log new user role if status is ok
9836: if ($answer eq 'ok') {
9837: &userrolelog($role,$uname,$udom,$url,$start,$end);
9838: if (($role eq 'cc') || ($role eq 'in') ||
9839: ($role eq 'ep') || ($role eq 'ad') ||
9840: ($role eq 'ta') || ($role eq 'st') ||
9841: ($role=~/^cr/) || ($role eq 'gr') ||
9842: ($role eq 'co')) {
9843: # for course roles, perform group memberships changes triggered by role change.
9844: unless ($role =~ /^gr/) {
9845: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9846: $origstart,$selfenroll,$context);
9847: }
9848: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9849: $selfenroll,$context);
9850: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
9851: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9852: ($role eq 'da')) {
9853: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9854: $context);
9855: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9856: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9857: $context);
9858: }
9859: if ($role eq 'cc') {
9860: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9861: }
9862: }
9863: return $answer;
9864: }
9865:
9866: sub autoupdate_coowners {
9867: my ($url,$end,$start,$uname,$udom) = @_;
9868: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9869: if (($cdom ne '') && ($cnum ne '')) {
9870: my $now = time;
9871: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9872: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9873: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9874: my $instcode = $coursehash{'internal.coursecode'};
9875: if ($instcode ne '') {
9876: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9877: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
9878: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
9879: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9880: if ($result eq 'valid') {
9881: if ($coursehash{'internal.co-owners'}) {
9882: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9883: push(@newcoowners,$coowner);
9884: }
9885: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9886: push(@newcoowners,$uname.':'.$udom);
9887: }
9888: @newcoowners = sort(@newcoowners);
9889: } else {
9890: push(@newcoowners,$uname.':'.$udom);
9891: }
9892: } else {
9893: if ($coursehash{'internal.co-owners'}) {
9894: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9895: unless ($coowner eq $uname.':'.$udom) {
9896: push(@newcoowners,$coowner);
9897: }
9898: }
9899: unless (@newcoowners > 0) {
9900: $delcoowners = 1;
9901: $coowners = '';
9902: }
9903: }
9904: }
9905: if (@newcoowners || $delcoowners) {
9906: &store_coowners($cdom,$cnum,$coursehash{'home'},
9907: $delcoowners,@newcoowners);
9908: }
9909: }
9910: }
9911: }
9912: }
9913: }
9914: }
9915:
9916: sub store_coowners {
9917: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9918: my $cid = $cdom.'_'.$cnum;
9919: my ($coowners,$delresult,$putresult);
9920: if (@newcoowners) {
9921: $coowners = join(',',@newcoowners);
9922: my %coownershash = (
9923: 'internal.co-owners' => $coowners,
9924: );
9925: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9926: if ($putresult eq 'ok') {
9927: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9928: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9929: }
9930: }
9931: }
9932: if ($delcoowners) {
9933: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9934: if ($delresult eq 'ok') {
9935: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9936: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9937: }
9938: }
9939: }
9940: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9941: my %crsinfo =
9942: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9943: if (ref($crsinfo{$cid}) eq 'HASH') {
9944: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9945: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9946: }
9947: }
9948: }
9949:
9950: # -------------------------------------------------- Modify user authentication
9951: # Overrides without validation
9952:
9953: sub modifyuserauth {
9954: my ($udom,$uname,$umode,$upass)=@_;
9955: my $uhome=&homeserver($uname,$udom);
9956: my $allowed;
9957: if (&allowed('mau',$udom)) {
9958: $allowed = 1;
9959: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
9960: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
9961: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
9962: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9963: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9964: if (($cdom ne '') && ($cnum ne '')) {
9965: my $is_owner = &is_course_owner($cdom,$cnum);
9966: if ($is_owner) {
9967: $allowed = 1;
9968: }
9969: }
9970: }
9971: unless ($allowed) { return 'refused'; }
9972: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
9973: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9974: ' in domain '.$env{'request.role.domain'});
9975: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9976: &escape($upass),$uhome);
9977: my $ip = &get_requestor_ip();
9978: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
9979: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9980: '(Remote '.$ip.'): '.$reply);
9981: &log($udom,,$uname,$uhome,
9982: 'Authentication changed by '.$env{'user.domain'}.', '.
9983: $env{'user.name'}.', '.$umode.
9984: '(Remote '.$ip.'): '.$reply);
9985: unless ($reply eq 'ok') {
9986: &logthis('Authentication mode error: '.$reply);
9987: return 'error: '.$reply;
9988: }
9989: return 'ok';
9990: }
9991:
9992: # --------------------------------------------------------------- Modify a user
9993:
9994: sub modifyuser {
9995: my ($udom, $uname, $uid,
9996: $umode, $upass, $first,
9997: $middle, $last, $gene,
9998: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
9999: $udom= &LONCAPA::clean_domain($udom);
10000: $uname=&LONCAPA::clean_username($uname);
10001: my $showcandelete = 'none';
10002: if (ref($candelete) eq 'ARRAY') {
10003: if (@{$candelete} > 0) {
10004: $showcandelete = join(', ',@{$candelete});
10005: }
10006: }
10007: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
10008: $umode.', '.$first.', '.$middle.', '.
10009: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
10010: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
10011: ' desiredhome not specified').
10012: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
10013: ' in domain '.$env{'request.role.domain'});
10014: my $uhome=&homeserver($uname,$udom,'true');
10015: my $newuser;
10016: if ($uhome eq 'no_host') {
10017: $newuser = 1;
10018: }
10019: # ----------------------------------------------------------------- Create User
10020: if (($uhome eq 'no_host') &&
10021: (($umode && $upass) || ($umode eq 'localauth'))) {
10022: my $unhome='';
10023: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
10024: $unhome = $desiredhome;
10025: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
10026: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
10027: } else { # load balancing routine for determining $unhome
10028: my $loadm=10000000;
10029: my %servers = &get_servers($udom,'library');
10030: foreach my $tryserver (keys(%servers)) {
10031: my $answer=reply('load',$tryserver);
10032: if (($answer=~/\d+/) && ($answer<$loadm)) {
10033: $loadm=$answer;
10034: $unhome=$tryserver;
10035: }
10036: }
10037: }
10038: if (($unhome eq '') || ($unhome eq 'no_host')) {
10039: return 'error: unable to find a home server for '.$uname.
10040: ' in domain '.$udom;
10041: }
10042: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
10043: &escape($upass),$unhome);
10044: unless ($reply eq 'ok') {
10045: return 'error: '.$reply;
10046: }
10047: $uhome=&homeserver($uname,$udom,'true');
10048: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
10049: return 'error: unable verify users home machine.';
10050: }
10051: } # End of creation of new user
10052: # ---------------------------------------------------------------------- Add ID
10053: if ($uid) {
10054: $uid=~tr/A-Z/a-z/;
10055: my %uidhash=&idrget($udom,$uname);
10056: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
10057: && (!$forceid)) {
10058: unless ($uid eq $uidhash{$uname}) {
10059: return 'error: user id "'.$uid.'" does not match '.
10060: 'current user id "'.$uidhash{$uname}.'".';
10061: }
10062: } else {
10063: &idput($udom,($uname => $uid));
10064: }
10065: }
10066: # -------------------------------------------------------------- Add names, etc
10067: my @tmp=&get('environment',
10068: ['firstname','middlename','lastname','generation','id',
10069: 'permanentemail','inststatus'],
10070: $udom,$uname);
10071: my (%names,%oldnames);
10072: if ($tmp[0] =~ m/^error:.*/) {
10073: %names=();
10074: } else {
10075: %names = @tmp;
10076: %oldnames = %names;
10077: }
10078: #
10079: # If name, email and/or uid are blank (e.g., because an uploaded file
10080: # of users did not contain them), do not overwrite existing values
10081: # unless field is in $candelete array ref.
10082: #
10083:
10084: my @fields = ('firstname','middlename','lastname','generation',
10085: 'permanentemail','id');
10086: my %newvalues;
10087: if (ref($candelete) eq 'ARRAY') {
10088: foreach my $field (@fields) {
10089: if (grep(/^\Q$field\E$/,@{$candelete})) {
10090: if ($field eq 'firstname') {
10091: $names{$field} = $first;
10092: } elsif ($field eq 'middlename') {
10093: $names{$field} = $middle;
10094: } elsif ($field eq 'lastname') {
10095: $names{$field} = $last;
10096: } elsif ($field eq 'generation') {
10097: $names{$field} = $gene;
10098: } elsif ($field eq 'permanentemail') {
10099: $names{$field} = $email;
10100: } elsif ($field eq 'id') {
10101: $names{$field} = $uid;
10102: }
10103: }
10104: }
10105: }
10106: if ($first) { $names{'firstname'} = $first; }
10107: if (defined($middle)) { $names{'middlename'} = $middle; }
10108: if ($last) { $names{'lastname'} = $last; }
10109: if (defined($gene)) { $names{'generation'} = $gene; }
10110: if ($email) {
10111: $email=~s/[^\w\@\.\-\,]//gs;
10112: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10113: }
10114: if ($uid) { $names{'id'} = $uid; }
10115: if (defined($inststatus)) {
10116: $names{'inststatus'} = '';
10117: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10118: if (ref($usertypes) eq 'HASH') {
10119: my @okstatuses;
10120: foreach my $item (split(/:/,$inststatus)) {
10121: if (defined($usertypes->{$item})) {
10122: push(@okstatuses,$item);
10123: }
10124: }
10125: if (@okstatuses) {
10126: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10127: }
10128: }
10129: }
10130: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10131: $umode.', '.$first.', '.$middle.', '.
10132: $last.', '.$gene.', '.$email.', '.$inststatus;
10133: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10134: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10135: } else {
10136: $logmsg .= ' during self creation';
10137: }
10138: my $changed;
10139: if ($newuser) {
10140: $changed = 1;
10141: } else {
10142: foreach my $field (@fields) {
10143: if ($names{$field} ne $oldnames{$field}) {
10144: $changed = 1;
10145: last;
10146: }
10147: }
10148: }
10149: unless ($changed) {
10150: $logmsg = 'No changes in user information needed for: '.$logmsg;
10151: &logthis($logmsg);
10152: return 'ok';
10153: }
10154: my $reply = &put('environment', \%names, $udom,$uname);
10155: if ($reply ne 'ok') {
10156: return 'error: '.$reply;
10157: }
10158: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10159: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10160: }
10161: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10162: &devalidate_cache_new('namescache',$uname.':'.$udom);
10163: $logmsg = 'Success modifying user '.$logmsg;
10164: &logthis($logmsg);
10165: return 'ok';
10166: }
10167:
10168: # -------------------------------------------------------------- Modify student
10169:
10170: sub modifystudent {
10171: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10172: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10173: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10174: if (!$cid) {
10175: unless ($cid=$env{'request.course.id'}) {
10176: return 'not_in_class';
10177: }
10178: }
10179: # --------------------------------------------------------------- Make the user
10180: my $reply=&modifyuser
10181: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10182: $desiredhome,$email,$inststatus);
10183: unless ($reply eq 'ok') { return $reply; }
10184: # This will cause &modify_student_enrollment to get the uid from the
10185: # student's environment
10186: $uid = undef if (!$forceid);
10187: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10188: $gene,$usec,$end,$start,$type,$locktype,
10189: $cid,$selfenroll,$context,$credits,$instsec);
10190: return $reply;
10191: }
10192:
10193: sub modify_student_enrollment {
10194: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10195: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10196: my ($cdom,$cnum,$chome);
10197: if (!$cid) {
10198: unless ($cid=$env{'request.course.id'}) {
10199: return 'not_in_class';
10200: }
10201: $cdom=$env{'course.'.$cid.'.domain'};
10202: $cnum=$env{'course.'.$cid.'.num'};
10203: } else {
10204: ($cdom,$cnum)=split(/_/,$cid);
10205: }
10206: $chome=$env{'course.'.$cid.'.home'};
10207: if (!$chome) {
10208: $chome=&homeserver($cnum,$cdom);
10209: }
10210: if (!$chome) { return 'unknown_course'; }
10211: # Make sure the user exists
10212: my $uhome=&homeserver($uname,$udom);
10213: if (($uhome eq '') || ($uhome eq 'no_host')) {
10214: return 'error: no such user';
10215: }
10216: # Get student data if we were not given enough information
10217: if (!defined($first) || $first eq '' ||
10218: !defined($last) || $last eq '' ||
10219: !defined($uid) || $uid eq '' ||
10220: !defined($middle) || $middle eq '' ||
10221: !defined($gene) || $gene eq '') {
10222: # They did not supply us with enough data to enroll the student, so
10223: # we need to pick up more information.
10224: my %tmp = &get('environment',
10225: ['firstname','middlename','lastname', 'generation','id']
10226: ,$udom,$uname);
10227:
10228: #foreach my $key (keys(%tmp)) {
10229: # &logthis("key $key = ".$tmp{$key});
10230: #}
10231: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10232: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10233: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
10234: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
10235: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10236: }
10237: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10238: my $user = "$uname:$udom";
10239: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10240: my $reply=cput('classlist',
10241: {$user =>
10242: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10243: $cdom,$cnum);
10244: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10245: &devalidate_getsection_cache($udom,$uname,$cid);
10246: } else {
10247: return 'error: '.$reply;
10248: }
10249: # Add student role to user
10250: my $uurl='/'.$cid;
10251: $uurl=~s/\_/\//g;
10252: if ($usec) {
10253: $uurl.='/'.$usec;
10254: }
10255: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10256: $selfenroll,$context);
10257: if ($result ne 'ok') {
10258: if ($old_entry{$user} ne '') {
10259: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10260: } else {
10261: $reply = &del('classlist',[$user],$cdom,$cnum);
10262: }
10263: }
10264: return $result;
10265: }
10266:
10267: sub format_name {
10268: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10269: my $name;
10270: if ($first ne 'lastname') {
10271: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10272: } else {
10273: if ($lastname=~/\S/) {
10274: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10275: $name=~s/\s+,/,/;
10276: } else {
10277: $name.= $firstname.' '.$middlename.' '.$generation;
10278: }
10279: }
10280: $name=~s/^\s+//;
10281: $name=~s/\s+$//;
10282: $name=~s/\s+/ /g;
10283: return $name;
10284: }
10285:
10286: # ------------------------------------------------- Write to course preferences
10287:
10288: sub writecoursepref {
10289: my ($courseid,%prefs)=@_;
10290: $courseid=~s/^\///;
10291: $courseid=~s/\_/\//g;
10292: my ($cdomain,$cnum)=split(/\//,$courseid);
10293: my $chome=homeserver($cnum,$cdomain);
10294: if (($chome eq '') || ($chome eq 'no_host')) {
10295: return 'error: no such course';
10296: }
10297: my $cstring='';
10298: foreach my $pref (keys(%prefs)) {
10299: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10300: }
10301: $cstring=~s/\&$//;
10302: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10303: }
10304:
10305: # ---------------------------------------------------------- Make/modify course
10306:
10307: sub createcourse {
10308: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10309: $course_owner,$crstype,$cnum,$context,$category)=@_;
10310: $url=&declutter($url);
10311: my $cid='';
10312: if ($context eq 'requestcourses') {
10313: my $can_create = 0;
10314: my ($ownername,$ownerdom) = split(':',$course_owner);
10315: if ($udom eq $ownerdom) {
10316: if (&usertools_access($ownername,$ownerdom,$category,undef,
10317: $context)) {
10318: $can_create = 1;
10319: }
10320: } else {
10321: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10322: $category);
10323: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10324: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10325: if (@curr > 0) {
10326: my @options = qw(approval validate autolimit);
10327: my $optregex = join('|',@options);
10328: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10329: $can_create = 1;
10330: }
10331: }
10332: }
10333: }
10334: if ($can_create) {
10335: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10336: unless (&allowed('ccc',$udom)) {
10337: return 'refused';
10338: }
10339: }
10340: } else {
10341: return 'refused';
10342: }
10343: } elsif (!&allowed('ccc',$udom)) {
10344: return 'refused';
10345: }
10346: # --------------------------------------------------------------- Get Unique ID
10347: my $uname;
10348: if ($cnum =~ /^$match_courseid$/) {
10349: my $chome=&homeserver($cnum,$udom,'true');
10350: if (($chome eq '') || ($chome eq 'no_host')) {
10351: $uname = $cnum;
10352: } else {
10353: $uname = &generate_coursenum($udom,$crstype);
10354: }
10355: } else {
10356: $uname = &generate_coursenum($udom,$crstype);
10357: }
10358: return $uname if ($uname =~ /^error/);
10359: # -------------------------------------------------- Check supplied server name
10360: if (!defined($course_server)) {
10361: if (defined(&domain($udom,'primary'))) {
10362: $course_server = &domain($udom,'primary');
10363: } else {
10364: $course_server = $env{'user.home'};
10365: }
10366: }
10367: my %host_servers =
10368: &Apache::lonnet::get_servers($udom,'library');
10369: unless ($host_servers{$course_server}) {
10370: return 'error: invalid home server for course: '.$course_server;
10371: }
10372: # ------------------------------------------------------------- Make the course
10373: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10374: $course_server);
10375: unless ($reply eq 'ok') { return 'error: '.$reply; }
10376: my $uhome=&homeserver($uname,$udom,'true');
10377: if (($uhome eq '') || ($uhome eq 'no_host')) {
10378: return 'error: no such course';
10379: }
10380: # ----------------------------------------------------------------- Course made
10381: # log existence
10382: my $now = time;
10383: my $newcourse = {
10384: $udom.'_'.$uname => {
10385: description => $description,
10386: inst_code => $inst_code,
10387: owner => $course_owner,
10388: type => $crstype,
10389: creator => $env{'user.name'}.':'.
10390: $env{'user.domain'},
10391: created => $now,
10392: context => $context,
10393: },
10394: };
10395: &courseidput($udom,$newcourse,$uhome,'notime');
10396: # set toplevel url
10397: my $topurl=$url;
10398: unless ($nonstandard) {
10399: # ------------------------------------------ For standard courses, make top url
10400: my $mapurl=&clutter($url);
10401: if ($mapurl eq '/res/') { $mapurl=''; }
10402: $env{'form.initmap'}=(<<ENDINITMAP);
10403: <map>
10404: <resource id="1" type="start"></resource>
10405: <resource id="2" src="$mapurl"></resource>
10406: <resource id="3" type="finish"></resource>
10407: <link index="1" from="1" to="2"></link>
10408: <link index="2" from="2" to="3"></link>
10409: </map>
10410: ENDINITMAP
10411: $topurl=&declutter(
10412: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10413: );
10414: }
10415: # ----------------------------------------------------------- Write preferences
10416: &writecoursepref($udom.'_'.$uname,
10417: ('description' => $description,
10418: 'url' => $topurl,
10419: 'internal.creator' => $env{'user.name'}.':'.
10420: $env{'user.domain'},
10421: 'internal.created' => $now,
10422: 'internal.creationcontext' => $context)
10423: );
10424: return '/'.$udom.'/'.$uname;
10425: }
10426:
10427: # ------------------------------------------------------------------- Create ID
10428: sub generate_coursenum {
10429: my ($udom,$crstype) = @_;
10430: my $domdesc = &domain($udom);
10431: return 'error: invalid domain' if ($domdesc eq '');
10432: my $first;
10433: if ($crstype eq 'Community') {
10434: $first = '0';
10435: } else {
10436: $first = int(1+rand(9));
10437: }
10438: my $uname=$first.
10439: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10440: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10441: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10442: # ----------------------------------------------- Make sure that does not exist
10443: my $uhome=&homeserver($uname,$udom,'true');
10444: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10445: if ($crstype eq 'Community') {
10446: $first = '0';
10447: } else {
10448: $first = int(1+rand(9));
10449: }
10450: $uname=$first.
10451: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10452: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10453: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10454: $uhome=&homeserver($uname,$udom,'true');
10455: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10456: return 'error: unable to generate unique course-ID';
10457: }
10458: }
10459: return $uname;
10460: }
10461:
10462: sub is_course {
10463: my ($cdom, $cnum) = scalar(@_) == 1 ?
10464: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10465: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10466: my $uhome=&homeserver($cnum,$cdom);
10467: my $iscourse;
10468: if (grep { $_ eq $uhome } current_machine_ids()) {
10469: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10470: } else {
10471: my $hashid = $cdom.':'.$cnum;
10472: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10473: unless (defined($cached)) {
10474: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10475: $cnum,undef,undef,'.');
10476: $iscourse = 0;
10477: if (exists($courses{$cdom.'_'.$cnum})) {
10478: $iscourse = 1;
10479: }
10480: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10481: }
10482: }
10483: return unless($iscourse);
10484: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10485: }
10486:
10487: sub store_userdata {
10488: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10489: my $result;
10490: if ($datakey ne '') {
10491: if (ref($storehash) eq 'HASH') {
10492: if ($udom eq '' || $uname eq '') {
10493: $udom = $env{'user.domain'};
10494: $uname = $env{'user.name'};
10495: }
10496: my $uhome=&homeserver($uname,$udom);
10497: if (($uhome eq '') || ($uhome eq 'no_host')) {
10498: $result = 'error: no_host';
10499: } else {
10500: $storehash->{'ip'} = &get_requestor_ip();
10501: $storehash->{'host'} = $perlvar{'lonHostID'};
10502:
10503: my $namevalue='';
10504: foreach my $key (keys(%{$storehash})) {
10505: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10506: }
10507: $namevalue=~s/\&$//;
10508: unless ($namespace eq 'courserequests') {
10509: $datakey = &escape($datakey);
10510: }
10511: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10512: $namevalue,$uhome);
10513: }
10514: } else {
10515: $result = 'error: data to store was not a hash reference';
10516: }
10517: } else {
10518: $result= 'error: invalid requestkey';
10519: }
10520: return $result;
10521: }
10522:
10523: # ---------------------------------------------------------- Assign Custom Role
10524:
10525: sub assigncustomrole {
10526: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10527: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10528: $end,$start,$deleteflag,$selfenroll,$context);
10529: }
10530:
10531: # ----------------------------------------------------------------- Revoke Role
10532:
10533: sub revokerole {
10534: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10535: my $now=time;
10536: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10537: }
10538:
10539: # ---------------------------------------------------------- Revoke Custom Role
10540:
10541: sub revokecustomrole {
10542: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10543: my $now=time;
10544: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10545: $deleteflag,$selfenroll,$context);
10546: }
10547:
10548: # ------------------------------------------------------------ Disk usage
10549: sub diskusage {
10550: my ($udom,$uname,$directorypath,$getpropath)=@_;
10551: $directorypath =~ s/\/$//;
10552: my $listing=&reply('du2:'.&escape($directorypath).':'
10553: .&escape($getpropath).':'.&escape($uname).':'
10554: .&escape($udom),homeserver($uname,$udom));
10555: if ($listing eq 'unknown_cmd') {
10556: if ($getpropath) {
10557: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10558: }
10559: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10560: }
10561: return $listing;
10562: }
10563:
10564: sub is_locked {
10565: my ($file_name, $domain, $user, $which) = @_;
10566: my @check;
10567: my $is_locked;
10568: push (@check,$file_name);
10569: my %locked = &get('file_permissions',\@check,
10570: $env{'user.domain'},$env{'user.name'});
10571: my ($tmp)=keys(%locked);
10572: if ($tmp=~/^error:/) { undef(%locked); }
10573:
10574: if (ref($locked{$file_name}) eq 'ARRAY') {
10575: $is_locked = 'false';
10576: foreach my $entry (@{$locked{$file_name}}) {
10577: if (ref($entry) eq 'ARRAY') {
10578: $is_locked = 'true';
10579: if (ref($which) eq 'ARRAY') {
10580: push(@{$which},$entry);
10581: } else {
10582: last;
10583: }
10584: }
10585: }
10586: } else {
10587: $is_locked = 'false';
10588: }
10589: return $is_locked;
10590: }
10591:
10592: sub declutter_portfile {
10593: my ($file) = @_;
10594: $file =~ s{^(/portfolio/|portfolio/)}{/};
10595: return $file;
10596: }
10597:
10598: # ------------------------------------------------------------- Mark as Read Only
10599:
10600: sub mark_as_readonly {
10601: my ($domain,$user,$files,$what) = @_;
10602: my %current_permissions = &dump('file_permissions',$domain,$user);
10603: my ($tmp)=keys(%current_permissions);
10604: if ($tmp=~/^error:/) { undef(%current_permissions); }
10605: foreach my $file (@{$files}) {
10606: $file = &declutter_portfile($file);
10607: push(@{$current_permissions{$file}},$what);
10608: }
10609: &put('file_permissions',\%current_permissions,$domain,$user);
10610: return;
10611: }
10612:
10613: # ------------------------------------------------------------Save Selected Files
10614:
10615: sub save_selected_files {
10616: my ($user, $path, @files) = @_;
10617: my $filename = $user."savedfiles";
10618: my @other_files = &files_not_in_path($user, $path);
10619: open (OUT,'>',LONCAPA::tempdir().$filename);
10620: foreach my $file (@files) {
10621: print (OUT $env{'form.currentpath'}.$file."\n");
10622: }
10623: foreach my $file (@other_files) {
10624: print (OUT $file."\n");
10625: }
10626: close (OUT);
10627: return 'ok';
10628: }
10629:
10630: sub clear_selected_files {
10631: my ($user) = @_;
10632: my $filename = $user."savedfiles";
10633: open (OUT,'>',LONCAPA::tempdir().$filename);
10634: print (OUT undef);
10635: close (OUT);
10636: return ("ok");
10637: }
10638:
10639: sub files_in_path {
10640: my ($user, $path) = @_;
10641: my $filename = $user."savedfiles";
10642: my %return_files;
10643: open (IN,'<',LONCAPA::tempdir().$filename);
10644: while (my $line_in = <IN>) {
10645: chomp ($line_in);
10646: my @paths_and_file = split (m!/!, $line_in);
10647: my $file_part = pop (@paths_and_file);
10648: my $path_part = join ('/', @paths_and_file);
10649: $path_part.='/';
10650: my $path_and_file = $path_part.$file_part;
10651: if ($path_part eq $path) {
10652: $return_files{$file_part}= 'selected';
10653: }
10654: }
10655: close (IN);
10656: return (\%return_files);
10657: }
10658:
10659: # called in portfolio select mode, to show files selected NOT in current directory
10660: sub files_not_in_path {
10661: my ($user, $path) = @_;
10662: my $filename = $user."savedfiles";
10663: my @return_files;
10664: my $path_part;
10665: open(IN, '<',LONCAPA::tempdir().$filename);
10666: while (my $line = <IN>) {
10667: #ok, I know it's clunky, but I want it to work
10668: my @paths_and_file = split(m|/|, $line);
10669: my $file_part = pop(@paths_and_file);
10670: chomp($file_part);
10671: my $path_part = join('/', @paths_and_file);
10672: $path_part .= '/';
10673: my $path_and_file = $path_part.$file_part;
10674: if ($path_part ne $path) {
10675: push(@return_files, ($path_and_file));
10676: }
10677: }
10678: close(OUT);
10679: return (@return_files);
10680: }
10681:
10682: #----------------------------------------------Get portfolio file permissions
10683:
10684: sub get_portfile_permissions {
10685: my ($domain,$user) = @_;
10686: my %current_permissions = &dump('file_permissions',$domain,$user);
10687: my ($tmp)=keys(%current_permissions);
10688: if ($tmp=~/^error:/) { undef(%current_permissions); }
10689: return \%current_permissions;
10690: }
10691:
10692: #---------------------------------------------Get portfolio file access controls
10693:
10694: sub get_access_controls {
10695: my ($current_permissions,$group,$file) = @_;
10696: my %access;
10697: my $real_file = $file;
10698: $file =~ s/\.meta$//;
10699: if (defined($file)) {
10700: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10701: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10702: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10703: }
10704: }
10705: } else {
10706: foreach my $key (keys(%{$current_permissions})) {
10707: if ($key =~ /\0accesscontrol$/) {
10708: if (defined($group)) {
10709: if ($key !~ m-^\Q$group\E/-) {
10710: next;
10711: }
10712: }
10713: my ($fullpath) = split(/\0/,$key);
10714: if (ref($$current_permissions{$key}) eq 'HASH') {
10715: foreach my $control (keys(%{$$current_permissions{$key}})) {
10716: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10717: }
10718: }
10719: }
10720: }
10721: }
10722: return %access;
10723: }
10724:
10725: sub modify_access_controls {
10726: my ($file_name,$changes,$domain,$user)=@_;
10727: my ($outcome,$deloutcome);
10728: my %store_permissions;
10729: my %new_values;
10730: my %new_control;
10731: my %translation;
10732: my @deletions = ();
10733: my $now = time;
10734: if (exists($$changes{'activate'})) {
10735: if (ref($$changes{'activate'}) eq 'HASH') {
10736: my @newitems = sort(keys(%{$$changes{'activate'}}));
10737: my $numnew = scalar(@newitems);
10738: for (my $i=0; $i<$numnew; $i++) {
10739: my $newkey = $newitems[$i];
10740: my $newid = &Apache::loncommon::get_cgi_id();
10741: if ($newkey =~ /^\d+:/) {
10742: $newkey =~ s/^(\d+)/$newid/;
10743: $translation{$1} = $newid;
10744: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10745: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10746: $translation{$1} = $newid;
10747: }
10748: $new_values{$file_name."\0".$newkey} =
10749: $$changes{'activate'}{$newitems[$i]};
10750: $new_control{$newkey} = $now;
10751: }
10752: }
10753: }
10754: my %todelete;
10755: my %changed_items;
10756: foreach my $action ('delete','update') {
10757: if (exists($$changes{$action})) {
10758: if (ref($$changes{$action}) eq 'HASH') {
10759: foreach my $key (keys(%{$$changes{$action}})) {
10760: my ($itemnum) = ($key =~ /^([^:]+):/);
10761: if ($action eq 'delete') {
10762: $todelete{$itemnum} = 1;
10763: } else {
10764: $changed_items{$itemnum} = $key;
10765: }
10766: }
10767: }
10768: }
10769: }
10770: # get lock on access controls for file.
10771: my $lockhash = {
10772: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10773: ':'.$env{'user.domain'},
10774: };
10775: my $tries = 0;
10776: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10777:
10778: while (($gotlock ne 'ok') && $tries < 10) {
10779: $tries ++;
10780: sleep(0.1);
10781: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10782: }
10783: if ($gotlock eq 'ok') {
10784: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10785: my ($tmp)=keys(%curr_permissions);
10786: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10787: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10788: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10789: if (ref($curr_controls) eq 'HASH') {
10790: foreach my $control_item (keys(%{$curr_controls})) {
10791: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10792: if (defined($todelete{$itemnum})) {
10793: push(@deletions,$file_name."\0".$control_item);
10794: } else {
10795: if (defined($changed_items{$itemnum})) {
10796: $new_control{$changed_items{$itemnum}} = $now;
10797: push(@deletions,$file_name."\0".$control_item);
10798: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10799: } else {
10800: $new_control{$control_item} = $$curr_controls{$control_item};
10801: }
10802: }
10803: }
10804: }
10805: }
10806: my ($group);
10807: if (&is_course($domain,$user)) {
10808: ($group,my $file) = split(/\//,$file_name,2);
10809: }
10810: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10811: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10812: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10813: # remove lock
10814: my @del_lock = ($file_name."\0".'locked_access_records');
10815: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10816: my $sqlresult =
10817: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10818: $group);
10819: } else {
10820: $outcome = "error: could not obtain lockfile\n";
10821: }
10822: return ($outcome,$deloutcome,\%new_values,\%translation);
10823: }
10824:
10825: sub make_public_indefinitely {
10826: my ($requrl) = @_;
10827: my $now = time;
10828: my $action = 'activate';
10829: my $aclnum = 0;
10830: if (&is_portfolio_url($requrl)) {
10831: my (undef,$udom,$unum,$file_name,$group) =
10832: &parse_portfolio_url($requrl);
10833: my $current_perms = &get_portfile_permissions($udom,$unum);
10834: my %access_controls = &get_access_controls($current_perms,
10835: $group,$file_name);
10836: foreach my $key (keys(%{$access_controls{$file_name}})) {
10837: my ($num,$scope,$end,$start) =
10838: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10839: if ($scope eq 'public') {
10840: if ($start <= $now && $end == 0) {
10841: $action = 'none';
10842: } else {
10843: $action = 'update';
10844: $aclnum = $num;
10845: }
10846: last;
10847: }
10848: }
10849: if ($action eq 'none') {
10850: return 'ok';
10851: } else {
10852: my %changes;
10853: my $newend = 0;
10854: my $newstart = $now;
10855: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10856: $changes{$action}{$newkey} = {
10857: type => 'public',
10858: time => {
10859: start => $newstart,
10860: end => $newend,
10861: },
10862: };
10863: my ($outcome,$deloutcome,$new_values,$translation) =
10864: &modify_access_controls($file_name,\%changes,$udom,$unum);
10865: return $outcome;
10866: }
10867: } else {
10868: return 'invalid';
10869: }
10870: }
10871:
10872: #------------------------------------------------------Get Marked as Read Only
10873:
10874: sub get_marked_as_readonly {
10875: my ($domain,$user,$what,$group) = @_;
10876: my $current_permissions = &get_portfile_permissions($domain,$user);
10877: my @readonly_files;
10878: my $cmp1=$what;
10879: if (ref($what)) { $cmp1=join('',@{$what}) };
10880: while (my ($file_name,$value) = each(%{$current_permissions})) {
10881: if (defined($group)) {
10882: if ($file_name !~ m-^\Q$group\E/-) {
10883: next;
10884: }
10885: }
10886: if (ref($value) eq "ARRAY"){
10887: foreach my $stored_what (@{$value}) {
10888: my $cmp2=$stored_what;
10889: if (ref($stored_what) eq 'ARRAY') {
10890: $cmp2=join('',@{$stored_what});
10891: }
10892: if ($cmp1 eq $cmp2) {
10893: push(@readonly_files, $file_name);
10894: last;
10895: } elsif (!defined($what)) {
10896: push(@readonly_files, $file_name);
10897: last;
10898: }
10899: }
10900: }
10901: }
10902: return @readonly_files;
10903: }
10904: #-----------------------------------------------------------Get Marked as Read Only Hash
10905:
10906: sub get_marked_as_readonly_hash {
10907: my ($current_permissions,$group,$what) = @_;
10908: my %readonly_files;
10909: while (my ($file_name,$value) = each(%{$current_permissions})) {
10910: if (defined($group)) {
10911: if ($file_name !~ m-^\Q$group\E/-) {
10912: next;
10913: }
10914: }
10915: if (ref($value) eq "ARRAY"){
10916: foreach my $stored_what (@{$value}) {
10917: if (ref($stored_what) eq 'ARRAY') {
10918: foreach my $lock_descriptor(@{$stored_what}) {
10919: if ($lock_descriptor eq 'graded') {
10920: $readonly_files{$file_name} = 'graded';
10921: } elsif ($lock_descriptor eq 'handback') {
10922: $readonly_files{$file_name} = 'handback';
10923: } else {
10924: if (!exists($readonly_files{$file_name})) {
10925: $readonly_files{$file_name} = 'locked';
10926: }
10927: }
10928: }
10929: }
10930: }
10931: }
10932: }
10933: return %readonly_files;
10934: }
10935: # ------------------------------------------------------------ Unmark as Read Only
10936:
10937: sub unmark_as_readonly {
10938: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10939: # for portfolio submissions, $what contains [$symb,$crsid]
10940: my ($domain,$user,$what,$file_name,$group) = @_;
10941: $file_name = &declutter_portfile($file_name);
10942: my $symb_crs = $what;
10943: if (ref($what)) { $symb_crs=join('',@$what); }
10944: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10945: my ($tmp)=keys(%current_permissions);
10946: if ($tmp=~/^error:/) { undef(%current_permissions); }
10947: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10948: foreach my $file (@readonly_files) {
10949: my $clean_file = &declutter_portfile($file);
10950: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10951: my $current_locks = $current_permissions{$file};
10952: my @new_locks;
10953: my @del_keys;
10954: if (ref($current_locks) eq "ARRAY"){
10955: foreach my $locker (@{$current_locks}) {
10956: my $compare=$locker;
10957: if (ref($locker) eq 'ARRAY') {
10958: $compare=join('',@{$locker});
10959: if ($compare ne $symb_crs) {
10960: push(@new_locks, $locker);
10961: }
10962: }
10963: }
10964: if (scalar(@new_locks) > 0) {
10965: $current_permissions{$file} = \@new_locks;
10966: } else {
10967: push(@del_keys, $file);
10968: &del('file_permissions',\@del_keys, $domain, $user);
10969: delete($current_permissions{$file});
10970: }
10971: }
10972: }
10973: &put('file_permissions',\%current_permissions,$domain,$user);
10974: return;
10975: }
10976:
10977: # ------------------------------------------------------------ Directory lister
10978:
10979: sub dirlist {
10980: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10981: $uri=~s/^\///;
10982: $uri=~s/\/$//;
10983: my ($udom, $uname);
10984: if ($getuserdir) {
10985: $udom = $userdomain;
10986: $uname = $username;
10987: } else {
10988: (undef,$udom,$uname)=split(/\//,$uri);
10989: if(defined($userdomain)) {
10990: $udom = $userdomain;
10991: }
10992: if(defined($username)) {
10993: $uname = $username;
10994: }
10995: }
10996: my ($dirRoot,$listing,@listing_results);
10997:
10998: $dirRoot = $perlvar{'lonDocRoot'};
10999: if (defined($getpropath)) {
11000: $dirRoot = &propath($udom,$uname);
11001: $dirRoot =~ s/\/$//;
11002: } elsif (defined($getuserdir)) {
11003: my $subdir=$uname.'__';
11004: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
11005: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
11006: ."/$udom/$subdir/$uname";
11007: } elsif (defined($alternateRoot)) {
11008: $dirRoot = $alternateRoot;
11009: }
11010:
11011: if($udom) {
11012: if($uname) {
11013: my $uhome = &homeserver($uname,$udom);
11014: if ($uhome eq 'no_host') {
11015: return ([],'no_host');
11016: }
11017: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
11018: .$getuserdir.':'.&escape($dirRoot)
11019: .':'.&escape($uname).':'.&escape($udom),$uhome);
11020: if ($listing eq 'unknown_cmd') {
11021: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
11022: } else {
11023: @listing_results = map { &unescape($_); } split(/:/,$listing);
11024: }
11025: if ($listing eq 'unknown_cmd') {
11026: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
11027: @listing_results = split(/:/,$listing);
11028: } else {
11029: @listing_results = map { &unescape($_); } split(/:/,$listing);
11030: }
11031: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11032: ($listing eq 'rejected') || ($listing eq 'refused') ||
11033: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11034: return ([],$listing);
11035: } else {
11036: return (\@listing_results);
11037: }
11038: } elsif(!$alternateRoot) {
11039: my (%allusers,%listerror);
11040: my %servers = &get_servers($udom,'library');
11041: foreach my $tryserver (keys(%servers)) {
11042: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
11043: &escape($udom),$tryserver);
11044: if ($listing eq 'unknown_cmd') {
11045: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
11046: $udom, $tryserver);
11047: } else {
11048: @listing_results = map { &unescape($_); } split(/:/,$listing);
11049: }
11050: if ($listing eq 'unknown_cmd') {
11051: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
11052: $udom, $tryserver);
11053: @listing_results = split(/:/,$listing);
11054: } else {
11055: @listing_results =
11056: map { &unescape($_); } split(/:/,$listing);
11057: }
11058: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
11059: ($listing eq 'rejected') || ($listing eq 'refused') ||
11060: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
11061: $listerror{$tryserver} = $listing;
11062: } else {
11063: foreach my $line (@listing_results) {
11064: my ($entry) = split(/&/,$line,2);
11065: $allusers{$entry} = 1;
11066: }
11067: }
11068: }
11069: my @alluserslist=();
11070: foreach my $user (sort(keys(%allusers))) {
11071: push(@alluserslist,$user.'&user');
11072: }
11073: if (!%listerror) {
11074: # no errors
11075: return (\@alluserslist);
11076: } elsif (scalar(keys(%servers)) == 1) {
11077: # one library server, one error
11078: my ($key) = keys(%listerror);
11079: return (\@alluserslist, $listerror{$key});
11080: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
11081: # con_lost indicates that we might miss data from at least one
11082: # library server
11083: return (\@alluserslist, 'con_lost');
11084: } else {
11085: # multiple library servers and no con_lost -> data should be
11086: # complete.
11087: return (\@alluserslist);
11088: }
11089:
11090: } else {
11091: return ([],'missing username');
11092: }
11093: } elsif(!defined($getpropath)) {
11094: my $path = $perlvar{'lonDocRoot'}.'/res/';
11095: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
11096: return (\@all_domains);
11097: } else {
11098: return ([],'missing domain');
11099: }
11100: }
11101:
11102: # --------------------------------------------- GetFileTimestamp
11103: # This function utilizes dirlist and returns the date stamp for
11104: # when it was last modified. It will also return an error of -1
11105: # if an error occurs
11106:
11107: sub GetFileTimestamp {
11108: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11109: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11110: $studentName = &LONCAPA::clean_username($studentName);
11111: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11112: undef,$getuserdir);
11113: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11114: return -1;
11115: }
11116: if (ref($fileref) eq 'ARRAY') {
11117: my @stats = split('&',$fileref->[0]);
11118: # @stats contains first the filename, then the stat output
11119: return $stats[10]; # so this is 10 instead of 9.
11120: } else {
11121: return -1;
11122: }
11123: }
11124:
11125: sub stat_file {
11126: my ($uri) = @_;
11127: $uri = &clutter_with_no_wrapper($uri);
11128:
11129: my ($udom,$uname,$file);
11130: if ($uri =~ m-^/(uploaded|editupload)/-) {
11131: ($udom,$uname,$file) =
11132: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11133: $file = 'userfiles/'.$file;
11134: }
11135: if ($uri =~ m-^/res/-) {
11136: ($udom,$uname) =
11137: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11138: $file = $uri;
11139: }
11140:
11141: if (!$udom || !$uname || !$file) {
11142: # unable to handle the uri
11143: return ();
11144: }
11145: my $getpropath;
11146: if ($file =~ /^userfiles\//) {
11147: $getpropath = 1;
11148: }
11149: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11150: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11151: return ();
11152: } else {
11153: if (ref($listref) eq 'ARRAY') {
11154: my @stats = split('&',$listref->[0]);
11155: shift(@stats); #filename is first
11156: return @stats;
11157: }
11158: }
11159: return ();
11160: }
11161:
11162: # -------------------------------------------------------- Value of a Condition
11163:
11164: # gets the value of a specific preevaluated condition
11165: # stored in the string $env{user.state.<cid>}
11166: # or looks up a condition reference in the bighash and if if hasn't
11167: # already been evaluated recurses into docondval to get the value of
11168: # the condition, then memoizing it to
11169: # $env{user.state.<cid>.<condition>}
11170: sub directcondval {
11171: my $number=shift;
11172: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11173: &Apache::lonuserstate::evalstate();
11174: }
11175: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11176: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11177: } elsif ($number =~ /^_/) {
11178: my $sub_condition;
11179: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11180: &GDBM_READER(),0640)) {
11181: $sub_condition=$bighash{'conditions'.$number};
11182: untie(%bighash);
11183: }
11184: my $value = &docondval($sub_condition);
11185: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11186: return $value;
11187: }
11188: if ($env{'user.state.'.$env{'request.course.id'}}) {
11189: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11190: } else {
11191: return 2;
11192: }
11193: }
11194:
11195: # get the collection of conditions for this resource
11196: sub condval {
11197: my $condidx=shift;
11198: my $allpathcond='';
11199: foreach my $cond (split(/\|/,$condidx)) {
11200: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11201: $allpathcond.=
11202: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11203: }
11204: }
11205: $allpathcond=~s/\|$//;
11206: return &docondval($allpathcond);
11207: }
11208:
11209: #evaluates an expression of conditions
11210: sub docondval {
11211: my ($allpathcond) = @_;
11212: my $result=0;
11213: if ($env{'request.course.id'}
11214: && defined($allpathcond)) {
11215: my $operand='|';
11216: my @stack;
11217: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11218: if ($chunk eq '(') {
11219: push @stack,($operand,$result);
11220: } elsif ($chunk eq ')') {
11221: my $before=pop @stack;
11222: if (pop @stack eq '&') {
11223: $result=$result>$before?$before:$result;
11224: } else {
11225: $result=$result>$before?$result:$before;
11226: }
11227: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11228: $operand=$chunk;
11229: } else {
11230: my $new=directcondval($chunk);
11231: if ($operand eq '&') {
11232: $result=$result>$new?$new:$result;
11233: } else {
11234: $result=$result>$new?$result:$new;
11235: }
11236: }
11237: }
11238: }
11239: return $result;
11240: }
11241:
11242: # ---------------------------------------------------- Devalidate courseresdata
11243:
11244: sub devalidatecourseresdata {
11245: my ($coursenum,$coursedomain)=@_;
11246: my $hashid=$coursenum.':'.$coursedomain;
11247: &devalidate_cache_new('courseres',$hashid);
11248: }
11249:
11250:
11251: # --------------------------------------------------- Course Resourcedata Query
11252: #
11253: # Parameters:
11254: # $coursenum - Number of the course.
11255: # $coursedomain - Domain at which the course was created.
11256: # Returns:
11257: # A hash of the course parameters along (I think) with timestamps
11258: # and version info.
11259:
11260: sub get_courseresdata {
11261: my ($coursenum,$coursedomain)=@_;
11262: my $coursehom=&homeserver($coursenum,$coursedomain);
11263: my $hashid=$coursenum.':'.$coursedomain;
11264: my ($result,$cached)=&is_cached_new('courseres',$hashid);
11265: my %dumpreply;
11266: unless (defined($cached)) {
11267: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11268: $result=\%dumpreply;
11269: my ($tmp) = keys(%dumpreply);
11270: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11271: &do_cache_new('courseres',$hashid,$result,600);
11272: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11273: return $tmp;
11274: } elsif ($tmp =~ /^(error)/) {
11275: $result=undef;
11276: &do_cache_new('courseres',$hashid,$result,600);
11277: }
11278: }
11279: return $result;
11280: }
11281:
11282: sub devalidateuserresdata {
11283: my ($uname,$udom)=@_;
11284: my $hashid="$udom:$uname";
11285: &devalidate_cache_new('userres',$hashid);
11286: }
11287:
11288: sub get_userresdata {
11289: my ($uname,$udom)=@_;
11290: #most student don\'t have any data set, check if there is some data
11291: if (&EXT_cache_status($udom,$uname)) { return undef; }
11292:
11293: my $hashid="$udom:$uname";
11294: my ($result,$cached)=&is_cached_new('userres',$hashid);
11295: if (!defined($cached)) {
11296: my %resourcedata=&dump('resourcedata',$udom,$uname);
11297: $result=\%resourcedata;
11298: &do_cache_new('userres',$hashid,$result,600);
11299: }
11300: my ($tmp)=keys(%$result);
11301: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11302: return $result;
11303: }
11304: #error 2 occurs when the .db doesn't exist
11305: if ($tmp!~/error: 2 /) {
11306: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11307: &logthis("<font color=\"blue\">WARNING:".
11308: " Trying to get resource data for ".
11309: $uname." at ".$udom.": ".
11310: $tmp."</font>");
11311: }
11312: } elsif ($tmp=~/error: 2 /) {
11313: #&EXT_cache_set($udom,$uname);
11314: &do_cache_new('userres',$hashid,undef,600);
11315: undef($tmp); # not really an error so don't send it back
11316: }
11317: return $tmp;
11318: }
11319: #----------------------------------------------- resdata - return resource data
11320: # Purpose:
11321: # Return resource data for either users or for a course.
11322: # Parameters:
11323: # $name - Course/user name.
11324: # $domain - Name of the domain the user/course is registered on.
11325: # $type - Type of thing $name is (must be 'course' or 'user'
11326: # @which - Array of names of resources desired.
11327: # Returns:
11328: # The value of the first reasource in @which that is found in the
11329: # resource hash.
11330: # Exceptional Conditions:
11331: # If the $type passed in is not valid (not the string 'course' or
11332: # 'user', an undefined reference is returned.
11333: # If none of the resources are found, an undef is returned
11334: sub resdata {
11335: my ($name,$domain,$type,@which)=@_;
11336: my $result;
11337: if ($type eq 'course') {
11338: $result=&get_courseresdata($name,$domain);
11339: } elsif ($type eq 'user') {
11340: $result=&get_userresdata($name,$domain);
11341: }
11342: if (!ref($result)) { return $result; }
11343: foreach my $item (@which) {
11344: if (defined($result->{$item->[0]})) {
11345: return [$result->{$item->[0]},$item->[1]];
11346: }
11347: }
11348: return undef;
11349: }
11350:
11351: sub get_numsuppfiles {
11352: my ($cnum,$cdom,$ignorecache)=@_;
11353: my $hashid=$cnum.':'.$cdom;
11354: my ($suppcount,$cached);
11355: unless ($ignorecache) {
11356: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11357: }
11358: unless (defined($cached)) {
11359: my $chome=&homeserver($cnum,$cdom);
11360: unless ($chome eq 'no_host') {
11361: ($suppcount,my $errors) = (0,0);
11362: my $suppmap = 'supplemental.sequence';
11363: ($suppcount,$errors) =
11364: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11365: }
11366: &do_cache_new('suppcount',$hashid,$suppcount,600);
11367: }
11368: return $suppcount;
11369: }
11370:
11371: #
11372: # EXT resource caching routines
11373: #
11374:
11375: sub clear_EXT_cache_status {
11376: &delenv('cache.EXT.');
11377: }
11378:
11379: sub EXT_cache_status {
11380: my ($target_domain,$target_user) = @_;
11381: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11382: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11383: # We know already the user has no data
11384: return 1;
11385: } else {
11386: return 0;
11387: }
11388: }
11389:
11390: sub EXT_cache_set {
11391: my ($target_domain,$target_user) = @_;
11392: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11393: #&appenv({$cachename => time});
11394: }
11395:
11396: # --------------------------------------------------------- Value of a Variable
11397: sub EXT {
11398:
11399: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11400: unless ($varname) { return ''; }
11401: #get real user name/domain, courseid and symb
11402: my $courseid;
11403: my $publicuser;
11404: if ($symbparm) {
11405: $symbparm=&get_symb_from_alias($symbparm);
11406: }
11407: if (!($uname && $udom)) {
11408: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11409: if (!$symbparm) { $symbparm=$cursymb; }
11410: } else {
11411: $courseid=$env{'request.course.id'};
11412: }
11413: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11414: my $rest;
11415: if (defined($therest[0])) {
11416: $rest=join('.',@therest);
11417: } else {
11418: $rest='';
11419: }
11420:
11421: my $qualifierrest=$qualifier;
11422: if ($rest) { $qualifierrest.='.'.$rest; }
11423: my $spacequalifierrest=$space;
11424: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11425: if ($realm eq 'user') {
11426: # --------------------------------------------------------------- user.resource
11427: if ($space eq 'resource') {
11428: if ( (defined($Apache::lonhomework::parsing_a_problem)
11429: || defined($Apache::lonhomework::parsing_a_task))
11430: &&
11431: ($symbparm eq &symbread()) ) {
11432: # if we are in the middle of processing the resource the
11433: # get the value we are planning on committing
11434: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11435: return $Apache::lonhomework::results{$qualifierrest};
11436: } else {
11437: return $Apache::lonhomework::history{$qualifierrest};
11438: }
11439: } else {
11440: my %restored;
11441: if ($publicuser || $env{'request.state'} eq 'construct') {
11442: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11443: } else {
11444: %restored=&restore($symbparm,$courseid,$udom,$uname);
11445: }
11446: return $restored{$qualifierrest};
11447: }
11448: # ----------------------------------------------------------------- user.access
11449: } elsif ($space eq 'access') {
11450: # FIXME - not supporting calls for a specific user
11451: return &allowed($qualifier,$rest);
11452: # ------------------------------------------ user.preferences, user.environment
11453: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11454: if (($uname eq $env{'user.name'}) &&
11455: ($udom eq $env{'user.domain'})) {
11456: return $env{join('.',('environment',$qualifierrest))};
11457: } else {
11458: my %returnhash;
11459: if (!$publicuser) {
11460: %returnhash=&userenvironment($udom,$uname,
11461: $qualifierrest);
11462: }
11463: return $returnhash{$qualifierrest};
11464: }
11465: # ----------------------------------------------------------------- user.course
11466: } elsif ($space eq 'course') {
11467: # FIXME - not supporting calls for a specific user
11468: return $env{join('.',('request.course',$qualifier))};
11469: # ------------------------------------------------------------------- user.role
11470: } elsif ($space eq 'role') {
11471: # FIXME - not supporting calls for a specific user
11472: my ($role,$where)=split(/\./,$env{'request.role'});
11473: if ($qualifier eq 'value') {
11474: return $role;
11475: } elsif ($qualifier eq 'extent') {
11476: return $where;
11477: }
11478: # ----------------------------------------------------------------- user.domain
11479: } elsif ($space eq 'domain') {
11480: return $udom;
11481: # ------------------------------------------------------------------- user.name
11482: } elsif ($space eq 'name') {
11483: return $uname;
11484: # ---------------------------------------------------- Any other user namespace
11485: } else {
11486: my %reply;
11487: if (!$publicuser) {
11488: %reply=&get($space,[$qualifierrest],$udom,$uname);
11489: }
11490: return $reply{$qualifierrest};
11491: }
11492: } elsif ($realm eq 'query') {
11493: # ---------------------------------------------- pull stuff out of query string
11494: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11495: [$spacequalifierrest]);
11496: return $env{'form.'.$spacequalifierrest};
11497: } elsif ($realm eq 'request') {
11498: # ------------------------------------------------------------- request.browser
11499: if ($space eq 'browser') {
11500: return $env{'browser.'.$qualifier};
11501: # ------------------------------------------------------------ request.filename
11502: } else {
11503: return $env{'request.'.$spacequalifierrest};
11504: }
11505: } elsif ($realm eq 'course') {
11506: # ---------------------------------------------------------- course.description
11507: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11508: } elsif ($realm eq 'resource') {
11509:
11510: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11511: if (!$symbparm) { $symbparm=&symbread(); }
11512: }
11513:
11514: if ($qualifier eq '') {
11515: if ($space eq 'title') {
11516: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11517: return &gettitle($symbparm);
11518: }
11519:
11520: if ($space eq 'map') {
11521: my ($map) = &decode_symb($symbparm);
11522: return &symbread($map);
11523: }
11524: if ($space eq 'maptitle') {
11525: my ($map) = &decode_symb($symbparm);
11526: return &gettitle($map);
11527: }
11528: if ($space eq 'filename') {
11529: if ($symbparm) {
11530: return &clutter((&decode_symb($symbparm))[2]);
11531: }
11532: return &hreflocation('',$env{'request.filename'});
11533: }
11534:
11535: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11536: if ($space eq 'visibleparts') {
11537: my $navmap = Apache::lonnavmaps::navmap->new();
11538: my $item;
11539: if (ref($navmap)) {
11540: my $res = $navmap->getBySymb($symbparm);
11541: my $parts = $res->parts();
11542: if (ref($parts) eq 'ARRAY') {
11543: $item = join(',',@{$parts});
11544: }
11545: undef($navmap);
11546: }
11547: return $item;
11548: }
11549: }
11550: }
11551:
11552: my ($section, $group, @groups);
11553: my ($courselevelm,$courselevel);
11554: if (($courseid eq '') && ($cid)) {
11555: $courseid = $cid;
11556: }
11557: if (($symbparm && $courseid) &&
11558: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11559:
11560: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11561:
11562: # ----------------------------------------------------- Cascading lookup scheme
11563: my $symbp=$symbparm;
11564: my $mapp=&deversion((&decode_symb($symbp))[0]);
11565:
11566: my $symbparm=$symbp.'.'.$spacequalifierrest;
11567: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11568:
11569: if (($env{'user.name'} eq $uname) &&
11570: ($env{'user.domain'} eq $udom)) {
11571: $section=$env{'request.course.sec'};
11572: @groups = split(/:/,$env{'request.course.groups'});
11573: @groups=&sort_course_groups($courseid,@groups);
11574: } else {
11575: if (! defined($usection)) {
11576: $section=&getsection($udom,$uname,$courseid);
11577: } else {
11578: $section = $usection;
11579: }
11580: @groups = &get_users_groups($udom,$uname,$courseid);
11581: }
11582:
11583: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11584: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11585: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11586:
11587: $courselevel=$courseid.'.'.$spacequalifierrest;
11588: my $courselevelr=$courseid.'.'.$symbparm;
11589: $courselevelm=$courseid.'.'.$mapparm;
11590:
11591: # ----------------------------------------------------------- first, check user
11592:
11593: my $userreply=&resdata($uname,$udom,'user',
11594: ([$courselevelr,'resource'],
11595: [$courselevelm,'map' ],
11596: [$courselevel, 'course' ]));
11597: if (defined($userreply)) { return &get_reply($userreply); }
11598:
11599: # ------------------------------------------------ second, check some of course
11600: my $coursereply;
11601: if (@groups > 0) {
11602: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11603: $mapparm,$spacequalifierrest);
11604: if (defined($coursereply)) { return &get_reply($coursereply); }
11605: }
11606:
11607: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11608: $env{'course.'.$courseid.'.domain'},
11609: 'course',
11610: ([$seclevelr, 'resource'],
11611: [$seclevelm, 'map' ],
11612: [$seclevel, 'course' ],
11613: [$courselevelr,'resource']));
11614: if (defined($coursereply)) { return &get_reply($coursereply); }
11615:
11616: # ------------------------------------------------------ third, check map parms
11617: my %parmhash=();
11618: my $thisparm='';
11619: if (tie(%parmhash,'GDBM_File',
11620: $env{'request.course.fn'}.'_parms.db',
11621: &GDBM_READER(),0640)) {
11622: $thisparm=$parmhash{$symbparm};
11623: untie(%parmhash);
11624: }
11625: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11626: }
11627: # ------------------------------------------ fourth, look in resource metadata
11628:
11629: $spacequalifierrest=~s/\./\_/;
11630: my $filename;
11631: if (!$symbparm) { $symbparm=&symbread(); }
11632: if ($symbparm) {
11633: $filename=(&decode_symb($symbparm))[2];
11634: } else {
11635: $filename=$env{'request.filename'};
11636: }
11637: my $metadata=&metadata($filename,$spacequalifierrest);
11638: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11639: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11640: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11641:
11642: # ---------------------------------------------- fourth, look in rest of course
11643: if ($symbparm && defined($courseid) &&
11644: $courseid eq $env{'request.course.id'}) {
11645: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11646: $env{'course.'.$courseid.'.domain'},
11647: 'course',
11648: ([$courselevelm,'map' ],
11649: [$courselevel, 'course']));
11650: if (defined($coursereply)) { return &get_reply($coursereply); }
11651: }
11652: # ------------------------------------------------------------------ Cascade up
11653: unless ($space eq '0') {
11654: my @parts=split(/_/,$space);
11655: my $id=pop(@parts);
11656: my $part=join('_',@parts);
11657: if ($part eq '') { $part='0'; }
11658: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11659: $symbparm,$udom,$uname,$section,1);
11660: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11661: }
11662: if ($recurse) { return undef; }
11663: my $pack_def=&packages_tab_default($filename,$varname);
11664: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11665: # ---------------------------------------------------- Any other user namespace
11666: } elsif ($realm eq 'environment') {
11667: # ----------------------------------------------------------------- environment
11668: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11669: return $env{'environment.'.$spacequalifierrest};
11670: } else {
11671: if ($uname eq 'anonymous' && $udom eq '') {
11672: return '';
11673: }
11674: my %returnhash=&userenvironment($udom,$uname,
11675: $spacequalifierrest);
11676: return $returnhash{$spacequalifierrest};
11677: }
11678: } elsif ($realm eq 'system') {
11679: # ----------------------------------------------------------------- system.time
11680: if ($space eq 'time') {
11681: return time;
11682: }
11683: } elsif ($realm eq 'server') {
11684: # ----------------------------------------------------------------- system.time
11685: if ($space eq 'name') {
11686: return $ENV{'SERVER_NAME'};
11687: }
11688: }
11689: return '';
11690: }
11691:
11692: sub get_reply {
11693: my ($reply_value) = @_;
11694: if (ref($reply_value) eq 'ARRAY') {
11695: if (wantarray) {
11696: return @$reply_value;
11697: }
11698: return $reply_value->[0];
11699: } else {
11700: return $reply_value;
11701: }
11702: }
11703:
11704: sub check_group_parms {
11705: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11706: my @groupitems = ();
11707: my $resultitem;
11708: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11709: foreach my $group (@{$groups}) {
11710: foreach my $level (@levels) {
11711: my $item = $courseid.'.['.$group.'].'.$level->[0];
11712: push(@groupitems,[$item,$level->[1]]);
11713: }
11714: }
11715: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11716: $env{'course.'.$courseid.'.domain'},
11717: 'course',@groupitems);
11718: return $coursereply;
11719: }
11720:
11721: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11722: my ($courseid,@groups) = @_;
11723: @groups = sort(@groups);
11724: return @groups;
11725: }
11726:
11727: sub packages_tab_default {
11728: my ($uri,$varname)=@_;
11729: my (undef,$part,$name)=split(/\./,$varname);
11730:
11731: my (@extension,@specifics,$do_default);
11732: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11733: my ($pack_type,$pack_part)=split(/_/,$package,2);
11734: if ($pack_type eq 'default') {
11735: $do_default=1;
11736: } elsif ($pack_type eq 'extension') {
11737: push(@extension,[$package,$pack_type,$pack_part]);
11738: } elsif ($pack_part eq $part || $pack_type eq 'part') {
11739: # only look at packages defaults for packages that this id is
11740: push(@specifics,[$package,$pack_type,$pack_part]);
11741: }
11742: }
11743: # first look for a package that matches the requested part id
11744: foreach my $package (@specifics) {
11745: my (undef,$pack_type,$pack_part)=@{$package};
11746: next if ($pack_part ne $part);
11747: if (defined($packagetab{"$pack_type&$name&default"})) {
11748: return $packagetab{"$pack_type&$name&default"};
11749: }
11750: }
11751: # look for any possible matching non extension_ package
11752: foreach my $package (@specifics) {
11753: my (undef,$pack_type,$pack_part)=@{$package};
11754: if (defined($packagetab{"$pack_type&$name&default"})) {
11755: return $packagetab{"$pack_type&$name&default"};
11756: }
11757: if ($pack_type eq 'part') { $pack_part='0'; }
11758: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11759: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11760: }
11761: }
11762: # look for any posible extension_ match
11763: foreach my $package (@extension) {
11764: my ($package,$pack_type)=@{$package};
11765: if (defined($packagetab{"$pack_type&$name&default"})) {
11766: return $packagetab{"$pack_type&$name&default"};
11767: }
11768: if (defined($packagetab{$package."&$name&default"})) {
11769: return $packagetab{$package."&$name&default"};
11770: }
11771: }
11772: # look for a global default setting
11773: if ($do_default && defined($packagetab{"default&$name&default"})) {
11774: return $packagetab{"default&$name&default"};
11775: }
11776: return undef;
11777: }
11778:
11779: sub add_prefix_and_part {
11780: my ($prefix,$part)=@_;
11781: my $keyroot;
11782: if (defined($prefix) && $prefix !~ /^__/) {
11783: # prefix that has a part already
11784: $keyroot=$prefix;
11785: } elsif (defined($prefix)) {
11786: # prefix that is missing a part
11787: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11788: } else {
11789: # no prefix at all
11790: if (defined($part)) { $keyroot='_'.$part; }
11791: }
11792: return $keyroot;
11793: }
11794:
11795: # ---------------------------------------------------------------- Get metadata
11796:
11797: my %metaentry;
11798: my %importedpartids;
11799: my %importedrespids;
11800: sub metadata {
11801: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11802: $uri=&declutter($uri);
11803: # if it is a non metadata possible uri return quickly
11804: if (($uri eq '') ||
11805: (($uri =~ m|^/*adm/|) &&
11806: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
11807: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11808: return undef;
11809: }
11810: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
11811: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11812: return undef;
11813: }
11814: my $filename=$uri;
11815: $uri=~s/\.meta$//;
11816: #
11817: # Is the metadata already cached?
11818: # Look at timestamp of caching
11819: # Everything is cached by the main uri, libraries are never directly cached
11820: #
11821: if (!defined($liburi)) {
11822: my ($result,$cached)=&is_cached_new('meta',$uri);
11823: if (defined($cached)) { return $result->{':'.$what}; }
11824: }
11825: {
11826: # Imported parts would go here
11827: my @origfiletagids=();
11828: my $importedparts=0;
11829:
11830: # Imported responseids would go here
11831: my $importedresponses=0;
11832: #
11833: # Is this a recursive call for a library?
11834: #
11835: # if (! exists($metacache{$uri})) {
11836: # $metacache{$uri}={};
11837: # }
11838: my $cachetime = 60*60;
11839: if ($liburi) {
11840: $liburi=&declutter($liburi);
11841: $filename=$liburi;
11842: } else {
11843: &devalidate_cache_new('meta',$uri);
11844: undef(%metaentry);
11845: }
11846: my %metathesekeys=();
11847: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11848: my $metastring;
11849: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11850: my $which = &hreflocation('','/'.($liburi || $uri));
11851: $metastring =
11852: &Apache::lonnet::ssi_body($which,
11853: ('grade_target' => 'meta'));
11854: $cachetime = 1; # only want this cached in the child not long term
11855: } elsif (($uri !~ m -^(editupload)/-) &&
11856: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11857: my $file=&filelocation('',&clutter($filename));
11858: #push(@{$metaentry{$uri.'.file'}},$file);
11859: $metastring=&getfile($file);
11860: }
11861: my $parser=HTML::LCParser->new(\$metastring);
11862: my $token;
11863: undef %metathesekeys;
11864: while ($token=$parser->get_token) {
11865: if ($token->[0] eq 'S') {
11866: if (defined($token->[2]->{'package'})) {
11867: #
11868: # This is a package - get package info
11869: #
11870: my $package=$token->[2]->{'package'};
11871: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11872: if (defined($token->[2]->{'id'})) {
11873: $keyroot.='_'.$token->[2]->{'id'};
11874: }
11875: if ($metaentry{':packages'}) {
11876: $metaentry{':packages'}.=','.$package.$keyroot;
11877: } else {
11878: $metaentry{':packages'}=$package.$keyroot;
11879: }
11880: foreach my $pack_entry (keys(%packagetab)) {
11881: my $part=$keyroot;
11882: $part=~s/^\_//;
11883: if ($pack_entry=~/^\Q$package\E\&/ ||
11884: $pack_entry=~/^\Q$package\E_0\&/) {
11885: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11886: # ignore package.tab specified default values
11887: # here &package_tab_default() will fetch those
11888: if ($subp eq 'default') { next; }
11889: my $value=$packagetab{$pack_entry};
11890: my $unikey;
11891: if ($pack =~ /_0$/) {
11892: $unikey='parameter_0_'.$name;
11893: $part=0;
11894: } else {
11895: $unikey='parameter'.$keyroot.'_'.$name;
11896: }
11897: if ($subp eq 'display') {
11898: $value.=' [Part: '.$part.']';
11899: }
11900: $metaentry{':'.$unikey.'.part'}=$part;
11901: $metathesekeys{$unikey}=1;
11902: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11903: $metaentry{':'.$unikey.'.'.$subp}=$value;
11904: }
11905: if (defined($metaentry{':'.$unikey.'.default'})) {
11906: $metaentry{':'.$unikey}=
11907: $metaentry{':'.$unikey.'.default'};
11908: }
11909: }
11910: }
11911: } else {
11912: #
11913: # This is not a package - some other kind of start tag
11914: #
11915: my $entry=$token->[1];
11916: my $unikey='';
11917:
11918: if ($entry eq 'import') {
11919: #
11920: # Importing a library here
11921: #
11922: my $location=$parser->get_text('/import');
11923: my $dir=$filename;
11924: $dir=~s|[^/]*$||;
11925: $location=&filelocation($dir,$location);
11926:
11927: my $importid=$token->[2]->{'id'};
11928: my $importmode=$token->[2]->{'importmode'};
11929: #
11930: # Check metadata for imported file to
11931: # see if it contained response items
11932: #
11933: my %currmetaentry = %metaentry;
11934: my $libresponseorder = &metadata($location,'responseorder');
11935: my $origfile;
11936: if ($libresponseorder ne '') {
11937: if ($#origfiletagids<0) {
11938: undef(%importedrespids);
11939: undef(%importedpartids);
11940: }
11941: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11942: if (@{$importedrespids{$importid}} > 0) {
11943: $importedresponses = 1;
11944: # We need to get the original file and the imported file to get the response order correct
11945: # Load and inspect original file
11946: if ($#origfiletagids<0) {
11947: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11948: $origfile=&getfile($origfilelocation);
11949: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11950: }
11951: }
11952: }
11953: # Do not overwrite contents of %metaentry hash for resource itself with
11954: # hash populated for imported library file
11955: %metaentry = %currmetaentry;
11956: undef(%currmetaentry);
11957: if ($importmode eq 'problem') {
11958: # Import as problem/response
11959: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11960: } elsif ($importmode eq 'part') {
11961: # Import as part(s)
11962: $importedparts=1;
11963: # We need to get the original file and the imported file to get the part order correct
11964: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11965: # Load and inspect original file if we didn't do that already
11966: if ($#origfiletagids<0) {
11967: undef(%importedrespids);
11968: undef(%importedpartids);
11969: if ($origfile eq '') {
11970: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11971: $origfile=&getfile($origfilelocation);
11972: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11973: }
11974: }
11975:
11976: # Load and inspect imported file
11977: my $impfile=&getfile($location);
11978: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11979: if ($#impfilepartids>=0) {
11980: # This problem had parts
11981: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11982: } else {
11983: # Importing by turning a single problem into a problem part
11984: # It gets the import-tags ID as part-ID
11985: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11986: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11987: }
11988: } else {
11989: # Normal import
11990: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11991: if (defined($token->[2]->{'id'})) {
11992: $unikey.='_'.$token->[2]->{'id'};
11993: }
11994: }
11995:
11996: if ($depthcount<20) {
11997: my $metadata =
11998: &metadata($uri,'keys', $location,$unikey,
11999: $depthcount+1);
12000: foreach my $meta (split(',',$metadata)) {
12001: $metaentry{':'.$meta}=$metaentry{':'.$meta};
12002: $metathesekeys{$meta}=1;
12003: }
12004:
12005: }
12006: } else {
12007: #
12008: # Not importing, some other kind of non-package, non-library start tag
12009: #
12010: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
12011: if (defined($token->[2]->{'id'})) {
12012: $unikey.='_'.$token->[2]->{'id'};
12013: }
12014: if (defined($token->[2]->{'name'})) {
12015: $unikey.='_'.$token->[2]->{'name'};
12016: }
12017: $metathesekeys{$unikey}=1;
12018: foreach my $param (@{$token->[3]}) {
12019: $metaentry{':'.$unikey.'.'.$param} =
12020: $token->[2]->{$param};
12021: }
12022: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
12023: my $default=$metaentry{':'.$unikey.'.default'};
12024: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
12025: # only ws inside the tag, and not in default, so use default
12026: # as value
12027: $metaentry{':'.$unikey}=$default;
12028: } elsif ( $internaltext =~ /\S/ ) {
12029: # something interesting inside the tag
12030: $metaentry{':'.$unikey}=$internaltext;
12031: } else {
12032: # no interesting values, don't set a default
12033: }
12034: # end of not-a-package not-a-library import
12035: }
12036: # end of not-a-package start tag
12037: }
12038: # the next is the end of "start tag"
12039: }
12040: }
12041: my ($extension) = ($uri =~ /\.(\w+)$/);
12042: $extension = lc($extension);
12043: if ($extension eq 'htm') { $extension='html'; }
12044:
12045: foreach my $key (keys(%packagetab)) {
12046: #no specific packages #how's our extension
12047: if ($key!~/^extension_\Q$extension\E&/) { next; }
12048: &metadata_create_package_def($uri,$key,'extension_'.$extension,
12049: \%metathesekeys);
12050: }
12051:
12052: if (!exists($metaentry{':packages'})
12053: || $packagetab{"import_defaults&extension_$extension"}) {
12054: foreach my $key (keys(%packagetab)) {
12055: #no specific packages well let's get default then
12056: if ($key!~/^default&/) { next; }
12057: &metadata_create_package_def($uri,$key,'default',
12058: \%metathesekeys);
12059: }
12060: }
12061: # are there custom rights to evaluate
12062: if ($metaentry{':copyright'} eq 'custom') {
12063:
12064: #
12065: # Importing a rights file here
12066: #
12067: unless ($depthcount) {
12068: my $location=$metaentry{':customdistributionfile'};
12069: my $dir=$filename;
12070: $dir=~s|[^/]*$||;
12071: $location=&filelocation($dir,$location);
12072: my $rights_metadata =
12073: &metadata($uri,'keys',$location,'_rights',
12074: $depthcount+1);
12075: foreach my $rights (split(',',$rights_metadata)) {
12076: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
12077: $metathesekeys{$rights}=1;
12078: }
12079: }
12080: }
12081: # uniqifiy package listing
12082: my %seen;
12083: my @uniq_packages =
12084: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
12085: $metaentry{':packages'} = join(',',@uniq_packages);
12086:
12087: if (($importedresponses) || ($importedparts)) {
12088: if ($importedparts) {
12089: # We had imported parts and need to rebuild partorder
12090: $metaentry{':partorder'}='';
12091: $metathesekeys{'partorder'}=1;
12092: }
12093: if ($importedresponses) {
12094: # We had imported responses and need to rebuild responseorder
12095: $metaentry{':responseorder'}='';
12096: $metathesekeys{'responseorder'}=1;
12097: }
12098: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12099: my $origid = $origfiletagids[$index+1];
12100: if ($origfiletagids[$index] eq 'part') {
12101: # Original part, part of the problem
12102: if ($importedparts) {
12103: $metaentry{':partorder'}.=','.$origid;
12104: }
12105: } elsif ($origfiletagids[$index] eq 'import') {
12106: if ($importedparts) {
12107: # We have imported parts at this position
12108: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12109: }
12110: if ($importedresponses) {
12111: # We have imported responses at this position
12112: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12113: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12114: }
12115: }
12116: } else {
12117: # Original response item, part of the problem
12118: if ($importedresponses) {
12119: $metaentry{':responseorder'}.=','.$origid;
12120: }
12121: }
12122: }
12123: if ($importedparts) {
12124: $metaentry{':partorder'}=~s/^\,//;
12125: }
12126: if ($importedresponses) {
12127: $metaentry{':responseorder'}=~s/^\,//;
12128: }
12129: }
12130:
12131: $metaentry{':keys'} = join(',',keys(%metathesekeys));
12132: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12133: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12134: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12135: # this is the end of "was not already recently cached
12136: }
12137: return $metaentry{':'.$what};
12138: }
12139:
12140: sub metadata_create_package_def {
12141: my ($uri,$key,$package,$metathesekeys)=@_;
12142: my ($pack,$name,$subp)=split(/\&/,$key);
12143: if ($subp eq 'default') { next; }
12144:
12145: if (defined($metaentry{':packages'})) {
12146: $metaentry{':packages'}.=','.$package;
12147: } else {
12148: $metaentry{':packages'}=$package;
12149: }
12150: my $value=$packagetab{$key};
12151: my $unikey;
12152: $unikey='parameter_0_'.$name;
12153: $metaentry{':'.$unikey.'.part'}=0;
12154: $$metathesekeys{$unikey}=1;
12155: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12156: $metaentry{':'.$unikey.'.'.$subp}=$value;
12157: }
12158: if (defined($metaentry{':'.$unikey.'.default'})) {
12159: $metaentry{':'.$unikey}=
12160: $metaentry{':'.$unikey.'.default'};
12161: }
12162: }
12163:
12164: sub metadata_generate_part0 {
12165: my ($metadata,$metacache,$uri) = @_;
12166: my %allnames;
12167: foreach my $metakey (keys(%$metadata)) {
12168: if ($metakey=~/^parameter\_(.*)/) {
12169: my $part=$$metacache{':'.$metakey.'.part'};
12170: my $name=$$metacache{':'.$metakey.'.name'};
12171: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12172: $allnames{$name}=$part;
12173: }
12174: }
12175: }
12176: foreach my $name (keys(%allnames)) {
12177: $$metadata{"parameter_0_$name"}=1;
12178: my $key=":parameter_0_$name";
12179: $$metacache{"$key.part"}='0';
12180: $$metacache{"$key.name"}=$name;
12181: $$metacache{"$key.type"}=$$metacache{':parameter_'.
12182: $allnames{$name}.'_'.$name.
12183: '.type'};
12184: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12185: '.display'};
12186: my $expr='[Part: '.$allnames{$name}.']';
12187: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12188: $$metacache{"$key.display"}=$olddis;
12189: }
12190: }
12191:
12192: # ------------------------------------------------------ Devalidate title cache
12193:
12194: sub devalidate_title_cache {
12195: my ($url)=@_;
12196: if (!$env{'request.course.id'}) { return; }
12197: my $symb=&symbread($url);
12198: if (!$symb) { return; }
12199: my $key=$env{'request.course.id'}."\0".$symb;
12200: &devalidate_cache_new('title',$key);
12201: }
12202:
12203: # ------------------------------------------------- Get the title of a course
12204:
12205: sub current_course_title {
12206: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12207: }
12208: # ------------------------------------------------- Get the title of a resource
12209:
12210: sub gettitle {
12211: my $urlsymb=shift;
12212: my $symb=&symbread($urlsymb);
12213: if ($symb) {
12214: my $key=$env{'request.course.id'}."\0".$symb;
12215: my ($result,$cached)=&is_cached_new('title',$key);
12216: if (defined($cached)) {
12217: return $result;
12218: }
12219: my ($map,$resid,$url)=&decode_symb($symb);
12220: my $title='';
12221: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12222: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12223: } else {
12224: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12225: &GDBM_READER(),0640)) {
12226: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12227: $title=$bighash{'title_'.$mapid.'.'.$resid};
12228: untie(%bighash);
12229: }
12230: }
12231: $title=~s/\&colon\;/\:/gs;
12232: if ($title) {
12233: # Remember both $symb and $title for dynamic metadata
12234: $accesshash{$symb.'___crstitle'}=$title;
12235: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12236: # Cache this title and then return it
12237: return &do_cache_new('title',$key,$title,600);
12238: }
12239: $urlsymb=$url;
12240: }
12241: my $title=&metadata($urlsymb,'title');
12242: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12243: return $title;
12244: }
12245:
12246: sub get_slot {
12247: my ($which,$cnum,$cdom)=@_;
12248: if (!$cnum || !$cdom) {
12249: (undef,my $courseid)=&whichuser();
12250: $cdom=$env{'course.'.$courseid.'.domain'};
12251: $cnum=$env{'course.'.$courseid.'.num'};
12252: }
12253: my $key=join("\0",'slots',$cdom,$cnum,$which);
12254: my %slotinfo;
12255: if (exists($remembered{$key})) {
12256: $slotinfo{$which} = $remembered{$key};
12257: } else {
12258: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12259: &Apache::lonhomework::showhash(%slotinfo);
12260: my ($tmp)=keys(%slotinfo);
12261: if ($tmp=~/^error:/) { return (); }
12262: $remembered{$key} = $slotinfo{$which};
12263: }
12264: if (ref($slotinfo{$which}) eq 'HASH') {
12265: return %{$slotinfo{$which}};
12266: }
12267: return $slotinfo{$which};
12268: }
12269:
12270: sub get_reservable_slots {
12271: my ($cnum,$cdom,$uname,$udom) = @_;
12272: my $now = time;
12273: my $reservable_info;
12274: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12275: if (exists($remembered{$key})) {
12276: $reservable_info = $remembered{$key};
12277: } else {
12278: my %resv;
12279: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12280: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12281: $reservable_info = \%resv;
12282: $remembered{$key} = $reservable_info;
12283: }
12284: return $reservable_info;
12285: }
12286:
12287: sub get_course_slots {
12288: my ($cnum,$cdom) = @_;
12289: my $hashid=$cnum.':'.$cdom;
12290: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12291: if (defined($cached)) {
12292: if (ref($result) eq 'HASH') {
12293: return %{$result};
12294: }
12295: } else {
12296: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12297: my ($tmp) = keys(%slots);
12298: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12299: &do_cache_new('allslots',$hashid,\%slots,600);
12300: return %slots;
12301: }
12302: }
12303: return;
12304: }
12305:
12306: sub devalidate_slots_cache {
12307: my ($cnum,$cdom)=@_;
12308: my $hashid=$cnum.':'.$cdom;
12309: &devalidate_cache_new('allslots',$hashid);
12310: }
12311:
12312: sub get_coursechange {
12313: my ($cdom,$cnum) = @_;
12314: if ($cdom eq '' || $cnum eq '') {
12315: return unless ($env{'request.course.id'});
12316: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12317: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12318: }
12319: my $hashid=$cdom.'_'.$cnum;
12320: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12321: if ((defined($cached)) && ($change ne '')) {
12322: return $change;
12323: } else {
12324: my %crshash;
12325: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12326: if ($crshash{'internal.contentchange'} eq '') {
12327: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12328: if ($change eq '') {
12329: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12330: $change = $crshash{'internal.created'};
12331: }
12332: } else {
12333: $change = $crshash{'internal.contentchange'};
12334: }
12335: my $cachetime = 600;
12336: &do_cache_new('crschange',$hashid,$change,$cachetime);
12337: }
12338: return $change;
12339: }
12340:
12341: sub devalidate_coursechange_cache {
12342: my ($cnum,$cdom)=@_;
12343: my $hashid=$cnum.':'.$cdom;
12344: &devalidate_cache_new('crschange',$hashid);
12345: }
12346:
12347: # ------------------------------------------------- Update symbolic store links
12348:
12349: sub symblist {
12350: my ($mapname,%newhash)=@_;
12351: $mapname=&deversion(&declutter($mapname));
12352: my %hash;
12353: if (($env{'request.course.fn'}) && (%newhash)) {
12354: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12355: &GDBM_WRCREAT(),0640)) {
12356: foreach my $url (keys(%newhash)) {
12357: next if ($url eq 'last_known'
12358: && $env{'form.no_update_last_known'});
12359: $hash{declutter($url)}=&encode_symb($mapname,
12360: $newhash{$url}->[1],
12361: $newhash{$url}->[0]);
12362: }
12363: if (untie(%hash)) {
12364: return 'ok';
12365: }
12366: }
12367: }
12368: return 'error';
12369: }
12370:
12371: # --------------------------------------------------------------- Verify a symb
12372:
12373: sub symbverify {
12374: my ($symb,$thisurl,$encstate)=@_;
12375: my $thisfn=$thisurl;
12376: $thisfn=&declutter($thisfn);
12377: # direct jump to resource in page or to a sequence - will construct own symbs
12378: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12379: # check URL part
12380: my ($map,$resid,$url)=&decode_symb($symb);
12381:
12382: unless ($url eq $thisfn) { return 0; }
12383:
12384: $symb=&symbclean($symb);
12385: $thisurl=&deversion($thisurl);
12386: $thisfn=&deversion($thisfn);
12387:
12388: my %bighash;
12389: my $okay=0;
12390:
12391: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12392: &GDBM_READER(),0640)) {
12393: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12394: $thisurl =~ s/\?.+$//;
12395: if ($map =~ m{^uploaded/.+\.page$}) {
12396: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12397: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12398: }
12399: }
12400: my $ids;
12401: if ($map =~ m{^uploaded/.+\.page$}) {
12402: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12403: } else {
12404: $ids=$bighash{'ids_'.&clutter($thisurl)};
12405: }
12406: unless ($ids) {
12407: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12408: $ids=$bighash{$idkey};
12409: }
12410: if ($ids) {
12411: # ------------------------------------------------------------------- Has ID(s)
12412: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12413: $symb =~ s/\?.+$//;
12414: }
12415: foreach my $id (split(/\,/,$ids)) {
12416: my ($mapid,$resid)=split(/\./,$id);
12417: if (
12418: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12419: eq $symb) {
12420: if (ref($encstate)) {
12421: $$encstate = $bighash{'encrypted_'.$id};
12422: }
12423: if (($env{'request.role.adv'}) ||
12424: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12425: ($thisurl eq '/adm/navmaps')) {
12426: $okay=1;
12427: last;
12428: }
12429: }
12430: }
12431: }
12432: untie(%bighash);
12433: }
12434: return $okay;
12435: }
12436:
12437: # --------------------------------------------------------------- Clean-up symb
12438:
12439: sub symbclean {
12440: my $symb=shift;
12441: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12442: # remove version from map
12443: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12444:
12445: # remove version from URL
12446: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12447:
12448: # remove wrapper
12449:
12450: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12451: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12452: return $symb;
12453: }
12454:
12455: # ---------------------------------------------- Split symb to find map and url
12456:
12457: sub encode_symb {
12458: my ($map,$resid,$url)=@_;
12459: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12460: }
12461:
12462: sub decode_symb {
12463: my $symb=shift;
12464: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12465: my ($map,$resid,$url)=split(/___/,$symb);
12466: return (&fixversion($map),$resid,&fixversion($url));
12467: }
12468:
12469: sub fixversion {
12470: my $fn=shift;
12471: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12472: my %bighash;
12473: my $uri=&clutter($fn);
12474: my $key=$env{'request.course.id'}.'_'.$uri;
12475: # is this cached?
12476: my ($result,$cached)=&is_cached_new('courseresversion',$key);
12477: if (defined($cached)) { return $result; }
12478: # unfortunately not cached, or expired
12479: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12480: &GDBM_READER(),0640)) {
12481: if ($bighash{'version_'.$uri}) {
12482: my $version=$bighash{'version_'.$uri};
12483: unless (($version eq 'mostrecent') ||
12484: ($version==&getversion($uri))) {
12485: $uri=~s/\.(\w+)$/\.$version\.$1/;
12486: }
12487: }
12488: untie %bighash;
12489: }
12490: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12491: }
12492:
12493: sub deversion {
12494: my $url=shift;
12495: $url=~s/\.\d+\.(\w+)$/\.$1/;
12496: return $url;
12497: }
12498:
12499: # ------------------------------------------------------ Return symb list entry
12500:
12501: sub symbread {
12502: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles,
12503: $ignoresymbdb,$noenccheck)=@_;
12504: my $cache_str='request.symbread.cached.'.$thisfn;
12505: if (defined($env{$cache_str})) {
12506: unless (ref($possibles) eq 'HASH') {
12507: if ($ignorecachednull) {
12508: return $env{$cache_str} unless ($env{$cache_str} eq '');
12509: } else {
12510: return $env{$cache_str};
12511: }
12512: }
12513: }
12514: # no filename provided? try from environment
12515: unless ($thisfn) {
12516: if ($env{'request.symb'}) {
12517: return $env{$cache_str}=&symbclean($env{'request.symb'});
12518: }
12519: $thisfn=$env{'request.filename'};
12520: }
12521: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12522: # is that filename actually a symb? Verify, clean, and return
12523: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12524: if (&symbverify($thisfn,$1)) {
12525: return $env{$cache_str}=&symbclean($thisfn);
12526: }
12527: }
12528: $thisfn=declutter($thisfn);
12529: my %hash;
12530: my %bighash;
12531: my $syval='';
12532: if (($env{'request.course.fn'}) && ($thisfn)) {
12533: my $targetfn = $thisfn;
12534: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12535: $targetfn = 'adm/wrapper/'.$thisfn;
12536: }
12537: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12538: $targetfn=$1;
12539: }
12540: unless ($ignoresymbdb) {
12541: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12542: &GDBM_READER(),0640)) {
12543: $syval=$hash{$targetfn};
12544: untie(%hash);
12545: }
12546: if ($syval && $checkforblock) {
12547: my @blockers = &has_comm_blocking('bre',$syval,$thisfn,$ignoresymbdb,$noenccheck);
12548: if (@blockers) {
12549: $syval='';
12550: }
12551: }
12552: }
12553: # ---------------------------------------------------------- There was an entry
12554: if ($syval) {
12555: #unless ($syval=~/\_\d+$/) {
12556: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12557: #&appenv({'request.ambiguous' => $thisfn});
12558: #return $env{$cache_str}='';
12559: #}
12560: #$syval.=$1;
12561: #}
12562: } else {
12563: # ------------------------------------------------------- Was not in symb table
12564: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12565: &GDBM_READER(),0640)) {
12566: # ---------------------------------------------- Get ID(s) for current resource
12567: my $ids=$bighash{'ids_'.&clutter($thisfn)};
12568: unless ($ids) {
12569: $ids=$bighash{'ids_/'.$thisfn};
12570: }
12571: unless ($ids) {
12572: # alias?
12573: $ids=$bighash{'mapalias_'.$thisfn};
12574: }
12575: if ($ids) {
12576: # ------------------------------------------------------------------- Has ID(s)
12577: my @possibilities=split(/\,/,$ids);
12578: if ($#possibilities==0) {
12579: # ----------------------------------------------- There is only one possibility
12580: my ($mapid,$resid)=split(/\./,$ids);
12581: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12582: $resid,$thisfn);
12583: if (ref($possibles) eq 'HASH') {
12584: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12585: $possibles->{$syval} = 1;
12586: }
12587: }
12588: if ($checkforblock) {
12589: unless ($bighash{'randomout_'.$ids} || $env{'request.role.adv'}) {
12590: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids},'',$noenccheck);
12591: if (@blockers) {
12592: $syval = '';
12593: untie(%bighash);
12594: return $env{$cache_str}='';
12595: }
12596: }
12597: }
12598: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12599: # ------------------------------------------ There is more than one possibility
12600: my $realpossible=0;
12601: foreach my $id (@possibilities) {
12602: my $file=$bighash{'src_'.$id};
12603: my $canaccess;
12604: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12605: $canaccess = 1;
12606: } else {
12607: $canaccess = &allowed('bre',$file);
12608: }
12609: if ($canaccess) {
12610: my ($mapid,$resid)=split(/\./,$id);
12611: if ($bighash{'map_type_'.$mapid} ne 'page') {
12612: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12613: $resid,$thisfn);
12614: next if ($bighash{'randomout_'.$id} && !$env{'request.role.adv'});
12615: next unless (($noenccheck) || ($bighash{'encrypted_'.$id} eq $env{'request.enc'}));
12616: if ($checkforblock) {
12617: my @blockers = &has_comm_blocking('bre',$poss_syval,$file,'',$noenccheck);
12618: if (@blockers > 0) {
12619: $syval = '';
12620: } else {
12621: $syval = $poss_syval;
12622: $realpossible++;
12623: }
12624: } else {
12625: $syval = $poss_syval;
12626: $realpossible++;
12627: }
12628: if ($syval) {
12629: if (ref($possibles) eq 'HASH') {
12630: $possibles->{$syval} = 1;
12631: }
12632: }
12633: }
12634: }
12635: }
12636: if ($realpossible!=1) { $syval=''; }
12637: } else {
12638: $syval='';
12639: }
12640: }
12641: untie(%bighash);
12642: }
12643: }
12644: if ($syval) {
12645: return $env{$cache_str}=$syval;
12646: }
12647: }
12648: &appenv({'request.ambiguous' => $thisfn});
12649: return $env{$cache_str}='';
12650: }
12651:
12652: # ---------------------------------------------------------- Return random seed
12653:
12654: sub numval {
12655: my $txt=shift;
12656: $txt=~tr/A-J/0-9/;
12657: $txt=~tr/a-j/0-9/;
12658: $txt=~tr/K-T/0-9/;
12659: $txt=~tr/k-t/0-9/;
12660: $txt=~tr/U-Z/0-5/;
12661: $txt=~tr/u-z/0-5/;
12662: $txt=~s/\D//g;
12663: if ($_64bit) { if ($txt > 2**32) { return -1; } }
12664: return int($txt);
12665: }
12666:
12667: sub numval2 {
12668: my $txt=shift;
12669: $txt=~tr/A-J/0-9/;
12670: $txt=~tr/a-j/0-9/;
12671: $txt=~tr/K-T/0-9/;
12672: $txt=~tr/k-t/0-9/;
12673: $txt=~tr/U-Z/0-5/;
12674: $txt=~tr/u-z/0-5/;
12675: $txt=~s/\D//g;
12676: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12677: my $total;
12678: foreach my $val (@txts) { $total+=$val; }
12679: if ($_64bit) { if ($total > 2**32) { return -1; } }
12680: return int($total);
12681: }
12682:
12683: sub numval3 {
12684: use integer;
12685: my $txt=shift;
12686: $txt=~tr/A-J/0-9/;
12687: $txt=~tr/a-j/0-9/;
12688: $txt=~tr/K-T/0-9/;
12689: $txt=~tr/k-t/0-9/;
12690: $txt=~tr/U-Z/0-5/;
12691: $txt=~tr/u-z/0-5/;
12692: $txt=~s/\D//g;
12693: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12694: my $total;
12695: foreach my $val (@txts) { $total+=$val; }
12696: if ($_64bit) { $total=(($total<<32)>>32); }
12697: return $total;
12698: }
12699:
12700: sub digest {
12701: my ($data)=@_;
12702: my $digest=&Digest::MD5::md5($data);
12703: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12704: my ($e,$f);
12705: {
12706: use integer;
12707: $e=($a+$b);
12708: $f=($c+$d);
12709: if ($_64bit) {
12710: $e=(($e<<32)>>32);
12711: $f=(($f<<32)>>32);
12712: }
12713: }
12714: if (wantarray) {
12715: return ($e,$f);
12716: } else {
12717: my $g;
12718: {
12719: use integer;
12720: $g=($e+$f);
12721: if ($_64bit) {
12722: $g=(($g<<32)>>32);
12723: }
12724: }
12725: return $g;
12726: }
12727: }
12728:
12729: sub latest_rnd_algorithm_id {
12730: return '64bit5';
12731: }
12732:
12733: sub get_rand_alg {
12734: my ($courseid)=@_;
12735: if (!$courseid) { $courseid=(&whichuser())[1]; }
12736: if ($courseid) {
12737: return $env{"course.$courseid.rndseed"};
12738: }
12739: return &latest_rnd_algorithm_id();
12740: }
12741:
12742: sub validCODE {
12743: my ($CODE)=@_;
12744: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12745: return 0;
12746: }
12747:
12748: sub getCODE {
12749: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12750: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12751: defined($Apache::lonhomework::parsing_a_task) ) &&
12752: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12753: return $Apache::lonhomework::history{'resource.CODE'};
12754: }
12755: return undef;
12756: }
12757: #
12758: # Determines the random seed for a specific context:
12759: #
12760: # parameters:
12761: # symb - in course context the symb for the seed.
12762: # course_id - The course id of the form domain_coursenum.
12763: # domain - Domain for the user.
12764: # course - Course for the user.
12765: # cenv - environment of the course.
12766: #
12767: # NOTE:
12768: # All parameters are picked out of the environment if missing
12769: # or not defined.
12770: # If a symb cannot be determined the current time is used instead.
12771: #
12772: # For a given well defined symb, courside, domain, username,
12773: # and course environment, the seed is reproducible.
12774: #
12775: sub rndseed {
12776: my ($symb,$courseid,$domain,$username, $cenv)=@_;
12777: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12778: if (!defined($symb)) {
12779: unless ($symb=$wsymb) { return time; }
12780: }
12781: if (!defined $courseid) {
12782: $courseid=$wcourseid;
12783: }
12784: if (!defined $domain) { $domain=$wdomain; }
12785: if (!defined $username) { $username=$wusername }
12786:
12787: my $which;
12788: if (defined($cenv->{'rndseed'})) {
12789: $which = $cenv->{'rndseed'};
12790: } else {
12791: $which =&get_rand_alg($courseid);
12792: }
12793: if (defined(&getCODE())) {
12794: if ($which eq '64bit5') {
12795: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12796: } elsif ($which eq '64bit4') {
12797: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12798: } else {
12799: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12800: }
12801: } elsif ($which eq '64bit5') {
12802: return &rndseed_64bit5($symb,$courseid,$domain,$username);
12803: } elsif ($which eq '64bit4') {
12804: return &rndseed_64bit4($symb,$courseid,$domain,$username);
12805: } elsif ($which eq '64bit3') {
12806: return &rndseed_64bit3($symb,$courseid,$domain,$username);
12807: } elsif ($which eq '64bit2') {
12808: return &rndseed_64bit2($symb,$courseid,$domain,$username);
12809: } elsif ($which eq '64bit') {
12810: return &rndseed_64bit($symb,$courseid,$domain,$username);
12811: }
12812: return &rndseed_32bit($symb,$courseid,$domain,$username);
12813: }
12814:
12815: sub rndseed_32bit {
12816: my ($symb,$courseid,$domain,$username)=@_;
12817: {
12818: use integer;
12819: my $symbchck=unpack("%32C*",$symb) << 27;
12820: my $symbseed=numval($symb) << 22;
12821: my $namechck=unpack("%32C*",$username) << 17;
12822: my $nameseed=numval($username) << 12;
12823: my $domainseed=unpack("%32C*",$domain) << 7;
12824: my $courseseed=unpack("%32C*",$courseid);
12825: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12826: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12827: #&logthis("rndseed :$num:$symb");
12828: if ($_64bit) { $num=(($num<<32)>>32); }
12829: return $num;
12830: }
12831: }
12832:
12833: sub rndseed_64bit {
12834: my ($symb,$courseid,$domain,$username)=@_;
12835: {
12836: use integer;
12837: my $symbchck=unpack("%32S*",$symb) << 21;
12838: my $symbseed=numval($symb) << 10;
12839: my $namechck=unpack("%32S*",$username);
12840:
12841: my $nameseed=numval($username) << 21;
12842: my $domainseed=unpack("%32S*",$domain) << 10;
12843: my $courseseed=unpack("%32S*",$courseid);
12844:
12845: my $num1=$symbchck+$symbseed+$namechck;
12846: my $num2=$nameseed+$domainseed+$courseseed;
12847: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12848: #&logthis("rndseed :$num:$symb");
12849: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12850: return "$num1,$num2";
12851: }
12852: }
12853:
12854: sub rndseed_64bit2 {
12855: my ($symb,$courseid,$domain,$username)=@_;
12856: {
12857: use integer;
12858: # strings need to be an even # of cahracters long, it it is odd the
12859: # last characters gets thrown away
12860: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12861: my $symbseed=numval($symb) << 10;
12862: my $namechck=unpack("%32S*",$username.' ');
12863:
12864: my $nameseed=numval($username) << 21;
12865: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12866: my $courseseed=unpack("%32S*",$courseid.' ');
12867:
12868: my $num1=$symbchck+$symbseed+$namechck;
12869: my $num2=$nameseed+$domainseed+$courseseed;
12870: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12871: #&logthis("rndseed :$num:$symb");
12872: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12873: return "$num1,$num2";
12874: }
12875: }
12876:
12877: sub rndseed_64bit3 {
12878: my ($symb,$courseid,$domain,$username)=@_;
12879: {
12880: use integer;
12881: # strings need to be an even # of cahracters long, it it is odd the
12882: # last characters gets thrown away
12883: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12884: my $symbseed=numval2($symb) << 10;
12885: my $namechck=unpack("%32S*",$username.' ');
12886:
12887: my $nameseed=numval2($username) << 21;
12888: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12889: my $courseseed=unpack("%32S*",$courseid.' ');
12890:
12891: my $num1=$symbchck+$symbseed+$namechck;
12892: my $num2=$nameseed+$domainseed+$courseseed;
12893: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12894: #&logthis("rndseed :$num1:$num2:$_64bit");
12895: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12896:
12897: return "$num1:$num2";
12898: }
12899: }
12900:
12901: sub rndseed_64bit4 {
12902: my ($symb,$courseid,$domain,$username)=@_;
12903: {
12904: use integer;
12905: # strings need to be an even # of cahracters long, it it is odd the
12906: # last characters gets thrown away
12907: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12908: my $symbseed=numval3($symb) << 10;
12909: my $namechck=unpack("%32S*",$username.' ');
12910:
12911: my $nameseed=numval3($username) << 21;
12912: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12913: my $courseseed=unpack("%32S*",$courseid.' ');
12914:
12915: my $num1=$symbchck+$symbseed+$namechck;
12916: my $num2=$nameseed+$domainseed+$courseseed;
12917: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12918: #&logthis("rndseed :$num1:$num2:$_64bit");
12919: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12920:
12921: return "$num1:$num2";
12922: }
12923: }
12924:
12925: sub rndseed_64bit5 {
12926: my ($symb,$courseid,$domain,$username)=@_;
12927: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12928: return "$num1:$num2";
12929: }
12930:
12931: sub rndseed_CODE_64bit {
12932: my ($symb,$courseid,$domain,$username)=@_;
12933: {
12934: use integer;
12935: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12936: my $symbseed=numval2($symb);
12937: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12938: my $CODEseed=numval(&getCODE());
12939: my $courseseed=unpack("%32S*",$courseid.' ');
12940: my $num1=$symbseed+$CODEchck;
12941: my $num2=$CODEseed+$courseseed+$symbchck;
12942: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12943: #&logthis("rndseed :$num1:$num2:$symb");
12944: if ($_64bit) { $num1=(($num1<<32)>>32); }
12945: if ($_64bit) { $num2=(($num2<<32)>>32); }
12946: return "$num1:$num2";
12947: }
12948: }
12949:
12950: sub rndseed_CODE_64bit4 {
12951: my ($symb,$courseid,$domain,$username)=@_;
12952: {
12953: use integer;
12954: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12955: my $symbseed=numval3($symb);
12956: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12957: my $CODEseed=numval3(&getCODE());
12958: my $courseseed=unpack("%32S*",$courseid.' ');
12959: my $num1=$symbseed+$CODEchck;
12960: my $num2=$CODEseed+$courseseed+$symbchck;
12961: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12962: #&logthis("rndseed :$num1:$num2:$symb");
12963: if ($_64bit) { $num1=(($num1<<32)>>32); }
12964: if ($_64bit) { $num2=(($num2<<32)>>32); }
12965: return "$num1:$num2";
12966: }
12967: }
12968:
12969: sub rndseed_CODE_64bit5 {
12970: my ($symb,$courseid,$domain,$username)=@_;
12971: my $code = &getCODE();
12972: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12973: return "$num1:$num2";
12974: }
12975:
12976: sub setup_random_from_rndseed {
12977: my ($rndseed)=@_;
12978: if ($rndseed =~/([,:])/) {
12979: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12980: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12981: &Math::Random::random_set_seed_from_phrase($rndseed);
12982: } else {
12983: &Math::Random::random_set_seed($num1,$num2);
12984: }
12985: } else {
12986: &Math::Random::random_set_seed_from_phrase($rndseed);
12987: }
12988: }
12989:
12990: sub latest_receipt_algorithm_id {
12991: return 'receipt3';
12992: }
12993:
12994: sub recunique {
12995: my $fucourseid=shift;
12996: my $unique;
12997: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12998: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12999: $unique=$env{"course.$fucourseid.internal.encseed"};
13000: } else {
13001: $unique=$perlvar{'lonReceipt'};
13002: }
13003: return unpack("%32C*",$unique);
13004: }
13005:
13006: sub recprefix {
13007: my $fucourseid=shift;
13008: my $prefix;
13009: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
13010: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
13011: $prefix=$env{"course.$fucourseid.internal.encpref"};
13012: } else {
13013: $prefix=$perlvar{'lonHostID'};
13014: }
13015: return unpack("%32C*",$prefix);
13016: }
13017:
13018: sub ireceipt {
13019: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
13020:
13021: my $return =&recprefix($fucourseid).'-';
13022:
13023: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
13024: $env{'request.state'} eq 'construct') {
13025: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
13026: return $return;
13027: }
13028:
13029: my $cuname=unpack("%32C*",$funame);
13030: my $cudom=unpack("%32C*",$fudom);
13031: my $cucourseid=unpack("%32C*",$fucourseid);
13032: my $cusymb=unpack("%32C*",$fusymb);
13033: my $cunique=&recunique($fucourseid);
13034: my $cpart=unpack("%32S*",$part);
13035: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
13036:
13037: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
13038:
13039: $return.= ($cunique%$cuname+
13040: $cunique%$cudom+
13041: $cusymb%$cuname+
13042: $cusymb%$cudom+
13043: $cucourseid%$cuname+
13044: $cucourseid%$cudom+
13045: $cpart%$cuname+
13046: $cpart%$cudom);
13047: } else {
13048: $return.= ($cunique%$cuname+
13049: $cunique%$cudom+
13050: $cusymb%$cuname+
13051: $cusymb%$cudom+
13052: $cucourseid%$cuname+
13053: $cucourseid%$cudom);
13054: }
13055: return $return;
13056: }
13057:
13058: sub receipt {
13059: my ($part)=@_;
13060: my ($symb,$courseid,$domain,$name) = &whichuser();
13061: return &ireceipt($name,$domain,$courseid,$symb,$part);
13062: }
13063:
13064: sub whichuser {
13065: my ($passedsymb)=@_;
13066: my ($symb,$courseid,$domain,$name,$publicuser);
13067: if (defined($env{'form.grade_symb'})) {
13068: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
13069: my $allowed=&allowed('vgr',$tmp_courseid);
13070: if (!$allowed &&
13071: exists($env{'request.course.sec'}) &&
13072: $env{'request.course.sec'} !~ /^\s*$/) {
13073: $allowed=&allowed('vgr',$tmp_courseid.
13074: '/'.$env{'request.course.sec'});
13075: }
13076: if ($allowed) {
13077: ($symb)=&get_env_multiple('form.grade_symb');
13078: $courseid=$tmp_courseid;
13079: ($domain)=&get_env_multiple('form.grade_domain');
13080: ($name)=&get_env_multiple('form.grade_username');
13081: return ($symb,$courseid,$domain,$name,$publicuser);
13082: }
13083: }
13084: if (!$passedsymb) {
13085: $symb=&symbread();
13086: } else {
13087: $symb=$passedsymb;
13088: }
13089: $courseid=$env{'request.course.id'};
13090: $domain=$env{'user.domain'};
13091: $name=$env{'user.name'};
13092: if ($name eq 'public' && $domain eq 'public') {
13093: if (!defined($env{'form.username'})) {
13094: $env{'form.username'}.=time.rand(10000000);
13095: }
13096: $name.=$env{'form.username'};
13097: }
13098: return ($symb,$courseid,$domain,$name,$publicuser);
13099:
13100: }
13101:
13102: # ------------------------------------------------------------ Serves up a file
13103: # returns either the contents of the file or
13104: # -1 if the file doesn't exist
13105: #
13106: # if the target is a file that was uploaded via DOCS,
13107: # a check will be made to see if a current copy exists on the local server,
13108: # if it does this will be served, otherwise a copy will be retrieved from
13109: # the home server for the course and stored in /home/httpd/html/userfiles on
13110: # the local server.
13111:
13112: sub getfile {
13113: my ($file) = @_;
13114: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
13115: &repcopy($file);
13116: return &readfile($file);
13117: }
13118:
13119: sub repcopy_userfile {
13120: my ($file)=@_;
13121: my $londocroot = $perlvar{'lonDocRoot'};
13122: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13123: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13124: my ($cdom,$cnum,$filename) =
13125: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13126: my $uri="/uploaded/$cdom/$cnum/$filename";
13127: if (-e "$file") {
13128: # we already have a local copy, check it out
13129: my @fileinfo = stat($file);
13130: my $rtncode;
13131: my $info;
13132: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13133: if ($lwpresp ne 'ok') {
13134: # there is no such file anymore, even though we had a local copy
13135: if ($rtncode eq '404') {
13136: unlink($file);
13137: }
13138: return -1;
13139: }
13140: if ($info < $fileinfo[9]) {
13141: # nice, the file we have is up-to-date, just say okay
13142: return 'ok';
13143: } else {
13144: # the file is outdated, get rid of it
13145: unlink($file);
13146: }
13147: }
13148: # one way or the other, at this point, we don't have the file
13149: # construct the correct path for the file
13150: my @parts = ($cdom,$cnum);
13151: if ($filename =~ m|^(.+)/[^/]+$|) {
13152: push @parts, split(/\//,$1);
13153: }
13154: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13155: foreach my $part (@parts) {
13156: $path .= '/'.$part;
13157: if (!-e $path) {
13158: mkdir($path,0770);
13159: }
13160: }
13161: # now the path exists for sure
13162: # get a user agent
13163: my $ua=new LWP::UserAgent;
13164: my $transferfile=$file.'.in.transfer';
13165: # FIXME: this should flock
13166: if (-e $transferfile) { return 'ok'; }
13167: my $request;
13168: $uri=~s/^\///;
13169: my $homeserver = &homeserver($cnum,$cdom);
13170: my $hostname = &hostname($homeserver);
13171: my $protocol = $protocol{$homeserver};
13172: $protocol = 'http' if ($protocol ne 'https');
13173: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13174: my $response=$ua->request($request,$transferfile);
13175: # did it work?
13176: if ($response->is_error()) {
13177: unlink($transferfile);
13178: &logthis("Userfile repcopy failed for $uri");
13179: return -1;
13180: }
13181: # worked, rename the transfer file
13182: rename($transferfile,$file);
13183: return 'ok';
13184: }
13185:
13186: sub tokenwrapper {
13187: my $uri=shift;
13188: $uri=~s|^https?\://([^/]+)||;
13189: $uri=~s|^/||;
13190: $env{'user.environment'}=~/\/([^\/]+)\.id/;
13191: my $token=$1;
13192: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13193: if ($udom && $uname && $file) {
13194: $file=~s|(\?\.*)*$||;
13195: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13196: my $homeserver = &homeserver($uname,$udom);
13197: my $hostname = &hostname($homeserver);
13198: my $protocol = $protocol{$homeserver};
13199: $protocol = 'http' if ($protocol ne 'https');
13200: return $protocol.'://'.$hostname.'/'.$uri.
13201: (($uri=~/\?/)?'&':'?').'token='.$token.
13202: '&tokenissued='.$perlvar{'lonHostID'};
13203: } else {
13204: return '/adm/notfound.html';
13205: }
13206: }
13207:
13208: # call with reqtype HEAD: get last modification time
13209: # call with reqtype GET: get the file contents
13210: # Do not call this with reqtype GET for large files! It loads everything into memory
13211: #
13212: sub getuploaded {
13213: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13214: $uri=~s/^\///;
13215: my $homeserver = &homeserver($cnum,$cdom);
13216: my $hostname = &hostname($homeserver);
13217: my $protocol = $protocol{$homeserver};
13218: $protocol = 'http' if ($protocol ne 'https');
13219: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13220: my $ua=new LWP::UserAgent;
13221: my $request=new HTTP::Request($reqtype,$uri);
13222: my $response=$ua->request($request);
13223: $$rtncode = $response->code;
13224: if (! $response->is_success()) {
13225: return 'failed';
13226: }
13227: if ($reqtype eq 'HEAD') {
13228: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13229: } elsif ($reqtype eq 'GET') {
13230: $$info = $response->content;
13231: }
13232: return 'ok';
13233: }
13234:
13235: sub readfile {
13236: my $file = shift;
13237: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13238: my $fh;
13239: open($fh,"<",$file);
13240: my $a='';
13241: while (my $line = <$fh>) { $a .= $line; }
13242: return $a;
13243: }
13244:
13245: sub filelocation {
13246: my ($dir,$file) = @_;
13247: my $location;
13248: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13249:
13250: if ($file =~ m-^/adm/-) {
13251: $file=~s-^/adm/wrapper/-/-;
13252: $file=~s-^/adm/coursedocs/showdoc/-/-;
13253: }
13254:
13255: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13256: $location = $file;
13257: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13258: my ($udom,$uname,$filename)=
13259: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13260: my $home=&homeserver($uname,$udom);
13261: my $is_me=0;
13262: my @ids=¤t_machine_ids();
13263: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13264: if ($is_me) {
13265: $location=propath($udom,$uname).'/userfiles/'.$filename;
13266: } else {
13267: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13268: $udom.'/'.$uname.'/'.$filename;
13269: }
13270: } elsif ($file =~ m-^/adm/-) {
13271: $location = $perlvar{'lonDocRoot'}.'/'.$file;
13272: } else {
13273: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13274: $file=~s:^/(res|priv)/:/:;
13275: my $space=$1;
13276: if ( !( $file =~ m:^/:) ) {
13277: $location = $dir. '/'.$file;
13278: } else {
13279: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13280: }
13281: }
13282: $location=~s://+:/:g; # remove duplicate /
13283: while ($location=~m{/\.\./}) {
13284: if ($location =~ m{/[^/]+/\.\./}) {
13285: $location=~ s{/[^/]+/\.\./}{/}g;
13286: } else {
13287: $location=~ s{/\.\./}{/}g;
13288: }
13289: } #remove dir/..
13290: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13291: return $location;
13292: }
13293:
13294: sub hreflocation {
13295: my ($dir,$file)=@_;
13296: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13297: $file=filelocation($dir,$file);
13298: } elsif ($file=~m-^/adm/-) {
13299: $file=~s-^/adm/wrapper/-/-;
13300: $file=~s-^/adm/coursedocs/showdoc/-/-;
13301: }
13302: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13303: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13304: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13305: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13306: {/uploaded/$1/$2/}x;
13307: }
13308: if ($file=~ m{^/userfiles/}) {
13309: $file =~ s{^/userfiles/}{/uploaded/};
13310: }
13311: return $file;
13312: }
13313:
13314:
13315:
13316:
13317:
13318: sub current_machine_domains {
13319: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13320: }
13321:
13322: sub machine_domains {
13323: my ($hostname) = @_;
13324: my @domains;
13325: my %hostname = &all_hostnames();
13326: while( my($id, $name) = each(%hostname)) {
13327: # &logthis("-$id-$name-$hostname-");
13328: if ($hostname eq $name) {
13329: push(@domains,&host_domain($id));
13330: }
13331: }
13332: return @domains;
13333: }
13334:
13335: sub current_machine_ids {
13336: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13337: }
13338:
13339: sub machine_ids {
13340: my ($hostname) = @_;
13341: $hostname ||= &hostname($perlvar{'lonHostID'});
13342: my @ids;
13343: my %name_to_host = &all_names();
13344: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13345: return @{ $name_to_host{$hostname} };
13346: }
13347: return;
13348: }
13349:
13350: sub additional_machine_domains {
13351: my @domains;
13352: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13353: while( my $line = <$fh>) {
13354: $line =~ s/\s//g;
13355: push(@domains,$line);
13356: }
13357: return @domains;
13358: }
13359:
13360: sub default_login_domain {
13361: my $domain = $perlvar{'lonDefDomain'};
13362: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13363: foreach my $posdom (¤t_machine_domains(),
13364: &additional_machine_domains()) {
13365: if (lc($posdom) eq lc($testdomain)) {
13366: $domain=$posdom;
13367: last;
13368: }
13369: }
13370: return $domain;
13371: }
13372:
13373: sub shared_institution {
13374: my ($dom,$lonhost) = @_;
13375: if ($lonhost eq '') {
13376: $lonhost = $perlvar{'lonHostID'};
13377: }
13378: my $same_intdom;
13379: my $hostintdom = &internet_dom($lonhost);
13380: if ($hostintdom ne '') {
13381: my %iphost = &get_iphost();
13382: my $primary_id = &domain($dom,'primary');
13383: my $primary_ip = &get_host_ip($primary_id);
13384: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13385: foreach my $id (@{$iphost{$primary_ip}}) {
13386: my $intdom = &internet_dom($id);
13387: if ($intdom eq $hostintdom) {
13388: $same_intdom = 1;
13389: last;
13390: }
13391: }
13392: }
13393: }
13394: return $same_intdom;
13395: }
13396:
13397: sub uses_sts {
13398: my ($ignore_cache) = @_;
13399: my $lonhost = $perlvar{'lonHostID'};
13400: my $hostname = &hostname($lonhost);
13401: my $sts_on;
13402: if ($protocol{$lonhost} eq 'https') {
13403: my $cachetime = 12*3600;
13404: if (!$ignore_cache) {
13405: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13406: if (defined($cached)) {
13407: return $sts_on;
13408: }
13409: }
13410: my $ua=new LWP::UserAgent;
13411: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13412: my $request=new HTTP::Request('HEAD',$url);
13413: my $response=$ua->request($request);
13414: if ($response->is_success) {
13415: my $has_sts = $response->header('Strict-Transport-Security');
13416: if ($has_sts eq '') {
13417: $sts_on = 0;
13418: } else {
13419: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13420: my $maxage = $1;
13421: if ($maxage) {
13422: $sts_on = 1;
13423: } else {
13424: $sts_on = 0;
13425: }
13426: } else {
13427: $sts_on = 0;
13428: }
13429: }
13430: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13431: }
13432: }
13433: return;
13434: }
13435:
13436: sub get_requestor_ip {
13437: my ($r,$nolookup,$noproxy) = @_;
13438: my $from_ip;
13439: if (ref($r)) {
13440: $from_ip = $r->get_remote_host($nolookup);
13441: } else {
13442: $from_ip = $ENV{'REMOTE_ADDR'};
13443: }
13444: return $from_ip;
13445: }
13446:
13447: # ------------------------------------------------------------- Declutters URLs
13448:
13449: sub declutter {
13450: my $thisfn=shift;
13451: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13452: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13453: $thisfn=~s{^/home/httpd/html}{};
13454: }
13455: $thisfn=~s/^\///;
13456: $thisfn=~s|^adm/wrapper/||;
13457: $thisfn=~s|^adm/coursedocs/showdoc/||;
13458: $thisfn=~s/^res\///;
13459: $thisfn=~s/^priv\///;
13460: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13461: $thisfn=~s/\?.+$//;
13462: }
13463: return $thisfn;
13464: }
13465:
13466: # ------------------------------------------------------------- Clutter up URLs
13467:
13468: sub clutter {
13469: my $thisfn='/'.&declutter(shift);
13470: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13471: || $thisfn =~ m{^/adm/(includes|pages)} ) {
13472: $thisfn='/res'.$thisfn;
13473: }
13474: if ($thisfn !~m|^/adm|) {
13475: if ($thisfn =~ m|^/ext/|) {
13476: $thisfn='/adm/wrapper'.$thisfn;
13477: } else {
13478: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13479: my $embstyle=&Apache::loncommon::fileembstyle($ext);
13480: if ($embstyle eq 'ssi'
13481: || ($embstyle eq 'hdn')
13482: || ($embstyle eq 'rat')
13483: || ($embstyle eq 'prv')
13484: || ($embstyle eq 'ign')) {
13485: #do nothing with these
13486: } elsif (($embstyle eq 'img')
13487: || ($embstyle eq 'emb')
13488: || ($embstyle eq 'wrp')) {
13489: $thisfn='/adm/wrapper'.$thisfn;
13490: } elsif ($embstyle eq 'unk'
13491: && $thisfn!~/\.(sequence|page)$/) {
13492: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
13493: } else {
13494: # &logthis("Got a blank emb style");
13495: }
13496: }
13497: }
13498: return $thisfn;
13499: }
13500:
13501: sub clutter_with_no_wrapper {
13502: my $uri = &clutter(shift);
13503: if ($uri =~ m-^/adm/-) {
13504: $uri =~ s-^/adm/wrapper/-/-;
13505: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13506: }
13507: return $uri;
13508: }
13509:
13510: sub freeze_escape {
13511: my ($value)=@_;
13512: if (ref($value)) {
13513: $value=&nfreeze($value);
13514: return '__FROZEN__'.&escape($value);
13515: }
13516: return &escape($value);
13517: }
13518:
13519:
13520: sub thaw_unescape {
13521: my ($value)=@_;
13522: if ($value =~ /^__FROZEN__/) {
13523: substr($value,0,10,undef);
13524: $value=&unescape($value);
13525: return &thaw($value);
13526: }
13527: return &unescape($value);
13528: }
13529:
13530: sub correct_line_ends {
13531: my ($result)=@_;
13532: $$result =~s/\r\n/\n/mg;
13533: $$result =~s/\r/\n/mg;
13534: }
13535: # ================================================================ Main Program
13536:
13537: sub goodbye {
13538: &logthis("Starting Shut down");
13539: #not converted to using infrastruture and probably shouldn't be
13540: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13541: #converted
13542: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13543: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13544: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13545: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13546: #1.1 only
13547: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13548: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13549: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13550: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13551: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13552: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13553: &logthis(sprintf("%-20s is %s",'hits',$hits));
13554: &flushcourselogs();
13555: &logthis("Shutting down");
13556: }
13557:
13558: sub get_dns {
13559: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13560: if (!$ignore_cache) {
13561: my ($content,$cached)=
13562: &Apache::lonnet::is_cached_new('dns',$url);
13563: if ($cached) {
13564: &$func($content,$hashref);
13565: return;
13566: }
13567: }
13568:
13569: my %alldns;
13570: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13571: foreach my $dns (<$config>) {
13572: next if ($dns !~ /^\^(\S*)/x);
13573: my $line = $1;
13574: my ($host,$protocol) = split(/:/,$line);
13575: if ($protocol ne 'https') {
13576: $protocol = 'http';
13577: }
13578: $alldns{$host} = $protocol;
13579: }
13580: close($config);
13581: }
13582: while (%alldns) {
13583: my ($dns) = sort { $b cmp $a } keys(%alldns);
13584: my $ua=new LWP::UserAgent;
13585: $ua->timeout(30);
13586: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13587: my $response=$ua->request($request);
13588: delete($alldns{$dns});
13589: next if ($response->is_error());
13590: my @content = split("\n",$response->content);
13591: unless ($nocache) {
13592: &do_cache_new('dns',$url,\@content,30*24*60*60);
13593: }
13594: &$func(\@content,$hashref);
13595: return;
13596: }
13597: my $which = (split('/',$url))[3];
13598: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13599: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13600: my @content = <$config>;
13601: &$func(\@content,$hashref);
13602: }
13603: return;
13604: }
13605:
13606: # ------------------------------------------------------Get DNS checksums file
13607: sub parse_dns_checksums_tab {
13608: my ($lines,$hashref) = @_;
13609: my $lonhost = $perlvar{'lonHostID'};
13610: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13611: my $loncaparev = &get_server_loncaparev($machine_dom);
13612: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13613: my $webconfdir = '/etc/httpd/conf';
13614: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13615: $webconfdir = '/etc/apache2';
13616: } elsif ($distro =~ /^sles(\d+)$/) {
13617: if ($1 >= 10) {
13618: $webconfdir = '/etc/apache2';
13619: }
13620: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13621: if ($1 >= 10.0) {
13622: $webconfdir = '/etc/apache2';
13623: }
13624: }
13625: my ($release,$timestamp) = split(/\-/,$loncaparev);
13626: my (%chksum,%revnum);
13627: if (ref($lines) eq 'ARRAY') {
13628: chomp(@{$lines});
13629: my $version = shift(@{$lines});
13630: if ($version eq $release) {
13631: foreach my $line (@{$lines}) {
13632: my ($file,$version,$shasum) = split(/,/,$line);
13633: if ($file =~ m{^/etc/httpd/conf}) {
13634: if ($webconfdir eq '/etc/apache2') {
13635: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13636: }
13637: }
13638: $chksum{$file} = $shasum;
13639: $revnum{$file} = $version;
13640: }
13641: if (ref($hashref) eq 'HASH') {
13642: %{$hashref} = (
13643: sums => \%chksum,
13644: versions => \%revnum,
13645: );
13646: }
13647: }
13648: }
13649: return;
13650: }
13651:
13652: sub fetch_dns_checksums {
13653: my %checksums;
13654: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13655: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13656: my ($release,$timestamp) = split(/\-/,$loncaparev);
13657: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13658: \%checksums);
13659: return \%checksums;
13660: }
13661:
13662: # ------------------------------------------------------------ Read domain file
13663: {
13664: my $loaded;
13665: my %domain;
13666:
13667: sub parse_domain_tab {
13668: my ($lines) = @_;
13669: foreach my $line (@$lines) {
13670: next if ($line =~ /^(\#|\s*$ )/x);
13671:
13672: chomp($line);
13673: my ($name,@elements) = split(/:/,$line,9);
13674: my %this_domain;
13675: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13676: 'lang_def', 'city', 'longi', 'lati',
13677: 'primary') {
13678: $this_domain{$field} = shift(@elements);
13679: }
13680: $domain{$name} = \%this_domain;
13681: }
13682: }
13683:
13684: sub reset_domain_info {
13685: undef($loaded);
13686: undef(%domain);
13687: }
13688:
13689: sub load_domain_tab {
13690: my ($ignore_cache,$nocache) = @_;
13691: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13692: my $fh;
13693: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13694: my @lines = <$fh>;
13695: &parse_domain_tab(\@lines);
13696: }
13697: close($fh);
13698: $loaded = 1;
13699: }
13700:
13701: sub domain {
13702: &load_domain_tab() if (!$loaded);
13703:
13704: my ($name,$what) = @_;
13705: return if ( !exists($domain{$name}) );
13706:
13707: if (!$what) {
13708: return $domain{$name}{'description'};
13709: }
13710: return $domain{$name}{$what};
13711: }
13712:
13713: sub domain_info {
13714: &load_domain_tab() if (!$loaded);
13715: return %domain;
13716: }
13717:
13718: }
13719:
13720:
13721: # ------------------------------------------------------------- Read hosts file
13722: {
13723: my %hostname;
13724: my %hostdom;
13725: my %libserv;
13726: my $loaded;
13727: my %name_to_host;
13728: my %internetdom;
13729: my %LC_dns_serv;
13730:
13731: sub parse_hosts_tab {
13732: my ($file) = @_;
13733: foreach my $configline (@$file) {
13734: next if ($configline =~ /^(\#|\s*$ )/x);
13735: chomp($configline);
13736: if ($configline =~ /^\^/) {
13737: if ($configline =~ /^\^([\w.\-]+)/) {
13738: $LC_dns_serv{$1} = 1;
13739: }
13740: next;
13741: }
13742: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13743: $name=~s/\s//g;
13744: if ($id && $domain && $role && $name) {
13745: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13746: my $curr = $hostname{$id};
13747: my $skip;
13748: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13749: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13750: $skip = 1;
13751: } else {
13752: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13753: }
13754: }
13755: unless ($skip) {
13756: push(@{$name_to_host{$name}},$id);
13757: }
13758: } else {
13759: push(@{$name_to_host{$name}},$id);
13760: }
13761: $hostname{$id}=$name;
13762: $hostdom{$id}=$domain;
13763: if ($role eq 'library') { $libserv{$id}=$name; }
13764: if (defined($protocol)) {
13765: if ($protocol eq 'https') {
13766: $protocol{$id} = $protocol;
13767: } else {
13768: $protocol{$id} = 'http';
13769: }
13770: } else {
13771: $protocol{$id} = 'http';
13772: }
13773: if (defined($intdom)) {
13774: $internetdom{$id} = $intdom;
13775: }
13776: }
13777: }
13778: }
13779:
13780: sub reset_hosts_info {
13781: &purge_remembered();
13782: &reset_domain_info();
13783: &reset_hosts_ip_info();
13784: undef(%name_to_host);
13785: undef(%hostname);
13786: undef(%hostdom);
13787: undef(%libserv);
13788: undef($loaded);
13789: }
13790:
13791: sub load_hosts_tab {
13792: my ($ignore_cache,$nocache) = @_;
13793: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13794: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13795: my @config = <$config>;
13796: &parse_hosts_tab(\@config);
13797: close($config);
13798: $loaded=1;
13799: }
13800:
13801: sub hostname {
13802: &load_hosts_tab() if (!$loaded);
13803:
13804: my ($lonid) = @_;
13805: return $hostname{$lonid};
13806: }
13807:
13808: sub all_hostnames {
13809: &load_hosts_tab() if (!$loaded);
13810:
13811: return %hostname;
13812: }
13813:
13814: sub all_names {
13815: my ($ignore_cache,$nocache) = @_;
13816: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13817:
13818: return %name_to_host;
13819: }
13820:
13821: sub all_host_domain {
13822: &load_hosts_tab() if (!$loaded);
13823: return %hostdom;
13824: }
13825:
13826: sub is_library {
13827: &load_hosts_tab() if (!$loaded);
13828:
13829: return exists($libserv{$_[0]});
13830: }
13831:
13832: sub all_library {
13833: &load_hosts_tab() if (!$loaded);
13834:
13835: return %libserv;
13836: }
13837:
13838: sub unique_library {
13839: #2x reverse removes all hostnames that appear more than once
13840: my %unique = reverse &all_library();
13841: return reverse %unique;
13842: }
13843:
13844: sub get_servers {
13845: &load_hosts_tab() if (!$loaded);
13846:
13847: my ($domain,$type) = @_;
13848: my %possible_hosts = ($type eq 'library') ? %libserv
13849: : %hostname;
13850: my %result;
13851: if (ref($domain) eq 'ARRAY') {
13852: while ( my ($host,$hostname) = each(%possible_hosts)) {
13853: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13854: $result{$host} = $hostname;
13855: }
13856: }
13857: } else {
13858: while ( my ($host,$hostname) = each(%possible_hosts)) {
13859: if ($hostdom{$host} eq $domain) {
13860: $result{$host} = $hostname;
13861: }
13862: }
13863: }
13864: return %result;
13865: }
13866:
13867: sub get_unique_servers {
13868: my %unique = reverse &get_servers(@_);
13869: return reverse %unique;
13870: }
13871:
13872: sub host_domain {
13873: &load_hosts_tab() if (!$loaded);
13874:
13875: my ($lonid) = @_;
13876: return $hostdom{$lonid};
13877: }
13878:
13879: sub all_domains {
13880: &load_hosts_tab() if (!$loaded);
13881:
13882: my %seen;
13883: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13884: return @uniq;
13885: }
13886:
13887: sub internet_dom {
13888: &load_hosts_tab() if (!$loaded);
13889:
13890: my ($lonid) = @_;
13891: return $internetdom{$lonid};
13892: }
13893:
13894: sub is_LC_dns {
13895: &load_hosts_tab() if (!$loaded);
13896:
13897: my ($hostname) = @_;
13898: return exists($LC_dns_serv{$hostname});
13899: }
13900:
13901: }
13902:
13903: {
13904: my %iphost;
13905: my %name_to_ip;
13906: my %lonid_to_ip;
13907:
13908: sub get_hosts_from_ip {
13909: my ($ip) = @_;
13910: my %iphosts = &get_iphost();
13911: if (ref($iphosts{$ip})) {
13912: return @{$iphosts{$ip}};
13913: }
13914: return;
13915: }
13916:
13917: sub reset_hosts_ip_info {
13918: undef(%iphost);
13919: undef(%name_to_ip);
13920: undef(%lonid_to_ip);
13921: }
13922:
13923: sub get_host_ip {
13924: my ($lonid) = @_;
13925: if (exists($lonid_to_ip{$lonid})) {
13926: return $lonid_to_ip{$lonid};
13927: }
13928: my $name=&hostname($lonid);
13929: my $ip = gethostbyname($name);
13930: return if (!$ip || length($ip) ne 4);
13931: $ip=inet_ntoa($ip);
13932: $name_to_ip{$name} = $ip;
13933: $lonid_to_ip{$lonid} = $ip;
13934: return $ip;
13935: }
13936:
13937: sub get_iphost {
13938: my ($ignore_cache,$nocache) = @_;
13939:
13940: if (!$ignore_cache) {
13941: if (%iphost) {
13942: return %iphost;
13943: }
13944: my ($ip_info,$cached)=
13945: &Apache::lonnet::is_cached_new('iphost','iphost');
13946: if ($cached) {
13947: %iphost = %{$ip_info->[0]};
13948: %name_to_ip = %{$ip_info->[1]};
13949: %lonid_to_ip = %{$ip_info->[2]};
13950: return %iphost;
13951: }
13952: }
13953:
13954: # get yesterday's info for fallback
13955: my %old_name_to_ip;
13956: my ($ip_info,$cached)=
13957: &Apache::lonnet::is_cached_new('iphost','iphost');
13958: if ($cached) {
13959: %old_name_to_ip = %{$ip_info->[1]};
13960: }
13961:
13962: my %name_to_host = &all_names($ignore_cache,$nocache);
13963: foreach my $name (keys(%name_to_host)) {
13964: my $ip;
13965: if (!exists($name_to_ip{$name})) {
13966: $ip = gethostbyname($name);
13967: if (!$ip || length($ip) ne 4) {
13968: if (defined($old_name_to_ip{$name})) {
13969: $ip = $old_name_to_ip{$name};
13970: &logthis("Can't find $name defaulting to old $ip");
13971: } else {
13972: &logthis("Name $name no IP found");
13973: next;
13974: }
13975: } else {
13976: $ip=inet_ntoa($ip);
13977: }
13978: $name_to_ip{$name} = $ip;
13979: } else {
13980: $ip = $name_to_ip{$name};
13981: }
13982: foreach my $id (@{ $name_to_host{$name} }) {
13983: $lonid_to_ip{$id} = $ip;
13984: }
13985: push(@{$iphost{$ip}},@{$name_to_host{$name}});
13986: }
13987: unless ($nocache) {
13988: &do_cache_new('iphost','iphost',
13989: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13990: 48*60*60);
13991: }
13992:
13993: return %iphost;
13994: }
13995:
13996: #
13997: # Given a DNS returns the loncapa host name for that DNS
13998: #
13999: sub host_from_dns {
14000: my ($dns) = @_;
14001: my @hosts;
14002: my $ip;
14003:
14004: if (exists($name_to_ip{$dns})) {
14005: $ip = $name_to_ip{$dns};
14006: }
14007: if (!$ip) {
14008: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
14009: if (length($ip) == 4) {
14010: $ip = &IO::Socket::inet_ntoa($ip);
14011: }
14012: }
14013: if ($ip) {
14014: @hosts = get_hosts_from_ip($ip);
14015: return $hosts[0];
14016: }
14017: return undef;
14018: }
14019:
14020: sub get_internet_names {
14021: my ($lonid) = @_;
14022: return if ($lonid eq '');
14023: my ($idnref,$cached)=
14024: &Apache::lonnet::is_cached_new('internetnames',$lonid);
14025: if ($cached) {
14026: return $idnref;
14027: }
14028: my $ip = &get_host_ip($lonid);
14029: my @hosts = &get_hosts_from_ip($ip);
14030: my %iphost = &get_iphost();
14031: my (@idns,%seen);
14032: foreach my $id (@hosts) {
14033: my $dom = &host_domain($id);
14034: my $prim_id = &domain($dom,'primary');
14035: my $prim_ip = &get_host_ip($prim_id);
14036: next if ($seen{$prim_ip});
14037: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
14038: foreach my $id (@{$iphost{$prim_ip}}) {
14039: my $intdom = &internet_dom($id);
14040: unless (grep(/^\Q$intdom\E$/,@idns)) {
14041: push(@idns,$intdom);
14042: }
14043: }
14044: }
14045: $seen{$prim_ip} = 1;
14046: }
14047: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
14048: }
14049:
14050: }
14051:
14052: sub all_loncaparevs {
14053: 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);
14054: }
14055:
14056: # ------------------------------------------------------- Read loncaparev table
14057: {
14058: sub load_loncaparevs {
14059: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
14060: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
14061: while (my $configline=<$config>) {
14062: chomp($configline);
14063: my ($hostid,$loncaparev)=split(/:/,$configline);
14064: $loncaparevs{$hostid}=$loncaparev;
14065: }
14066: close($config);
14067: }
14068: }
14069: }
14070: }
14071:
14072: # ----------------------------------------------------- Read serverhostID table
14073: {
14074: sub load_serverhomeIDs {
14075: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
14076: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
14077: while (my $configline=<$config>) {
14078: chomp($configline);
14079: my ($name,$id)=split(/:/,$configline);
14080: $serverhomeIDs{$name}=$id;
14081: }
14082: close($config);
14083: }
14084: }
14085: }
14086: }
14087:
14088:
14089: BEGIN {
14090:
14091: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
14092: unless ($readit) {
14093: {
14094: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
14095: %perlvar = (%perlvar,%{$configvars});
14096: }
14097:
14098:
14099: # ------------------------------------------------------ Read spare server file
14100: {
14101: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
14102:
14103: while (my $configline=<$config>) {
14104: chomp($configline);
14105: if ($configline) {
14106: my ($host,$type) = split(':',$configline,2);
14107: if (!defined($type) || $type eq '') { $type = 'default' };
14108: push(@{ $spareid{$type} }, $host);
14109: }
14110: }
14111: close($config);
14112: }
14113: # ------------------------------------------------------------ Read permissions
14114: {
14115: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
14116:
14117: while (my $configline=<$config>) {
14118: chomp($configline);
14119: if ($configline) {
14120: my ($role,$perm)=split(/ /,$configline);
14121: if ($perm ne '') { $pr{$role}=$perm; }
14122: }
14123: }
14124: close($config);
14125: }
14126:
14127: # -------------------------------------------- Read plain texts for permissions
14128: {
14129: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
14130:
14131: while (my $configline=<$config>) {
14132: chomp($configline);
14133: if ($configline) {
14134: my ($short,@plain)=split(/:/,$configline);
14135: %{$prp{$short}} = ();
14136: if (@plain > 0) {
14137: $prp{$short}{'std'} = $plain[0];
14138: for (my $i=1; $i<@plain; $i++) {
14139: $prp{$short}{'alt'.$i} = $plain[$i];
14140: }
14141: }
14142: }
14143: }
14144: close($config);
14145: }
14146:
14147: # ---------------------------------------------------------- Read package table
14148: {
14149: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14150:
14151: while (my $configline=<$config>) {
14152: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14153: chomp($configline);
14154: my ($short,$plain)=split(/:/,$configline);
14155: my ($pack,$name)=split(/\&/,$short);
14156: if ($plain ne '') {
14157: $packagetab{$pack.'&'.$name.'&name'}=$name;
14158: $packagetab{$short}=$plain;
14159: }
14160: }
14161: close($config);
14162: }
14163:
14164: # --------------------------------------------------------- Read loncaparev table
14165:
14166: &load_loncaparevs();
14167:
14168: # ------------------------------------------------------- Read serverhostID table
14169:
14170: &load_serverhomeIDs();
14171:
14172: # ---------------------------------------------------------- Read releaseslist XML
14173: {
14174: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14175: if (-e $file) {
14176: my $parser = HTML::LCParser->new($file);
14177: while (my $token = $parser->get_token()) {
14178: if ($token->[0] eq 'S') {
14179: my $item = $token->[1];
14180: my $name = $token->[2]{'name'};
14181: my $value = $token->[2]{'value'};
14182: if ($item ne '' && $name ne '' && $value ne '') {
14183: my $release = $parser->get_text();
14184: $release =~ s/(^\s*|\s*$ )//gx;
14185: $needsrelease{$item.':'.$name.':'.$value} = $release;
14186: }
14187: }
14188: }
14189: }
14190: }
14191:
14192: # ---------------------------------------------------------- Read managers table
14193: {
14194: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14195: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14196: while (my $configline=<$config>) {
14197: chomp($configline);
14198: next if ($configline =~ /^\#/);
14199: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14200: $managerstab{$configline} = 1;
14201: }
14202: }
14203: close($config);
14204: }
14205: }
14206: }
14207:
14208: # ------------- set up temporary directory
14209: {
14210: $tmpdir = LONCAPA::tempdir();
14211:
14212: }
14213:
14214: # ------------- set default texengine (domain default overrides this)
14215: {
14216: $deftex = LONCAPA::texengine();
14217: }
14218:
14219: # ------------- set default minimum length for passwords for internal auth users
14220: {
14221: $passwdmin = LONCAPA::passwd_min();
14222: }
14223:
14224: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14225: 'compress_threshold'=> 20_000,
14226: });
14227:
14228: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14229: $dumpcount=0;
14230: $locknum=0;
14231:
14232: &logtouch();
14233: &logthis('<font color="yellow">INFO: Read configuration</font>');
14234: $readit=1;
14235: {
14236: use integer;
14237: my $test=(2**32)+1;
14238: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14239: &logthis(" Detected 64bit platform ($_64bit)");
14240: }
14241: }
14242: }
14243:
14244: 1;
14245: __END__
14246:
14247: =pod
14248:
14249: =head1 NAME
14250:
14251: Apache::lonnet - Subroutines to ask questions about things in the network.
14252:
14253: =head1 SYNOPSIS
14254:
14255: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14256:
14257: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14258:
14259: Common parameters:
14260:
14261: =over 4
14262:
14263: =item *
14264:
14265: $uname : an internal username (if $cname expecting a course Id specifically)
14266:
14267: =item *
14268:
14269: $udom : a domain (if $cdom expecting a course's domain specifically)
14270:
14271: =item *
14272:
14273: $symb : a resource instance identifier
14274:
14275: =item *
14276:
14277: $namespace : the name of a .db file that contains the data needed or
14278: being set.
14279:
14280: =back
14281:
14282: =head1 OVERVIEW
14283:
14284: lonnet provides subroutines which interact with the
14285: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14286: about classes, users, and resources.
14287:
14288: For many of these objects you can also use this to store data about
14289: them or modify them in various ways.
14290:
14291: =head2 Symbs
14292:
14293: To identify a specific instance of a resource, LON-CAPA uses symbols
14294: or "symbs"X<symb>. These identifiers are built from the URL of the
14295: map, the resource number of the resource in the map, and the URL of
14296: the resource itself. The latter is somewhat redundant, but might help
14297: if maps change.
14298:
14299: An example is
14300:
14301: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14302:
14303: The respective map entry is
14304:
14305: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14306: title="Problem 2">
14307: </resource>
14308:
14309: Symbs are used by the random number generator, as well as to store and
14310: restore data specific to a certain instance of for example a problem.
14311:
14312: =head2 Storing And Retrieving Data
14313:
14314: X<store()>X<cstore()>X<restore()>Three of the most important functions
14315: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14316: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14317: is is the non-critical message twin of cstore. These functions are for
14318: handlers to store a perl hash to a user's permanent data space in an
14319: easy manner, and to retrieve it again on another call. It is expected
14320: that a handler would use this once at the beginning to retrieve data,
14321: and then again once at the end to send only the new data back.
14322:
14323: The data is stored in the user's data directory on the user's
14324: homeserver under the ID of the course.
14325:
14326: The hash that is returned by restore will have all of the previous
14327: value for all of the elements of the hash.
14328:
14329: Example:
14330:
14331: #creating a hash
14332: my %hash;
14333: $hash{'foo'}='bar';
14334:
14335: #storing it
14336: &Apache::lonnet::cstore(\%hash);
14337:
14338: #changing a value
14339: $hash{'foo'}='notbar';
14340:
14341: #adding a new value
14342: $hash{'bar'}='foo';
14343: &Apache::lonnet::cstore(\%hash);
14344:
14345: #retrieving the hash
14346: my %history=&Apache::lonnet::restore();
14347:
14348: #print the hash
14349: foreach my $key (sort(keys(%history))) {
14350: print("\%history{$key} = $history{$key}");
14351: }
14352:
14353: Will print out:
14354:
14355: %history{1:foo} = bar
14356: %history{1:keys} = foo:timestamp
14357: %history{1:timestamp} = 990455579
14358: %history{2:bar} = foo
14359: %history{2:foo} = notbar
14360: %history{2:keys} = foo:bar:timestamp
14361: %history{2:timestamp} = 990455580
14362: %history{bar} = foo
14363: %history{foo} = notbar
14364: %history{timestamp} = 990455580
14365: %history{version} = 2
14366:
14367: Note that the special hash entries C<keys>, C<version> and
14368: C<timestamp> were added to the hash. C<version> will be equal to the
14369: total number of versions of the data that have been stored. The
14370: C<timestamp> attribute will be the UNIX time the hash was
14371: stored. C<keys> is available in every historical section to list which
14372: keys were added or changed at a specific historical revision of a
14373: hash.
14374:
14375: B<Warning>: do not store the hash that restore returns directly. This
14376: will cause a mess since it will restore the historical keys as if the
14377: were new keys. I.E. 1:foo will become 1:1:foo etc.
14378:
14379: Calling convention:
14380:
14381: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14382: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14383:
14384: For more detailed information, see lonnet specific documentation.
14385:
14386: =head1 RETURN MESSAGES
14387:
14388: =over 4
14389:
14390: =item * B<con_lost>: unable to contact remote host
14391:
14392: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14393: when the connection is brought back up
14394:
14395: =item * B<con_failed>: unable to contact remote host and unable to save message
14396: for later delivery
14397:
14398: =item * B<error:>: an error a occurred, a description of the error follows the :
14399:
14400: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14401: that was requested
14402:
14403: =back
14404:
14405: =head1 PUBLIC SUBROUTINES
14406:
14407: =head2 Session Environment Functions
14408:
14409: =over 4
14410:
14411: =item *
14412: X<appenv()>
14413: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14414: the user envirnoment file, and will be restored for each access this
14415: user makes during this session, also modifies the %env for the current
14416: process. Optional rolesarrayref - if defined contains a reference to an array
14417: of roles which are exempt from the restriction on modifying user.role entries
14418: in the user's environment.db and in %env.
14419:
14420: =item *
14421: X<delenv()>
14422: B<delenv($delthis,$regexp)>: removes all items from the session
14423: environment file that begin with $delthis. If the
14424: optional second arg - $regexp - is true, $delthis is treated as a
14425: regular expression, otherwise \Q$delthis\E is used.
14426: The values are also deleted from the current processes %env.
14427:
14428: =item * get_env_multiple($name)
14429:
14430: gets $name from the %env hash, it seemlessly handles the cases where multiple
14431: values may be defined and end up as an array ref.
14432:
14433: returns an array of values
14434:
14435: =back
14436:
14437: =head2 User Information
14438:
14439: =over 4
14440:
14441: =item *
14442: X<queryauthenticate()>
14443: B<queryauthenticate($uname,$udom)>: try to determine user's current
14444: authentication scheme
14445:
14446: =item *
14447: X<authenticate()>
14448: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14449: authenticate user from domain's lib servers (first use the current
14450: one). C<$upass> should be the users password.
14451: $checkdefauth is optional (value is 1 if a check should be made to
14452: authenticate user using default authentication method, and allow
14453: account creation if username does not have account in the domain).
14454: $clientcancheckhost is optional (value is 1 if checking whether the
14455: server can host will occur on the client side in lonauth.pm).
14456:
14457: =item *
14458: X<homeserver()>
14459: B<homeserver($uname,$udom)>: find the server which has
14460: the user's directory and files (there must be only one), this caches
14461: the answer, and also caches if there is a borken connection.
14462:
14463: =item *
14464: X<idget()>
14465: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14466: (IDs are a unique resource in a domain, there must be only 1 ID per
14467: username, and only 1 username per ID in a specific domain) (returns
14468: hash: id=>name,id=>name)
14469:
14470: =item *
14471: X<idrget()>
14472: B<idrget($udom,@unames)>: find the IDs behind a list of
14473: usernames (returns hash: name=>id,name=>id)
14474:
14475: =item *
14476: X<idput()>
14477: B<idput($udom,%ids)>: store away a list of names and associated IDs
14478:
14479: =item *
14480: X<rolesinit()>
14481: B<rolesinit($udom,$username)>: get user privileges.
14482: returns user role, first access and timer interval hashes
14483:
14484: =item *
14485: X<privileged()>
14486: B<privileged($username,$domain)>: returns a true if user has a
14487: privileged and active role (i.e. su or dc), false otherwise.
14488:
14489: =item *
14490: X<getsection()>
14491: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14492: course $cname, return section name/number or '' for "not in course"
14493: and '-1' for "no section"
14494:
14495: =item *
14496: X<userenvironment()>
14497: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14498: passed in @what from the requested user's environment, returns a hash
14499:
14500: =item *
14501: X<userlog_query()>
14502: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14503: activity.log file. %filters defines filters applied when parsing the
14504: log file. These can be start or end timestamps, or the type of action
14505: - log to look for Login or Logout events, check for Checkin or
14506: Checkout, role for role selection. The response is in the form
14507: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14508: escaped strings of the action recorded in the activity.log file.
14509:
14510: =back
14511:
14512: =head2 User Roles
14513:
14514: =over 4
14515:
14516: =item *
14517:
14518: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14519: returns codes for allowed actions.
14520:
14521: The first argument is required, all others are optional.
14522:
14523: $priv is the privilege being checked.
14524: $uri contains additional information about what is being checked for access (e.g.,
14525: URL, course ID etc.).
14526: $symb is the unique resource instance identifier in a course; if needed,
14527: but not provided, it will be retrieved via a call to &symbread().
14528: $role is the role for which a priv is being checked (only used if priv is evb).
14529: $clientip is the user's IP address (only used when checking for access to portfolio
14530: files).
14531: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14532: prevents recursive calls to &allowed.
14533:
14534: F: full access
14535: U,I,K: authentication modes (cxx only)
14536: '': forbidden
14537: 1: user needs to choose course
14538: 2: browse allowed
14539: A: passphrase authentication needed
14540: B: access temporarily blocked because of a blocking event in a course.
14541:
14542: =item *
14543:
14544: constructaccess($url,$setpriv) : check for access to construction space URL
14545:
14546: See if the owner domain and name in the URL match those in the
14547: expected environment. If so, return three element list
14548: ($ownername,$ownerdomain,$ownerhome).
14549:
14550: Otherwise return the null string.
14551:
14552: If second argument 'setpriv' is true, it assigns the privileges,
14553: and returns the same three element list, unless the owner has
14554: blocked "ad hoc" Domain Coordinator access to the Author Space,
14555: in which case the null string is returned.
14556:
14557: =item *
14558:
14559: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14560: define a custom role rolename set privileges in format of lonTabs/roles.tab
14561: for system, domain, and course level. $uname and $udom are optional (current
14562: user's username and domain will be used when either of $uname or $udom are absent.
14563:
14564: =item *
14565:
14566: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14567: (rolesplain.tab); plain text explanation of a user role term.
14568: $type is Course (default) or Community.
14569: If $forcedefault evaluates to true, text returned will be default
14570: text for $type. Otherwise, if this is a course, the text returned
14571: will be a custom name for the role (if defined in the course's
14572: environment). If no custom name is defined the default is returned.
14573:
14574: =item *
14575:
14576: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14577: All arguments are optional. Returns a hash of a roles, either for
14578: co-author/assistant author roles for a user's Construction Space
14579: (default), or if $context is 'userroles', roles for the user himself,
14580: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14581: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14582: For each key, value is set to colon-separated start and end times for
14583: the role. If no username and domain are specified, will default to
14584: current user/domain. Types, roles, and roledoms are references to arrays
14585: of role statuses (active, future or previous), roles
14586: (e.g., cc,in, st etc.) and domains of the roles which can be used
14587: to restrict the list of roles reported. If no array ref is
14588: provided for types, will default to return only active roles.
14589:
14590: =item *
14591:
14592: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14593: user: $uname:$udom has a role in the course: $cdom_$cnum.
14594:
14595: Additional optional arguments are: $type (if role checking is to be restricted
14596: to certain user status types -- previous (expired roles), active (currently
14597: available roles) or future (roles available in the future), and
14598: $hideprivileged -- if true will not report course roles for users who
14599: have active Domain Coordinator role in course's domain or in additional
14600: domains (specified in 'Domains to check for privileged users' in course
14601: environment -- set via: Course Settings -> Classlists and staff listing).
14602:
14603: =item *
14604:
14605: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14606: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14607: $possdomains and $possroles are optional array refs -- to domains to check and
14608: roles to check. If $possdomains is not specified, a dump will be done of the
14609: users' roles.db to check for a dc or su role in any domain. This can be
14610: time consuming if &privileged is called repeatedly (e.g., when displaying a
14611: classlist), so in such cases, supplying a $possdomains array is preferred, as
14612: this then allows &privileged_by_domain() to be used, which caches the identity
14613: of privileged users, eliminating the need for repeated calls to &dump().
14614:
14615: =item *
14616:
14617: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14618: where the outer hash keys are domains specified in the $possdomains array ref,
14619: next inner hash keys are privileged roles specified in the $roles array ref,
14620: and the innermost hash contains key = value pairs for username:domain = end:start
14621: for active or future "privileged" users with that role in that domain. To avoid
14622: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14623: innerhash are cached using priv_$role and $dom as the identifiers.
14624:
14625: =back
14626:
14627: =head2 User Modification
14628:
14629: =over 4
14630:
14631: =item *
14632:
14633: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14634: user for the level given by URL. Optional start and end dates (leave empty
14635: string or zero for "no date")
14636:
14637: =item *
14638:
14639: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14640: change a users, password, possible return values are: ok,
14641: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14642: refused
14643:
14644: =item *
14645:
14646: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14647:
14648: =item *
14649:
14650: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14651: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14652:
14653: will update user information (firstname,middlename,lastname,generation,
14654: permanentemail), and if forceid is true, student/employee ID also.
14655: A user's institutional affiliation(s) can also be updated.
14656: User information fields will not be overwritten with empty entries
14657: unless the field is included in the $candelete array reference.
14658: This array is included when a single user is modified via "Manage Users",
14659: or when Autoupdate.pl is run by cron in a domain.
14660:
14661: =item *
14662:
14663: modifystudent
14664:
14665: modify a student's enrollment and identification information.
14666: The course id is resolved based on the current user's environment.
14667: This means the invoking user must be a course coordinator or otherwise
14668: associated with a course.
14669:
14670: This call is essentially a wrapper for lonnet::modifyuser and
14671: lonnet::modify_student_enrollment
14672:
14673: Inputs:
14674:
14675: =over 4
14676:
14677: =item B<$udom> Student's loncapa domain
14678:
14679: =item B<$uname> Student's loncapa login name
14680:
14681: =item B<$uid> Student/Employee ID
14682:
14683: =item B<$umode> Student's authentication mode
14684:
14685: =item B<$upass> Student's password
14686:
14687: =item B<$first> Student's first name
14688:
14689: =item B<$middle> Student's middle name
14690:
14691: =item B<$last> Student's last name
14692:
14693: =item B<$gene> Student's generation
14694:
14695: =item B<$usec> Student's section in course
14696:
14697: =item B<$end> Unix time of the roles expiration
14698:
14699: =item B<$start> Unix time of the roles start date
14700:
14701: =item B<$forceid> If defined, allow $uid to be changed
14702:
14703: =item B<$desiredhome> server to use as home server for student
14704:
14705: =item B<$email> Student's permanent e-mail address
14706:
14707: =item B<$type> Type of enrollment (auto or manual)
14708:
14709: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14710:
14711: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14712:
14713: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14714:
14715: =item B<$context> role change context (shown in User Management Logs display in a course)
14716:
14717: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14718:
14719: =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.
14720:
14721: =back
14722:
14723: =item *
14724:
14725: modify_student_enrollment
14726:
14727: Change a student's enrollment status in a class. The environment variable
14728: 'role.request.course' must be defined for this function to proceed.
14729:
14730: Inputs:
14731:
14732: =over 4
14733:
14734: =item $udom, student's domain
14735:
14736: =item $uname, student's name
14737:
14738: =item $uid, student's user id
14739:
14740: =item $first, student's first name
14741:
14742: =item $middle
14743:
14744: =item $last
14745:
14746: =item $gene
14747:
14748: =item $usec
14749:
14750: =item $end
14751:
14752: =item $start
14753:
14754: =item $type
14755:
14756: =item $locktype
14757:
14758: =item $cid
14759:
14760: =item $selfenroll
14761:
14762: =item $context
14763:
14764: =item $credits, number of credits student will earn from this class
14765:
14766: =item $instsec, institutional course section code for student
14767:
14768: =back
14769:
14770:
14771: =item *
14772:
14773: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14774: custom role; give a custom role to a user for the level given by URL. Specify
14775: name and domain of role author, and role name
14776:
14777: =item *
14778:
14779: revokerole($udom,$uname,$url,$role) : revoke a role for url
14780:
14781: =item *
14782:
14783: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14784:
14785: =back
14786:
14787: =head2 Course Infomation
14788:
14789: =over 4
14790:
14791: =item *
14792:
14793: coursedescription($courseid,$options) : returns a hash of information about the
14794: specified course id, including all environment settings for the
14795: course, the description of the course will be in the hash under the
14796: key 'description'
14797:
14798: $options is an optional parameter that if supplied is a hash reference that controls
14799: what how this function works. It has the following key/values:
14800:
14801: =over 4
14802:
14803: =item freshen_cache
14804:
14805: If defined, and the environment cache for the course is valid, it is
14806: returned in the returned hash.
14807:
14808: =item one_time
14809:
14810: If defined, the last cache time is set to _now_
14811:
14812: =item user
14813:
14814: If defined, the supplied username is used instead of the current user.
14815:
14816:
14817: =back
14818:
14819: =item *
14820:
14821: resdata($name,$domain,$type,@which) : request for current parameter
14822: setting for a specific $type, where $type is either 'course' or 'user',
14823: @what should be a list of parameters to ask about. This routine caches
14824: answers for 10 minutes.
14825:
14826: =item *
14827:
14828: get_courseresdata($courseid, $domain) : dump the entire course resource
14829: data base, returning a hash that is keyed by the resource name and has
14830: values that are the resource value. I believe that the timestamps and
14831: versions are also returned.
14832:
14833: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14834: supplemental content area. This routine caches the number of files for
14835: 10 minutes.
14836:
14837: =back
14838:
14839: =head2 Course Modification
14840:
14841: =over 4
14842:
14843: =item *
14844:
14845: writecoursepref($courseid,%prefs) : write preferences (environment
14846: database) for a course
14847:
14848: =item *
14849:
14850: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14851:
14852: =item *
14853:
14854: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14855:
14856: =item *
14857:
14858: is_course($courseid), is_course($cdom, $cnum)
14859:
14860: Accepts either a combined $courseid (in the form of domain_courseid) or the
14861: two component version $cdom, $cnum. It checks if the specified course exists.
14862:
14863: Returns:
14864: undef if the course doesn't exist, otherwise
14865: in scalar context the combined courseid.
14866: in list context the two components of the course identifier, domain and
14867: courseid.
14868:
14869: =back
14870:
14871: =head2 Bubblesheet Configuration
14872:
14873: =over 4
14874:
14875: =item *
14876:
14877: get_scantron_config($which)
14878:
14879: $which - the name of the configuration to parse from the file.
14880:
14881: Parses and returns the bubblesheet configuration line selected as a
14882: hash of configuration file fields.
14883:
14884:
14885: Returns:
14886: If the named configuration is not in the file, an empty
14887: hash is returned.
14888:
14889: a hash with the fields
14890: name - internal name for the this configuration setup
14891: description - text to display to operator that describes this config
14892: CODElocation - if 0 or the string 'none'
14893: - no CODE exists for this config
14894: if -1 || the string 'letter'
14895: - a CODE exists for this config and is
14896: a string of letters
14897: Unsupported value (but planned for future support)
14898: if a positive integer
14899: - The CODE exists as the first n items from
14900: the question section of the form
14901: if the string 'number'
14902: - The CODE exists for this config and is
14903: a string of numbers
14904: CODEstart - (only matter if a CODE exists) column in the line where
14905: the CODE starts
14906: CODElength - length of the CODE
14907: IDstart - column where the student/employee ID starts
14908: IDlength - length of the student/employee ID info
14909: Qstart - column where the information from the bubbled
14910: 'questions' start
14911: Qlength - number of columns comprising a single bubble line from
14912: the sheet. (usually either 1 or 10)
14913: Qon - either a single character representing the character used
14914: to signal a bubble was chosen in the positional setup, or
14915: the string 'letter' if the letter of the chosen bubble is
14916: in the final, or 'number' if a number representing the
14917: chosen bubble is in the file (1->A 0->J)
14918: Qoff - the character used to represent that a bubble was
14919: left blank
14920: PaperID - if the scanning process generates a unique number for each
14921: sheet scanned the column that this ID number starts in
14922: PaperIDlength - number of columns that comprise the unique ID number
14923: for the sheet of paper
14924: FirstName - column that the first name starts in
14925: FirstNameLength - number of columns that the first name spans
14926: LastName - column that the last name starts in
14927: LastNameLength - number of columns that the last name spans
14928: BubblesPerRow - number of bubbles available in each row used to
14929: bubble an answer. (If not specified, 10 assumed).
14930:
14931:
14932: =item *
14933:
14934: get_scantronformat_file($cdom)
14935:
14936: $cdom - the course's domain (optional); if not supplied, uses
14937: domain for current $env{'request.course.id'}.
14938:
14939: Returns an array containing lines from the scantron format file for
14940: the domain of the course.
14941:
14942: If a url for a custom.tab file is listed in domain's configuration.db,
14943: lines are from this file.
14944:
14945: Otherwise, if a default.tab has been published in RES space by the
14946: domainconfig user, lines are from this file.
14947:
14948: Otherwise, fall back to getting lines from the legacy file on the
14949: local server: /home/httpd/lonTabs/default_scantronformat.tab
14950:
14951: =back
14952:
14953: =head2 Resource Subroutines
14954:
14955: =over 4
14956:
14957: =item *
14958:
14959: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14960:
14961: =item *
14962:
14963: repcopy($filename) : subscribes to the requested file, and attempts to
14964: replicate from the owning library server, Might return
14965: 'unavailable', 'not_found', 'forbidden', 'ok', or
14966: 'bad_request', also attempts to grab the metadata for the
14967: resource. Expects the local filesystem pathname
14968: (/home/httpd/html/res/....)
14969:
14970: =back
14971:
14972: =head2 Resource Information
14973:
14974: =over 4
14975:
14976: =item *
14977:
14978: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14979: and returns the value of a variety of different possible values,
14980: $varname should be a request string, and the other parameters can be
14981: used to specify who and what one is asking about. Ordinarily, $cid
14982: does not need to be specified, as it is retrived from
14983: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14984: within lonuserstate::loadmap() when initializing a course, before
14985: $env{'request.course.id'} has been set, so it needs to be provided
14986: in that one case.
14987:
14988: Possible values for $varname are environment.lastname (or other item
14989: from the envirnment hash), user.name (or someother aspect about the
14990: user), resource.0.maxtries (or some other part and parameter of a
14991: resource)
14992:
14993: =item *
14994:
14995: directcondval($number) : get current value of a condition; reads from a state
14996: string
14997:
14998: =item *
14999:
15000: condval($condidx) : value of condition index based on state
15001:
15002: =item *
15003:
15004: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
15005: resource's metadata, $what should be either a specific key, or either
15006: 'keys' (to get a list of possible keys) or 'packages' to get a list of
15007: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
15008:
15009: this function automatically caches all requests
15010:
15011: =item *
15012:
15013: metadata_query($query,$custom,$customshow) : make a metadata query against the
15014: network of library servers; returns file handle of where SQL and regex results
15015: will be stored for query
15016:
15017: =item *
15018:
15019: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
15020: return symbolic list entry (all arguments optional).
15021:
15022: Args: filename is the filename (including path) for the file for which a symb
15023: is required; donotrecurse, if true will prevent calls to allowed() being made
15024: to check access status if more than one resource was found in the bighash
15025: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
15026: a randompick); ignorecachednull, if true will prevent a symb of '' being
15027: returned if $env{$cache_str} is defined as ''; checkforblock if true will
15028: cause possible symbs to be checked to determine if they are subject to content
15029: blocking, if so they will not be included as possible symbs; possibles is a
15030: ref to a hash, which, as a side effect, will be populated with all possible
15031: symbs (content blocking not tested).
15032:
15033: returns the data handle
15034:
15035: =item *
15036:
15037: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
15038: and is a possible symb for the URL in $thisfn, and if is an encrypted
15039: resource that the user accessed using /enc/ returns a 1 on success, 0
15040: on failure, user must be in a course, as it assumes the existence of
15041: the course initial hash, and uses $env('request.course.id'}. The third
15042: arg is an optional reference to a scalar. If this arg is passed in the
15043: call to symbverify, it will be set to 1 if the symb has been set to be
15044: encrypted; otherwise it will be null.
15045:
15046: =item *
15047:
15048: symbclean($symb) : removes versions numbers from a symb, returns the
15049: cleaned symb
15050:
15051: =item *
15052:
15053: is_on_map($uri) : checks if the $uri is somewhere on the current
15054: course map, user must be in a course for it to work.
15055:
15056: =item *
15057:
15058: numval($salt) : return random seed value (addend for rndseed)
15059:
15060: =item *
15061:
15062: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
15063: a random seed, all arguments are optional, if they aren't sent it uses the
15064: environment to derive them. Note: if symb isn't sent and it can't get one
15065: from &symbread it will use the current time as its return value
15066:
15067: =item *
15068:
15069: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
15070: unfakeable, receipt
15071:
15072: =item *
15073:
15074: receipt() : API to ireceipt working off of env values; given out to users
15075:
15076: =item *
15077:
15078: countacc($url) : count the number of accesses to a given URL
15079:
15080: =item *
15081:
15082: 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
15083:
15084: =item *
15085:
15086: 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)
15087:
15088: =item *
15089:
15090: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
15091:
15092: =item *
15093:
15094: devalidate($symb) : devalidate temporary spreadsheet calculations,
15095: forcing spreadsheet to reevaluate the resource scores next time.
15096:
15097: =item *
15098:
15099: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
15100: when viewing in course context.
15101:
15102: input: six args -- filename (decluttered), course number, course domain,
15103: url, symb (if registered) and group (if this is a
15104: group item -- e.g., bulletin board, group page etc.).
15105:
15106: output: array of five scalars --
15107: $cfile -- url for file editing if editable on current server
15108: $home -- homeserver of resource (i.e., for author if published,
15109: or course if uploaded.).
15110: $switchserver -- 1 if server switch will be needed.
15111: $forceedit -- 1 if icon/link should be to go to edit mode
15112: $forceview -- 1 if icon/link should be to go to view mode
15113:
15114: =item *
15115:
15116: is_course_upload($file,$cnum,$cdom)
15117:
15118: Used in course context to determine if current file was uploaded to
15119: the course (i.e., would be found in /userfiles/docs on the course's
15120: homeserver.
15121:
15122: input: 3 args -- filename (decluttered), course number and course domain.
15123: output: boolean -- 1 if file was uploaded.
15124:
15125: =back
15126:
15127: =head2 Storing/Retreiving Data
15128:
15129: =over 4
15130:
15131: =item *
15132:
15133: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
15134: permanently for this url; hashref needs to be given and should be a \%hashname;
15135: the remaining args aren't required and if they aren't passed or are '' they will
15136: be derived from the env (with the exception of $laststore, which is an
15137: optional arg used when a user's submission is stored in grading).
15138: $laststore is $version=$timestamp, where $version is the most recent version
15139: number retrieved for the corresponding $symb in the $namespace db file, and
15140: $timestamp is the timestamp for that transaction (UNIX time).
15141: $laststore is currently only passed when cstore() is called by
15142: structuretags::finalize_storage().
15143:
15144: =item *
15145:
15146: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15147: but uses critical subroutine
15148:
15149: =item *
15150:
15151: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15152: all args are optional
15153:
15154: =item *
15155:
15156: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15157: dumps the complete (or key matching regexp) namespace into a hash
15158: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15159: normally &store()ed into
15160:
15161: $range should be either an integer '100' (give me the first 100
15162: matching records)
15163: or be two integers sperated by a - with no spaces
15164: '30-50' (give me the 30th through the 50th matching
15165: records)
15166:
15167:
15168: =item *
15169:
15170: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15171: replaces a &store() version of data with a replacement set of data
15172: for a particular resource in a namespace passed in the $storehash hash
15173: reference. If $tolog is true, the transaction is logged in the courselog
15174: with an action=PUTSTORE.
15175:
15176: =item *
15177:
15178: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15179: works very similar to store/cstore, but all data is stored in a
15180: temporary location and can be reset using tmpreset, $storehash should
15181: be a hash reference, returns nothing on success
15182:
15183: =item *
15184:
15185: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15186: similar to restore, but all data is stored in a temporary location and
15187: can be reset using tmpreset. Returns a hash of values on success,
15188: error string otherwise.
15189:
15190: =item *
15191:
15192: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15193: deltes all keys for $symb form the temporary storage hash.
15194:
15195: =item *
15196:
15197: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15198: reference filled in from namesp ($udom and $uname are optional)
15199:
15200: =item *
15201:
15202: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15203: namesp ($udom and $uname are optional)
15204:
15205: =item *
15206:
15207: dump($namespace,$udom,$uname,$regexp,$range) :
15208: dumps the complete (or key matching regexp) namespace into a hash
15209: ($udom, $uname, $regexp, $range are optional)
15210:
15211: $range should be either an integer '100' (give me the first 100
15212: matching records)
15213: or be two integers sperated by a - with no spaces
15214: '30-50' (give me the 30th through the 50th matching
15215: records)
15216: =item *
15217:
15218: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15219: $store can be a scalar, an array reference, or if the amount to be
15220: incremented is > 1, a hash reference.
15221:
15222: ($udom and $uname are optional)
15223:
15224: =item *
15225:
15226: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15227: ($udom and $uname are optional)
15228:
15229: =item *
15230:
15231: cput($namespace,$storehash,$udom,$uname) : critical put
15232: ($udom and $uname are optional)
15233:
15234: =item *
15235:
15236: newput($namespace,$storehash,$udom,$uname) :
15237:
15238: Attempts to store the items in the $storehash, but only if they don't
15239: currently exist, if this succeeds you can be certain that you have
15240: successfully created a new key value pair in the $namespace db.
15241:
15242:
15243: Args:
15244: $namespace: name of database to store values to
15245: $storehash: hashref to store to the db
15246: $udom: (optional) domain of user containing the db
15247: $uname: (optional) name of user caontaining the db
15248:
15249: Returns:
15250: 'ok' -> succeeded in storing all keys of $storehash
15251: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15252: least <key> already existed in the db (other
15253: requested keys may also already exist)
15254: 'error: <msg>' -> unable to tie the DB or other error occurred
15255: 'con_lost' -> unable to contact request server
15256: 'refused' -> action was not allowed by remote machine
15257:
15258:
15259: =item *
15260:
15261: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15262: reference filled in from namesp (encrypts the return communication)
15263: ($udom and $uname are optional)
15264:
15265: =item *
15266:
15267: log($udom,$name,$home,$message) : write to permanent log for user; use
15268: critical subroutine
15269:
15270: =item *
15271:
15272: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15273: array reference filled in from namespace found in domain level on either
15274: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15275:
15276: =item *
15277:
15278: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15279: domain level either on specified domain server ($uhome) or primary domain
15280: server ($udom and $uhome are optional)
15281:
15282: =item *
15283:
15284: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15285: for: authentication, language, quotas, timezone, date locale, and portal URL in
15286: the target domain.
15287:
15288: May also include additional key => value pairs for the following groups:
15289:
15290: =over
15291:
15292: =item
15293: disk quotas (MB allocated by default to portfolios and authoring spaces).
15294:
15295: =over
15296:
15297: =item defaultquota, authorquota
15298:
15299: =back
15300:
15301: =item
15302: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15303: portfolio for users).
15304:
15305: =over
15306:
15307: =item
15308: aboutme, blog, webdav, portfolio
15309:
15310: =back
15311:
15312: =item
15313: requestcourses: ability to request courses, and how requests are processed.
15314:
15315: =over
15316:
15317: =item
15318: official, unofficial, community, textbook
15319:
15320: =back
15321:
15322: =item
15323: inststatus: types of institutional affiliation, and order in which they are displayed.
15324:
15325: =over
15326:
15327: =item
15328: inststatustypes, inststatusorder, inststatusguest
15329:
15330: =back
15331:
15332: =item
15333: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15334: for course's uploaded content.
15335:
15336: =over
15337:
15338: =item
15339: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15340: communityquota, textbookquota
15341:
15342: =back
15343:
15344: =item
15345: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15346: on your servers.
15347:
15348: =over
15349:
15350: =item
15351: remotesessions, hostedsessions
15352:
15353: =back
15354:
15355: =back
15356:
15357: In cases where a domain coordinator has never used the "Set Domain Configuration"
15358: utility to create a configuration.db file on a domain's primary library server
15359: only the following domain defaults: auth_def, auth_arg_def, lang_def
15360: -- corresponding values are authentication type (internal, krb4, krb5,
15361: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15362: will be available. Values are retrieved from cache (if current), unless the
15363: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15364: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15365:
15366: Typical usage:
15367:
15368: %domdefaults = &get_domain_defaults($target_domain);
15369:
15370: =back
15371:
15372: =head2 Network Status Functions
15373:
15374: =over 4
15375:
15376: =item *
15377:
15378: dirlist() : return directory list based on URI (first arg).
15379:
15380: Inputs: 1 required, 5 optional.
15381:
15382: =over
15383:
15384: =item
15385: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15386:
15387: =item
15388: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15389:
15390: =item
15391: $username - username of user/course to be listed. Extracted from $uri if absent.
15392:
15393: =item
15394: $getpropath - boolean: 1 if prepend path using &propath().
15395:
15396: =item
15397: $getuserdir - boolean: 1 if prepend path for "userfiles".
15398:
15399: =item
15400: $alternateRoot - path to prepend in place of path from $uri.
15401:
15402: =back
15403:
15404: Returns: Array of up to two items.
15405:
15406: =over
15407:
15408: a reference to an array of files/subdirectories
15409:
15410: =over
15411:
15412: Each element in the array of files/subdirectories is a & separated list of
15413: item name and the result of running stat on the item. If dirlist was requested
15414: for a file instead of a directory, the item name will be ''. For a directory
15415: listing, if the item is a metadata file, the element will end &N&M
15416: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15417: default copyright set (1).
15418:
15419: =back
15420:
15421: a scalar containing error condition (if encountered).
15422:
15423: =over
15424:
15425: =item
15426: no_host (no homeserver identified for $username:$domain).
15427:
15428: =item
15429: no_such_host (server contacted for listing not identified as valid host).
15430:
15431: =item
15432: con_lost (connection to remote server failed).
15433:
15434: =item
15435: refused (invalid $username:$domain received on lond side).
15436:
15437: =item
15438: no_such_dir (directory at specified path on lond side does not exist).
15439:
15440: =item
15441: empty (directory at specified path on lond side is empty).
15442:
15443: =over
15444:
15445: This is currently not encountered because the &ls3, &ls2,
15446: &ls (_handler) routines on the lond side do not filter out
15447: . and .. from a directory listing.
15448:
15449: =back
15450:
15451: =back
15452:
15453: =back
15454:
15455: =item *
15456:
15457: spareserver() : find server with least workload from spare.tab
15458:
15459:
15460: =item *
15461:
15462: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15463: if there is no corresponding loncapa host.
15464:
15465: =back
15466:
15467:
15468: =head2 Apache Request
15469:
15470: =over 4
15471:
15472: =item *
15473:
15474: ssi($url,%hash) : server side include, does a complete request cycle on url to
15475: localhost, posts hash
15476:
15477: =back
15478:
15479: =head2 Data to String to Data
15480:
15481: =over 4
15482:
15483: =item *
15484:
15485: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15486: and '&' separators, supports elements that are arrayrefs and hashrefs
15487:
15488: =item *
15489:
15490: hashref2str($hashref) : convert a hashref into a string complete with
15491: escaping and '=' and '&' separators, supports elements that are
15492: arrayrefs and hashrefs
15493:
15494: =item *
15495:
15496: arrayref2str($arrayref) : convert an arrayref into a string complete
15497: with escaping and '&' separators, supports elements that are arrayrefs
15498: and hashrefs
15499:
15500: =item *
15501:
15502: str2hash($string) : convert string to hash using unescaping and
15503: splitting on '=' and '&', supports elements that are arrayrefs and
15504: hashrefs
15505:
15506: =item *
15507:
15508: str2array($string) : convert string to hash using unescaping and
15509: splitting on '&', supports elements that are arrayrefs and hashrefs
15510:
15511: =back
15512:
15513: =head2 Logging Routines
15514:
15515:
15516: These routines allow one to make log messages in the lonnet.log and
15517: lonnet.perm logfiles.
15518:
15519: =over 4
15520:
15521: =item *
15522:
15523: logtouch() : make sure the logfile, lonnet.log, exists
15524:
15525: =item *
15526:
15527: logthis() : append message to the normal lonnet.log file, it gets
15528: preiodically rolled over and deleted.
15529:
15530: =item *
15531:
15532: logperm() : append a permanent message to lonnet.perm.log, this log
15533: file never gets deleted by any automated portion of the system, only
15534: messages of critical importance should go in here.
15535:
15536:
15537: =back
15538:
15539: =head2 General File Helper Routines
15540:
15541: =over 4
15542:
15543: =item *
15544:
15545: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15546: (a) files in /uploaded
15547: (i) If a local copy of the file exists -
15548: compares modification date of local copy with last-modified date for
15549: definitive version stored on home server for course. If local copy is
15550: stale, requests a new version from the home server and stores it.
15551: If the original has been removed from the home server, then local copy
15552: is unlinked.
15553: (ii) If local copy does not exist -
15554: requests the file from the home server and stores it.
15555:
15556: If $caller is 'uploadrep':
15557: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15558: for request for files originally uploaded via DOCS.
15559: - returns 'ok' if fresh local copy now available, -1 otherwise.
15560:
15561: Otherwise:
15562: This indicates a call from the content generation phase of the request.
15563: - returns the entire contents of the file or -1.
15564:
15565: (b) files in /res
15566: - returns the entire contents of a file or -1;
15567: it properly subscribes to and replicates the file if neccessary.
15568:
15569:
15570: =item *
15571:
15572: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15573: reference
15574:
15575: returns either a stat() list of data about the file or an empty list
15576: if the file doesn't exist or couldn't find out about it (connection
15577: problems or user unknown)
15578:
15579: =item *
15580:
15581: filelocation($dir,$file) : returns file system location of a file
15582: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15583: directory that relative $file lookups are to looked in ($dir of /a/dir
15584: and a file of ../bob will become /a/bob)
15585:
15586: =item *
15587:
15588: hreflocation($dir,$file) : returns file system location or a URL; same as
15589: filelocation except for hrefs
15590:
15591: =item *
15592:
15593: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15594: also removes beginning /home/httpd/html unless /priv/ follows it.
15595:
15596: =back
15597:
15598: =head2 Usererfile file routines (/uploaded*)
15599:
15600: =over 4
15601:
15602: =item *
15603:
15604: userfileupload(): main rotine for putting a file in a user or course's
15605: filespace, arguments are,
15606:
15607: formname - required - this is the name of the element in $env where the
15608: filename, and the contents of the file to create/modifed exist
15609: the filename is in $env{'form.'.$formname.'.filename'} and the
15610: contents of the file is located in $env{'form.'.$formname}
15611: context - if coursedoc, store the file in the course of the active role
15612: of the current user;
15613: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15614: if 'canceloverwrite': delete file in tmp/overwrites directory
15615: subdir - required - subdirectory to put the file in under ../userfiles/
15616: if undefined, it will be placed in "unknown"
15617:
15618: (This routine calls clean_filename() to remove any dangerous
15619: characters from the filename, and then calls finuserfileupload() to
15620: complete the transaction)
15621:
15622: returns either the url of the uploaded file (/uploaded/....) if successful
15623: and /adm/notfound.html if unsuccessful
15624:
15625: =item *
15626:
15627: clean_filename(): routine for cleaing a filename up for storage in
15628: userfile space, argument is:
15629:
15630: filename - proposed filename
15631:
15632: returns: the new clean filename
15633:
15634: =item *
15635:
15636: finishuserfileupload(): routine that creates and sends the file to
15637: userspace, probably shouldn't be called directly
15638:
15639: docuname: username or courseid of destination for the file
15640: docudom: domain of user/course of destination for the file
15641: formname: same as for userfileupload()
15642: fname: filename (including subdirectories) for the file
15643: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15644: if hashref, and context is scantron, will convert csv format to standard format
15645: allfiles: reference to hash used to store objects found by parser
15646: codebase: reference to hash used for codebases of java objects found by parser
15647: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15648: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15649: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15650: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15651: context: if 'overwrite', will move the uploaded file from its temporary location to
15652: userfiles to facilitate overwriting a previously uploaded file with same name.
15653: mimetype: reference to scalar to accommodate mime type determined
15654: from File::MMagic if $parser = parse.
15655:
15656: returns either the url of the uploaded file (/uploaded/....) if successful
15657: and /adm/notfound.html if unsuccessful (or an error message if context
15658: was 'overwrite').
15659:
15660:
15661: =item *
15662:
15663: renameuserfile(): renames an existing userfile to a new name
15664:
15665: Args:
15666: docuname: username or courseid of destination for the file
15667: docudom: domain of user/course of destination for the file
15668: old: current file name (including any subdirs under userfiles)
15669: new: desired file name (including any subdirs under userfiles)
15670:
15671: =item *
15672:
15673: mkdiruserfile(): creates a directory is a userfiles dir
15674:
15675: Args:
15676: docuname: username or courseid of destination for the file
15677: docudom: domain of user/course of destination for the file
15678: dir: dir to create (including any subdirs under userfiles)
15679:
15680: =item *
15681:
15682: removeuserfile(): removes a file that exists in userfiles
15683:
15684: Args:
15685: docuname: username or courseid of destination for the file
15686: docudom: domain of user/course of destination for the file
15687: fname: filname to delete (including any subdirs under userfiles)
15688:
15689: =item *
15690:
15691: removeuploadedurl(): convience function for removeuserfile()
15692:
15693: Args:
15694: url: a full /uploaded/... url to delete
15695:
15696: =item *
15697:
15698: get_portfile_permissions():
15699: Args:
15700: domain: domain of user or course contain the portfolio files
15701: user: name of user or num of course contain the portfolio files
15702: Returns:
15703: hashref of a dump of the proper file_permissions.db
15704:
15705:
15706: =item *
15707:
15708: get_access_controls():
15709:
15710: Args:
15711: current_permissions: the hash ref returned from get_portfile_permissions()
15712: group: (optional) the group you want the files associated with
15713: file: (optional) the file you want access info on
15714:
15715: Returns:
15716: a hash (keys are file names) of hashes containing
15717: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15718: values are XML containing access control settings (see below)
15719:
15720: Internal notes:
15721:
15722: access controls are stored in file_permissions.db as key=value pairs.
15723: key -> path to file/file_name\0uniqueID:scope_end_start
15724: where scope -> public,guest,course,group,domains or users.
15725: end -> UNIX time for end of access (0 -> no end date)
15726: start -> UNIX time for start of access
15727:
15728: value -> XML description of access control
15729: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15730: <start></start>
15731: <end></end>
15732:
15733: <password></password> for scope type = guest
15734:
15735: <domain></domain> for scope type = course or group
15736: <number></number>
15737: <roles id="">
15738: <role></role>
15739: <access></access>
15740: <section></section>
15741: <group></group>
15742: </roles>
15743:
15744: <dom></dom> for scope type = domains
15745:
15746: <users> for scope type = users
15747: <user>
15748: <uname></uname>
15749: <udom></udom>
15750: </user>
15751: </users>
15752: </scope>
15753:
15754: Access data is also aggregated for each file in an additional key=value pair:
15755: key -> path to file/file_name\0accesscontrol
15756: value -> reference to hash
15757: hash contains key = value pairs
15758: where key = uniqueID:scope_end_start
15759: value = UNIX time record was last updated
15760:
15761: Used to improve speed of look-ups of access controls for each file.
15762:
15763: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15764:
15765: =item *
15766:
15767: modify_access_controls():
15768:
15769: Modifies access controls for a portfolio file
15770: Args
15771: 1. file name
15772: 2. reference to hash of required changes,
15773: 3. domain
15774: 4. username
15775: where domain,username are the domain of the portfolio owner
15776: (either a user or a course)
15777:
15778: Returns:
15779: 1. result of additions or updates ('ok' or 'error', with error message).
15780: 2. result of deletions ('ok' or 'error', with error message).
15781: 3. reference to hash of any new or updated access controls.
15782: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15783: key = integer (inbound ID)
15784: value = uniqueID
15785:
15786: =item *
15787:
15788: get_timebased_id():
15789:
15790: Attempts to get a unique timestamp-based suffix for use with items added to a
15791: course via the Course Editor (e.g., folders, composite pages,
15792: group bulletin boards).
15793:
15794: Args: (first three required; six others optional)
15795:
15796: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15797: docssequence, or name of group
15798:
15799: 2. keyid (alphanumeric): name of temporary locking key in hash,
15800: e.g., num, boardids
15801:
15802: 3. namespace: name of gdbm file used to store suffixes already assigned;
15803: file will be named nohist_namespace.db
15804:
15805: 4. cdom: domain of course; default is current course domain from %env
15806:
15807: 5. cnum: course number; default is current course number from %env
15808:
15809: 6. idtype: set to concat if an additional digit is to be appended to the
15810: unix timestamp to form the suffix, if the plain timestamp is already
15811: in use. Default is to not do this, but simply increment the unix
15812: timestamp by 1 until a unique key is obtained.
15813:
15814: 7. who: holder of locking key; defaults to user:domain for user.
15815:
15816: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15817: retrying); default is 3.
15818:
15819: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15820:
15821: Returns:
15822:
15823: 1. suffix obtained (numeric)
15824:
15825: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15826:
15827: 3. error: contains (localized) error message if an error occurred.
15828:
15829:
15830: =back
15831:
15832: =head2 HTTP Helper Routines
15833:
15834: =over 4
15835:
15836: =item *
15837:
15838: escape() : unpack non-word characters into CGI-compatible hex codes
15839:
15840: =item *
15841:
15842: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15843:
15844: =back
15845:
15846: =head1 PRIVATE SUBROUTINES
15847:
15848: =head2 Underlying communication routines (Shouldn't call)
15849:
15850: =over 4
15851:
15852: =item *
15853:
15854: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15855:
15856: =item *
15857:
15858: reply() : uses subreply to send a message to remote machine, logs all failures
15859:
15860: =item *
15861:
15862: critical() : passes a critical message to another server; if cannot
15863: get through then place message in connection buffer directory and
15864: returns con_delayed, if incapable of saving message, returns
15865: con_failed
15866:
15867: =item *
15868:
15869: reconlonc() : tries to reconnect lonc client processes.
15870:
15871: =back
15872:
15873: =head2 Resource Access Logging
15874:
15875: =over 4
15876:
15877: =item *
15878:
15879: flushcourselogs() : flush (save) buffer logs and access logs
15880:
15881: =item *
15882:
15883: courselog($what) : save message for course in hash
15884:
15885: =item *
15886:
15887: courseacclog($what) : save message for course using &courselog(). Perform
15888: special processing for specific resource types (problems, exams, quizzes, etc).
15889:
15890: =item *
15891:
15892: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15893: as a PerlChildExitHandler
15894:
15895: =back
15896:
15897: =head2 Other
15898:
15899: =over 4
15900:
15901: =item *
15902:
15903: symblist($mapname,%newhash) : update symbolic storage links
15904:
15905: =back
15906:
15907: =cut
15908:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>