1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1172.2.123 2020/05/04 15:07:10 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 $logentry = {
129: $id => {
130: 'exe_uname' => $env{'user.name'},
131: 'exe_udom' => $env{'user.domain'},
132: 'exe_time' => $now,
133: 'exe_ip' => $ENV{'REMOTE_ADDR'},
134: 'delflag' => $delflag,
135: 'logentry' => $storehash,
136: 'uname' => $uname,
137: 'udom' => $udom,
138: }
139: };
140: return &put('nohist_'.$hash_name,$logentry,$cdom,$cnum);
141: }
142: }
143:
144: sub logtouch {
145: my $execdir=$perlvar{'lonDaemons'};
146: unless (-e "$execdir/logs/lonnet.log") {
147: open(my $fh,">>","$execdir/logs/lonnet.log");
148: close $fh;
149: }
150: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
151: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
152: }
153:
154: sub logthis {
155: my $message=shift;
156: my $execdir=$perlvar{'lonDaemons'};
157: my $now=time;
158: my $local=localtime($now);
159: if (open(my $fh,">>","$execdir/logs/lonnet.log")) {
160: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
161: print $fh $logstring;
162: close($fh);
163: }
164: return 1;
165: }
166:
167: sub logperm {
168: my $message=shift;
169: my $execdir=$perlvar{'lonDaemons'};
170: my $now=time;
171: my $local=localtime($now);
172: if (open(my $fh,">>","$execdir/logs/lonnet.perm.log")) {
173: print $fh "$now:$message:$local\n";
174: close($fh);
175: }
176: return 1;
177: }
178:
179: sub create_connection {
180: my ($hostname,$lonid) = @_;
181: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
182: Type => SOCK_STREAM,
183: Timeout => 10);
184: return 0 if (!$client);
185: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
186: my $result = <$client>;
187: chomp($result);
188: return 1 if ($result eq 'done');
189: return 0;
190: }
191:
192: sub get_server_timezone {
193: my ($cnum,$cdom) = @_;
194: my $home=&homeserver($cnum,$cdom);
195: if ($home ne 'no_host') {
196: my $cachetime = 24*3600;
197: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
198: if (defined($cached)) {
199: return $timezone;
200: } else {
201: my $timezone = &reply('servertimezone',$home);
202: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
203: }
204: }
205: }
206:
207: sub get_server_distarch {
208: my ($lonhost,$ignore_cache) = @_;
209: if (defined($lonhost)) {
210: if (!defined(&hostname($lonhost))) {
211: return;
212: }
213: my $cachetime = 12*3600;
214: if (!$ignore_cache) {
215: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
216: if (defined($cached)) {
217: return $distarch;
218: }
219: }
220: my $rep = &reply('serverdistarch',$lonhost);
221: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
222: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
223: $rep eq '') {
224: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
225: }
226: }
227: return;
228: }
229:
230: sub get_server_loncaparev {
231: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
232: if (defined($lonhost)) {
233: if (!defined(&hostname($lonhost))) {
234: undef($lonhost);
235: }
236: }
237: if (!defined($lonhost)) {
238: if (defined(&domain($dom,'primary'))) {
239: $lonhost=&domain($dom,'primary');
240: if ($lonhost eq 'no_host') {
241: undef($lonhost);
242: }
243: }
244: }
245: if (defined($lonhost)) {
246: my $cachetime = 12*3600;
247: if (!$ignore_cache) {
248: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
249: if (defined($cached)) {
250: return $loncaparev;
251: }
252: }
253: my ($answer,$loncaparev);
254: my @ids=¤t_machine_ids();
255: if (grep(/^\Q$lonhost\E$/,@ids)) {
256: $answer = $perlvar{'lonVersion'};
257: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
258: $loncaparev = $1;
259: }
260: } else {
261: $answer = &reply('serverloncaparev',$lonhost);
262: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
263: if ($caller eq 'loncron') {
264: my $ua=new LWP::UserAgent;
265: $ua->timeout(4);
266: my $hostname = &hostname($lonhost);
267: my $protocol = $protocol{$lonhost};
268: $protocol = 'http' if ($protocol ne 'https');
269: my $url = $protocol.'://'.$hostname.'/adm/about.html';
270: my $request=new HTTP::Request('GET',$url);
271: my $response=$ua->request($request);
272: unless ($response->is_error()) {
273: my $content = $response->content;
274: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
275: $loncaparev = $1;
276: }
277: }
278: } else {
279: $loncaparev = $loncaparevs{$lonhost};
280: }
281: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
282: $loncaparev = $1;
283: }
284: }
285: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
286: }
287: }
288:
289: sub get_server_homeID {
290: my ($hostname,$ignore_cache,$caller) = @_;
291: unless ($ignore_cache) {
292: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
293: if (defined($cached)) {
294: return $serverhomeID;
295: }
296: }
297: my $cachetime = 12*3600;
298: my $serverhomeID;
299: if ($caller eq 'loncron') {
300: my @machine_ids = &machine_ids($hostname);
301: foreach my $id (@machine_ids) {
302: my $response = &reply('serverhomeID',$id);
303: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
304: $serverhomeID = $response;
305: last;
306: }
307: }
308: if ($serverhomeID eq '') {
309: $serverhomeID = $machine_ids[-1];
310: }
311: } else {
312: $serverhomeID = $serverhomeIDs{$hostname};
313: }
314: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
315: }
316:
317: sub get_remote_globals {
318: my ($lonhost,$whathash,$ignore_cache) = @_;
319: my ($result,%returnhash,%whatneeded);
320: if (ref($whathash) eq 'HASH') {
321: foreach my $what (sort(keys(%{$whathash}))) {
322: my $hashid = $lonhost.'-'.$what;
323: my ($response,$cached);
324: unless ($ignore_cache) {
325: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
326: }
327: if (defined($cached)) {
328: $returnhash{$what} = $response;
329: } else {
330: $whatneeded{$what} = 1;
331: }
332: }
333: if (keys(%whatneeded) == 0) {
334: $result = 'ok';
335: } else {
336: my $requested = &freeze_escape(\%whatneeded);
337: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
338: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
339: ($rep eq 'unknown_cmd')) {
340: $result = $rep;
341: } else {
342: $result = 'ok';
343: my @pairs=split(/\&/,$rep);
344: foreach my $item (@pairs) {
345: my ($key,$value)=split(/=/,$item,2);
346: my $what = &unescape($key);
347: my $hashid = $lonhost.'-'.$what;
348: $returnhash{$what}=&thaw_unescape($value);
349: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
350: }
351: }
352: }
353: }
354: return ($result,\%returnhash);
355: }
356:
357: sub remote_devalidate_cache {
358: my ($lonhost,$cachekeys) = @_;
359: my $items;
360: return unless (ref($cachekeys) eq 'ARRAY');
361: my $cachestr = join('&',@{$cachekeys});
362: return &reply('devalidatecache:'.&escape($cachestr),$lonhost);
363: }
364:
365: # -------------------------------------------------- Non-critical communication
366: sub subreply {
367: my ($cmd,$server)=@_;
368: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
369: #
370: # With loncnew process trimming, there's a timing hole between lonc server
371: # process exit and the master server picking up the listen on the AF_UNIX
372: # socket. In that time interval, a lock file will exist:
373:
374: my $lockfile=$peerfile.".lock";
375: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
376: sleep(0.1);
377: }
378: # At this point, either a loncnew parent is listening or an old lonc
379: # or loncnew child is listening so we can connect or everything's dead.
380: #
381: # We'll give the connection a few tries before abandoning it. If
382: # connection is not possible, we'll con_lost back to the client.
383: #
384: my $client;
385: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
386: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
387: Type => SOCK_STREAM,
388: Timeout => 10);
389: if ($client) {
390: last; # Connected!
391: } else {
392: &create_connection(&hostname($server),$server);
393: }
394: sleep(0.1); # Try again later if failed connection.
395: }
396: my $answer;
397: if ($client) {
398: print $client "sethost:$server:$cmd\n";
399: $answer=<$client>;
400: if (!$answer) { $answer="con_lost"; }
401: chomp($answer);
402: } else {
403: $answer = 'con_lost'; # Failed connection.
404: }
405: return $answer;
406: }
407:
408: sub reply {
409: my ($cmd,$server)=@_;
410: unless (defined(&hostname($server))) { return 'no_such_host'; }
411: my $answer=subreply($cmd,$server);
412: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
413: my $logged = $cmd;
414: if ($cmd =~ /^encrypt:([^:]+):/) {
415: my $subcmd = $1;
416: if (($subcmd eq 'auth') || ($subcmd eq 'passwd') ||
417: ($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
418: ($subcmd eq 'putdom') || ($subcmd eq 'autoexportgrades')) {
419: (undef,undef,my @rest) = split(/:/,$cmd);
420: if (($subcmd eq 'auth') || ($subcmd eq 'putdom')) {
421: splice(@rest,2,1,'Hidden');
422: } elsif ($subcmd eq 'passwd') {
423: splice(@rest,2,2,('Hidden','Hidden'));
424: } elsif (($subcmd eq 'changeuserauth') || ($subcmd eq 'makeuser') ||
425: ($subcmd eq 'autoexportgrades')) {
426: splice(@rest,3,1,'Hidden');
427: }
428: $logged = join(':',('encrypt:'.$subcmd,@rest));
429: }
430: }
431: &logthis("<font color=\"blue\">WARNING:".
432: " $logged to $server returned $answer</font>");
433: }
434: return $answer;
435: }
436:
437: # ----------------------------------------------------------- Send USR1 to lonc
438:
439: sub reconlonc {
440: my ($lonid) = @_;
441: if ($lonid) {
442: my $hostname = &hostname($lonid);
443: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
444: if ($hostname && -e $peerfile) {
445: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
446: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
447: Type => SOCK_STREAM,
448: Timeout => 10);
449: if ($client) {
450: print $client ("reset_retries\n");
451: my $answer=<$client>;
452: #reset just this one.
453: }
454: }
455: return;
456: }
457:
458: &logthis("Trying to reconnect lonc");
459: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
460: if (open(my $fh,"<",$loncfile)) {
461: my $loncpid=<$fh>;
462: chomp($loncpid);
463: if (kill 0 => $loncpid) {
464: &logthis("lonc at pid $loncpid responding, sending USR1");
465: kill USR1 => $loncpid;
466: sleep 1;
467: } else {
468: &logthis(
469: "<font color=\"blue\">WARNING:".
470: " lonc at pid $loncpid not responding, giving up</font>");
471: }
472: } else {
473: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
474: }
475: }
476:
477: # ------------------------------------------------------ Critical communication
478:
479: sub critical {
480: my ($cmd,$server)=@_;
481: unless (&hostname($server)) {
482: &logthis("<font color=\"blue\">WARNING:".
483: " Critical message to unknown server ($server)</font>");
484: return 'no_such_host';
485: }
486: my $answer=reply($cmd,$server);
487: if ($answer eq 'con_lost') {
488: &reconlonc($server);
489: my $answer=reply($cmd,$server);
490: if ($answer eq 'con_lost') {
491: my $now=time;
492: my $middlename=$cmd;
493: $middlename=substr($middlename,0,16);
494: $middlename=~s/\W//g;
495: my $dfilename=
496: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
497: $dumpcount++;
498: {
499: my $dfh;
500: if (open($dfh,">",$dfilename)) {
501: print $dfh "$cmd\n";
502: close($dfh);
503: }
504: }
505: sleep 1;
506: my $wcmd='';
507: {
508: my $dfh;
509: if (open($dfh,"<",$dfilename)) {
510: $wcmd=<$dfh>;
511: close($dfh);
512: }
513: }
514: chomp($wcmd);
515: if ($wcmd eq $cmd) {
516: &logthis("<font color=\"blue\">WARNING: ".
517: "Connection buffer $dfilename: $cmd</font>");
518: &logperm("D:$server:$cmd");
519: return 'con_delayed';
520: } else {
521: &logthis("<font color=\"red\">CRITICAL:"
522: ." Critical connection failed: $server $cmd</font>");
523: &logperm("F:$server:$cmd");
524: return 'con_failed';
525: }
526: }
527: }
528: return $answer;
529: }
530:
531: # ------------------------------------------- check if return value is an error
532:
533: sub error {
534: my ($result) = @_;
535: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
536: if ($2 == 2) { return undef; }
537: return $1;
538: }
539: return undef;
540: }
541:
542: sub convert_and_load_session_env {
543: my ($lonidsdir,$handle)=@_;
544: my @profile;
545: {
546: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
547: if (!$opened) {
548: return 0;
549: }
550: flock($idf,LOCK_SH);
551: @profile=<$idf>;
552: close($idf);
553: }
554: my %temp_env;
555: foreach my $line (@profile) {
556: if ($line !~ m/=/) {
557: return 0;
558: }
559: chomp($line);
560: my ($envname,$envvalue)=split(/=/,$line,2);
561: $temp_env{&unescape($envname)} = &unescape($envvalue);
562: }
563: unlink("$lonidsdir/$handle.id");
564: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
565: 0640)) {
566: %disk_env = %temp_env;
567: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
568: untie(%disk_env);
569: }
570: return 1;
571: }
572:
573: # ------------------------------------------- Transfer profile into environment
574: my $env_loaded;
575: sub transfer_profile_to_env {
576: my ($lonidsdir,$handle,$force_transfer) = @_;
577: if (!$force_transfer && $env_loaded) { return; }
578:
579: if (!defined($lonidsdir)) {
580: $lonidsdir = $perlvar{'lonIDsDir'};
581: }
582: if (!defined($handle)) {
583: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
584: }
585:
586: my $convert;
587: {
588: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
589: if (!$opened) {
590: return;
591: }
592: flock($idf,LOCK_SH);
593: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
594: &GDBM_READER(),0640)) {
595: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
596: untie(%disk_env);
597: } else {
598: $convert = 1;
599: }
600: }
601: if ($convert) {
602: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
603: &logthis("Failed to load session, or convert session.");
604: }
605: }
606:
607: my %remove;
608: while ( my $envname = each(%env) ) {
609: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
610: if ($time < time-300) {
611: $remove{$key}++;
612: }
613: }
614: }
615:
616: $env{'user.environment'} = "$lonidsdir/$handle.id";
617: $env_loaded=1;
618: foreach my $expired_key (keys(%remove)) {
619: &delenv($expired_key);
620: }
621: }
622:
623: # ---------------------------------------------------- Check for valid session
624: sub check_for_valid_session {
625: my ($r,$name,$userhashref,$domref) = @_;
626: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
627: my ($lonidsdir,$linkname,$pubname,$secure,$lonid);
628: if ($name eq 'lonDAV') {
629: $lonidsdir=$r->dir_config('lonDAVsessDir');
630: } else {
631: $lonidsdir=$r->dir_config('lonIDsDir');
632: if ($name eq '') {
633: $name = 'lonID';
634: }
635: }
636: if ($name eq 'lonID') {
637: $secure = 'lonSID';
638: $linkname = 'lonLinkID';
639: $pubname = 'lonPubID';
640: if (exists($cookies{$secure})) {
641: $lonid=$cookies{$secure};
642: } elsif (exists($cookies{$name})) {
643: $lonid=$cookies{$name};
644: } elsif ((exists($cookies{$linkname})) && ($ENV{'SERVER_PORT'} != 443)) {
645: $lonid=$cookies{$linkname};
646: } elsif (exists($cookies{$pubname})) {
647: $lonid=$cookies{$pubname};
648: }
649: } else {
650: $lonid=$cookies{$name};
651: }
652: return undef if (!$lonid);
653:
654: my $handle=&LONCAPA::clean_handle($lonid->value);
655: if (-l "$lonidsdir/$handle.id") {
656: my $link = readlink("$lonidsdir/$handle.id");
657: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
658: $handle = $1;
659: }
660: }
661: if (!-e "$lonidsdir/$handle.id") {
662: if ((ref($domref)) && ($name eq 'lonID') &&
663: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
664: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
665: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
666: $$domref = $possudom;
667: }
668: }
669: return undef;
670: }
671:
672: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
673: return undef if (!$opened);
674:
675: flock($idf,LOCK_SH);
676: my %disk_env;
677: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
678: &GDBM_READER(),0640)) {
679: return undef;
680: }
681:
682: if (!defined($disk_env{'user.name'})
683: || !defined($disk_env{'user.domain'})) {
684: untie(%disk_env);
685: return undef;
686: }
687:
688: if (ref($userhashref) eq 'HASH') {
689: $userhashref->{'name'} = $disk_env{'user.name'};
690: $userhashref->{'domain'} = $disk_env{'user.domain'};
691: }
692: untie(%disk_env);
693:
694: return $handle;
695: }
696:
697: sub timed_flock {
698: my ($file,$lock_type) = @_;
699: my $failed=0;
700: eval {
701: local $SIG{__DIE__}='DEFAULT';
702: local $SIG{ALRM}=sub {
703: $failed=1;
704: die("failed lock");
705: };
706: alarm(13);
707: flock($file,$lock_type);
708: alarm(0);
709: };
710: if ($failed) {
711: return undef;
712: } else {
713: return 1;
714: }
715: }
716:
717: sub get_sessionfile_vars {
718: my ($handle,$lonidsdir,$storearr) = @_;
719: my %returnhash;
720: unless (ref($storearr) eq 'ARRAY') {
721: return %returnhash;
722: }
723: if (-l "$lonidsdir/$handle.id") {
724: my $link = readlink("$lonidsdir/$handle.id");
725: if ((-e $link) && ($link =~ m{^\Q$lonidsdir\E/(.+)\.id$})) {
726: $handle = $1;
727: }
728: }
729: if ((-e "$lonidsdir/$handle.id") &&
730: ($handle =~ /^($match_username)\_\d+\_($match_domain)\_(.+)$/)) {
731: my ($possuname,$possudom,$possuhome) = ($1,$2,$3);
732: if ((&domain($possudom) ne '') && (&homeserver($possuname,$possudom) eq $possuhome)) {
733: if (open(my $idf,'+<',"$lonidsdir/$handle.id")) {
734: flock($idf,LOCK_SH);
735: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
736: &GDBM_READER(),0640)) {
737: foreach my $item (@{$storearr}) {
738: $returnhash{$item} = $disk_env{$item};
739: }
740: untie(%disk_env);
741: }
742: }
743: }
744: }
745: return %returnhash;
746: }
747:
748: # ---------------------------------------------------------- Append Environment
749:
750: sub appenv {
751: my ($newenv,$roles) = @_;
752: if (ref($newenv) eq 'HASH') {
753: foreach my $key (keys(%{$newenv})) {
754: my $refused = 0;
755: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
756: $refused = 1;
757: if (ref($roles) eq 'ARRAY') {
758: my ($type,$role) = ($key =~ m{^user\.(role|priv)\.(.+?)\./});
759: if (grep(/^\Q$role\E$/,@{$roles})) {
760: $refused = 0;
761: }
762: }
763: }
764: if ($refused) {
765: &logthis("<font color=\"blue\">WARNING: ".
766: "Attempt to modify environment ".$key." to ".$newenv->{$key}
767: .'</font>');
768: delete($newenv->{$key});
769: } else {
770: $env{$key}=$newenv->{$key};
771: }
772: }
773: my $lonids = $perlvar{'lonIDsDir'};
774: if ($env{'user.environment'} =~ m{^\Q$lonids/\E$match_username\_\d+\_$match_domain\_[\w\-.]+\.id$}) {
775: my $opened = open(my $env_file,'+<',$env{'user.environment'});
776: if ($opened
777: && &timed_flock($env_file,LOCK_EX)
778: &&
779: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
780: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
781: while (my ($key,$value) = each(%{$newenv})) {
782: $disk_env{$key} = $value;
783: }
784: untie(%disk_env);
785: }
786: }
787: }
788: return 'ok';
789: }
790: # ----------------------------------------------------- Delete from Environment
791:
792: sub delenv {
793: my ($delthis,$regexp,$roles) = @_;
794: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
795: my $refused = 1;
796: if (ref($roles) eq 'ARRAY') {
797: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
798: if (grep(/^\Q$role\E$/,@{$roles})) {
799: $refused = 0;
800: }
801: }
802: if ($refused) {
803: &logthis("<font color=\"blue\">WARNING: ".
804: "Attempt to delete from environment ".$delthis);
805: return 'error';
806: }
807: }
808: my $opened = open(my $env_file,'+<',$env{'user.environment'});
809: if ($opened
810: && &timed_flock($env_file,LOCK_EX)
811: &&
812: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
813: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
814: foreach my $key (keys(%disk_env)) {
815: if ($regexp) {
816: if ($key=~/^$delthis/) {
817: delete($env{$key});
818: delete($disk_env{$key});
819: }
820: } else {
821: if ($key=~/^\Q$delthis\E/) {
822: delete($env{$key});
823: delete($disk_env{$key});
824: }
825: }
826: }
827: untie(%disk_env);
828: }
829: return 'ok';
830: }
831:
832: sub get_env_multiple {
833: my ($name) = @_;
834: my @values;
835: if (defined($env{$name})) {
836: # exists is it an array
837: if (ref($env{$name})) {
838: @values=@{ $env{$name} };
839: } else {
840: $values[0]=$env{$name};
841: }
842: }
843: return(@values);
844: }
845:
846: # ------------------------------------------------------------------- Locking
847:
848: sub set_lock {
849: my ($text)=@_;
850: $locknum++;
851: my $id=$$.'-'.$locknum;
852: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
853: 'session.lock.'.$id => $text});
854: return $id;
855: }
856:
857: sub get_locks {
858: my $num=0;
859: my %texts=();
860: foreach my $lock (split(/\,/,$env{'session.locks'})) {
861: if ($lock=~/\w/) {
862: $num++;
863: $texts{$lock}=$env{'session.lock.'.$lock};
864: }
865: }
866: return ($num,%texts);
867: }
868:
869: sub remove_lock {
870: my ($id)=@_;
871: my $newlocks='';
872: foreach my $lock (split(/\,/,$env{'session.locks'})) {
873: if (($lock=~/\w/) && ($lock ne $id)) {
874: $newlocks.=','.$lock;
875: }
876: }
877: &appenv({'session.locks' => $newlocks});
878: &delenv('session.lock.'.$id);
879: }
880:
881: sub remove_all_locks {
882: my $activelocks=$env{'session.locks'};
883: foreach my $lock (split(/\,/,$env{'session.locks'})) {
884: if ($lock=~/\w/) {
885: &remove_lock($lock);
886: }
887: }
888: }
889:
890:
891: # ------------------------------------------ Find out current server userload
892: sub userload {
893: my $numusers=0;
894: {
895: opendir(LONIDS,$perlvar{'lonIDsDir'});
896: my $filename;
897: my $curtime=time;
898: while ($filename=readdir(LONIDS)) {
899: next if ($filename eq '.' || $filename eq '..');
900: next if ($filename =~ /publicuser_\d+\.id/);
901: next if ($filename =~ /^[a-f0-9]+_linked\.id$/);
902: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
903: if ($curtime-$mtime < 1800) { $numusers++; }
904: }
905: closedir(LONIDS);
906: }
907: my $userloadpercent=0;
908: my $maxuserload=$perlvar{'lonUserLoadLim'};
909: if ($maxuserload) {
910: $userloadpercent=100*$numusers/$maxuserload;
911: }
912: $userloadpercent=sprintf("%.2f",$userloadpercent);
913: return $userloadpercent;
914: }
915:
916: # ------------------------------ Find server with least workload from spare.tab
917:
918: sub spareserver {
919: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
920: my $spare_server;
921: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
922: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
923: : $userloadpercent;
924: my ($uint_dom,$remotesessions);
925: if (($udom ne '') && (&domain($udom) ne '')) {
926: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
927: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
928: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
929: $remotesessions = $udomdefaults{'remotesessions'};
930: }
931: my $spareshash = &this_host_spares($udom);
932: if (ref($spareshash) eq 'HASH') {
933: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
934: foreach my $try_server (@{ $spareshash->{'primary'} }) {
935: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
936: $try_server));
937: ($spare_server, $lowest_load) =
938: &compare_server_load($try_server, $spare_server, $lowest_load);
939: }
940: }
941:
942: my $found_server = ($spare_server ne '' && $lowest_load < 100);
943:
944: if (!$found_server) {
945: if (ref($spareshash->{'default'}) eq 'ARRAY') {
946: foreach my $try_server (@{ $spareshash->{'default'} }) {
947: next unless (&spare_can_host($udom,$uint_dom,
948: $remotesessions,$try_server));
949: ($spare_server, $lowest_load) =
950: &compare_server_load($try_server, $spare_server, $lowest_load);
951: }
952: }
953: }
954: }
955:
956: if (!$want_server_name) {
957: if (defined($spare_server)) {
958: my $hostname = &hostname($spare_server);
959: if (defined($hostname)) {
960: my $protocol = 'http';
961: if ($protocol{$spare_server} eq 'https') {
962: $protocol = $protocol{$spare_server};
963: }
964: $spare_server = $protocol.'://'.$hostname;
965: }
966: }
967: }
968: return $spare_server;
969: }
970:
971: sub compare_server_load {
972: my ($try_server, $spare_server, $lowest_load, $required) = @_;
973:
974: if ($required) {
975: my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
976: my $remoterev = &get_server_loncaparev(undef,$try_server);
977: my ($major,$minor) = ($remoterev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
978: if (($major eq '' && $minor eq '') ||
979: (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
980: return ($spare_server,$lowest_load);
981: }
982: }
983:
984: my $loadans = &reply('load', $try_server);
985: my $userloadans = &reply('userload',$try_server);
986:
987: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
988: return ($spare_server, $lowest_load); #didn't get a number from the server
989: }
990:
991: my $load;
992: if ($loadans =~ /\d/) {
993: if ($userloadans =~ /\d/) {
994: #both are numbers, pick the bigger one
995: $load = ($loadans > $userloadans) ? $loadans
996: : $userloadans;
997: } else {
998: $load = $loadans;
999: }
1000: } else {
1001: $load = $userloadans;
1002: }
1003:
1004: if (($load =~ /\d/) && ($load < $lowest_load)) {
1005: $spare_server = $try_server;
1006: $lowest_load = $load;
1007: }
1008: return ($spare_server,$lowest_load);
1009: }
1010:
1011: # --------------------------- ask offload servers if user already has a session
1012: sub find_existing_session {
1013: my ($udom,$uname) = @_;
1014: my $spareshash = &this_host_spares($udom);
1015: if (ref($spareshash) eq 'HASH') {
1016: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
1017: foreach my $try_server (@{ $spareshash->{'primary'} }) {
1018: return $try_server if (&has_user_session($try_server, $udom, $uname));
1019: }
1020: }
1021: if (ref($spareshash->{'default'}) eq 'ARRAY') {
1022: foreach my $try_server (@{ $spareshash->{'default'} }) {
1023: return $try_server if (&has_user_session($try_server, $udom, $uname));
1024: }
1025: }
1026: }
1027: return;
1028: }
1029:
1030: # check if user's browser sent load balancer cookie and server still has session
1031: # and is not overloaded.
1032: sub check_for_balancer_cookie {
1033: my ($r,$update_mtime) = @_;
1034: my ($otherserver,$cookie);
1035: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1036: if (exists($cookies{'balanceID'})) {
1037: my $balid = $cookies{'balanceID'};
1038: $cookie=&LONCAPA::clean_handle($balid->value);
1039: my $balancedir=$r->dir_config('lonBalanceDir');
1040: if ((-d $balancedir) && (-e "$balancedir/$cookie.id")) {
1041: if ($cookie =~ /^($match_domain)_($match_username)_[a-f0-9]+$/) {
1042: my ($possudom,$possuname) = ($1,$2);
1043: my $has_session = 0;
1044: if ((&domain($possudom) ne '') &&
1045: (&homeserver($possuname,$possudom) ne 'no_host')) {
1046: my $try_server;
1047: my $opened = open(my $idf,'+<',"$balancedir/$cookie.id");
1048: if ($opened) {
1049: flock($idf,LOCK_SH);
1050: while (my $line = <$idf>) {
1051: chomp($line);
1052: if (&hostname($line) ne '') {
1053: $try_server = $line;
1054: last;
1055: }
1056: }
1057: close($idf);
1058: if (($try_server) &&
1059: (&has_user_session($try_server,$possudom,$possuname))) {
1060: my $lowest_load = 30000;
1061: ($otherserver,$lowest_load) =
1062: &compare_server_load($try_server,undef,$lowest_load);
1063: if ($otherserver ne '' && $lowest_load < 100) {
1064: $has_session = 1;
1065: } else {
1066: undef($otherserver);
1067: }
1068: }
1069: }
1070: }
1071: if ($has_session) {
1072: if ($update_mtime) {
1073: my $atime = my $mtime = time;
1074: utime($atime,$mtime,"$balancedir/$cookie.id");
1075: }
1076: } else {
1077: unlink("$balancedir/$cookie.id");
1078: }
1079: }
1080: }
1081: }
1082: return ($otherserver,$cookie);
1083: }
1084:
1085: sub delbalcookie {
1086: my ($cookie,$balancer) =@_;
1087: if ($cookie =~ /^($match_domain)\_($match_username)\_[a-f0-9]{32}$/) {
1088: my ($udom,$uname) = ($1,$2);
1089: my $uprimary_id = &domain($udom,'primary');
1090: my $uintdom = &internet_dom($uprimary_id);
1091: my $intdom = &internet_dom($balancer);
1092: my $serverhomedom = &host_domain($balancer);
1093: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1094: return &reply("delbalcookie:$cookie",$balancer);
1095: }
1096: }
1097: }
1098:
1099: # -------------------------------- ask if server already has a session for user
1100: sub has_user_session {
1101: my ($lonid,$udom,$uname) = @_;
1102: my $result = &reply(join(':','userhassession',
1103: map {&escape($_)} ($udom,$uname)),$lonid);
1104: return 1 if ($result eq 'ok');
1105:
1106: return 0;
1107: }
1108:
1109: # --------- determine least loaded server in a user's domain which allows login
1110:
1111: sub choose_server {
1112: my ($udom,$checkloginvia,$required,$skiploadbal) = @_;
1113: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1114: my %servers = &get_servers($udom);
1115: my $lowest_load = 30000;
1116: my ($login_host,$hostname,$portal_path,$isredirect,$balancers);
1117: if ($skiploadbal) {
1118: ($balancers,my $cached)=&is_cached_new('loadbalancing',$udom);
1119: unless (defined($cached)) {
1120: my $cachetime = 60*60*24;
1121: my %domconfig =
1122: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1123: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1124: $balancers = &do_cache_new('loadbalancing',$udom,$domconfig{'loadbalancing'},
1125: $cachetime);
1126: }
1127: }
1128: }
1129: foreach my $lonhost (keys(%servers)) {
1130: my $loginvia;
1131: if ($skiploadbal) {
1132: if (ref($balancers) eq 'HASH') {
1133: next if (exists($balancers->{$lonhost}));
1134: }
1135: }
1136: if ($checkloginvia) {
1137: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1138: if ($loginvia) {
1139: my ($server,$path) = split(/:/,$loginvia);
1140: ($login_host, $lowest_load) =
1141: &compare_server_load($server, $login_host, $lowest_load, $required);
1142: if ($login_host eq $server) {
1143: $portal_path = $path;
1144: $isredirect = 1;
1145: }
1146: } else {
1147: ($login_host, $lowest_load) =
1148: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1149: if ($login_host eq $lonhost) {
1150: $portal_path = '';
1151: $isredirect = '';
1152: }
1153: }
1154: } else {
1155: ($login_host, $lowest_load) =
1156: &compare_server_load($lonhost, $login_host, $lowest_load, $required);
1157: }
1158: }
1159: if ($login_host ne '') {
1160: $hostname = &hostname($login_host);
1161: }
1162: return ($login_host,$hostname,$portal_path,$isredirect,$lowest_load);
1163: }
1164:
1165: sub get_course_sessions {
1166: my ($cnum,$cdom,$lastactivity) = @_;
1167: my %servers = &internet_dom_servers($cdom);
1168: my %returnhash;
1169: foreach my $server (sort(keys(%servers))) {
1170: my $rep = &reply("coursesessions:$cdom:$cnum:$lastactivity",$server);
1171: my @pairs=split(/\&/,$rep);
1172: unless (($rep eq 'unknown_cmd') || ($rep =~ /^error/)) {
1173: foreach my $item (@pairs) {
1174: my ($key,$value)=split(/=/,$item,2);
1175: $key = &unescape($key);
1176: next if ($key =~ /^error: 2 /);
1177: if (exists($returnhash{$key})) {
1178: next if ($value < $returnhash{$key});
1179: }
1180: $returnhash{$key}=$value;
1181: }
1182: }
1183: }
1184: return %returnhash;
1185: }
1186:
1187: # --------------------------------------------- Try to change a user's password
1188:
1189: sub changepass {
1190: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1191: $currentpass = &escape($currentpass);
1192: $newpass = &escape($newpass);
1193: my $lonhost = $perlvar{'lonHostID'};
1194: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1195: $server);
1196: if (! $answer) {
1197: &logthis("No reply on password change request to $server ".
1198: "by $uname in domain $udom.");
1199: } elsif ($answer =~ "^ok") {
1200: &logthis("$uname in $udom successfully changed their password ".
1201: "on $server.");
1202: } elsif ($answer =~ "^pwchange_failure") {
1203: &logthis("$uname in $udom was unable to change their password ".
1204: "on $server. The action was blocked by either lcpasswd ".
1205: "or pwchange");
1206: } elsif ($answer =~ "^non_authorized") {
1207: &logthis("$uname in $udom did not get their password correct when ".
1208: "attempting to change it on $server.");
1209: } elsif ($answer =~ "^auth_mode_error") {
1210: &logthis("$uname in $udom attempted to change their password despite ".
1211: "not being locally or internally authenticated on $server.");
1212: } elsif ($answer =~ "^unknown_user") {
1213: &logthis("$uname in $udom attempted to change their password ".
1214: "on $server but were unable to because $server is not ".
1215: "their home server.");
1216: } elsif ($answer =~ "^refused") {
1217: &logthis("$server refused to change $uname in $udom password because ".
1218: "it was sent an unencrypted request to change the password.");
1219: } elsif ($answer =~ "invalid_client") {
1220: &logthis("$server refused to change $uname in $udom password because ".
1221: "it was a reset by e-mail originating from an invalid server.");
1222: } elsif ($answer =~ "^prioruse") {
1223: &logthis("$server refused to change $uname in $udom password because ".
1224: "the password had been used before");
1225: }
1226: return $answer;
1227: }
1228:
1229: # ----------------------- Try to determine user's current authentication scheme
1230:
1231: sub queryauthenticate {
1232: my ($uname,$udom)=@_;
1233: my $uhome=&homeserver($uname,$udom);
1234: if (!$uhome) {
1235: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1236: return 'no_host';
1237: }
1238: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1239: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1240: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1241: }
1242: return $answer;
1243: }
1244:
1245: # --------- Try to authenticate user from domain's lib servers (first this one)
1246:
1247: sub authenticate {
1248: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1249: $upass=&escape($upass);
1250: $uname= &LONCAPA::clean_username($uname);
1251: my $uhome=&homeserver($uname,$udom,1);
1252: my $newhome;
1253: if ((!$uhome) || ($uhome eq 'no_host')) {
1254: # Maybe the machine was offline and only re-appeared again recently?
1255: &reconlonc();
1256: # One more
1257: $uhome=&homeserver($uname,$udom,1);
1258: if (($uhome eq 'no_host') && $checkdefauth) {
1259: if (defined(&domain($udom,'primary'))) {
1260: $newhome=&domain($udom,'primary');
1261: }
1262: if ($newhome ne '') {
1263: $uhome = $newhome;
1264: }
1265: }
1266: if ((!$uhome) || ($uhome eq 'no_host')) {
1267: &logthis("User $uname at $udom is unknown in authenticate");
1268: return 'no_host';
1269: }
1270: }
1271: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1272: if ($answer eq 'authorized') {
1273: if ($newhome) {
1274: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1275: return 'no_account_on_host';
1276: } else {
1277: &logthis("User $uname at $udom authorized by $uhome");
1278: return $uhome;
1279: }
1280: }
1281: if ($answer eq 'non_authorized') {
1282: &logthis("User $uname at $udom rejected by $uhome");
1283: return 'no_host';
1284: }
1285: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1286: return 'no_host';
1287: }
1288:
1289: sub can_host_session {
1290: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1291: my $canhost = 1;
1292: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1293: if (ref($remotesessions) eq 'HASH') {
1294: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1295: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1296: $canhost = 0;
1297: } else {
1298: $canhost = 1;
1299: }
1300: }
1301: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1302: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1303: $canhost = 1;
1304: } else {
1305: $canhost = 0;
1306: }
1307: }
1308: if ($canhost) {
1309: if ($remotesessions->{'version'} ne '') {
1310: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1311: if ($reqmajor ne '' && $reqminor ne '') {
1312: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1313: my $major = $1;
1314: my $minor = $2;
1315: if (($major < $reqmajor ) ||
1316: (($major == $reqmajor) && ($minor < $reqminor))) {
1317: $canhost = 0;
1318: }
1319: } else {
1320: $canhost = 0;
1321: }
1322: }
1323: }
1324: }
1325: }
1326: if ($canhost) {
1327: if (ref($hostedsessions) eq 'HASH') {
1328: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1329: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1330: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1331: if (($uint_dom ne '') &&
1332: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1333: $canhost = 0;
1334: } else {
1335: $canhost = 1;
1336: }
1337: }
1338: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1339: if (($uint_dom ne '') &&
1340: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1341: $canhost = 1;
1342: } else {
1343: $canhost = 0;
1344: }
1345: }
1346: }
1347: }
1348: return $canhost;
1349: }
1350:
1351: sub spare_can_host {
1352: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1353: my $canhost=1;
1354: my $try_server_hostname = &hostname($try_server);
1355: my $serverhomeID = &get_server_homeID($try_server_hostname);
1356: my $serverhomedom = &host_domain($serverhomeID);
1357: my %defdomdefaults = &get_domain_defaults($serverhomedom);
1358: if (ref($defdomdefaults{'offloadnow'}) eq 'HASH') {
1359: if ($defdomdefaults{'offloadnow'}{$try_server}) {
1360: $canhost = 0;
1361: }
1362: }
1363: if (($canhost) && ($uint_dom)) {
1364: my @intdoms;
1365: my $internet_names = &get_internet_names($try_server);
1366: if (ref($internet_names) eq 'ARRAY') {
1367: @intdoms = @{$internet_names};
1368: }
1369: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1370: my $remoterev = &get_server_loncaparev(undef,$try_server);
1371: $canhost = &can_host_session($udom,$try_server,$remoterev,
1372: $remotesessions,
1373: $defdomdefaults{'hostedsessions'});
1374: }
1375: }
1376: return $canhost;
1377: }
1378:
1379: sub this_host_spares {
1380: my ($dom) = @_;
1381: my ($dom_in_use,$lonhost_in_use,$result);
1382: my @hosts = ¤t_machine_ids();
1383: foreach my $lonhost (@hosts) {
1384: if (&host_domain($lonhost) eq $dom) {
1385: $dom_in_use = $dom;
1386: $lonhost_in_use = $lonhost;
1387: last;
1388: }
1389: }
1390: if ($dom_in_use ne '') {
1391: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1392: }
1393: if (ref($result) ne 'HASH') {
1394: $lonhost_in_use = $perlvar{'lonHostID'};
1395: $dom_in_use = &host_domain($lonhost_in_use);
1396: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1397: if (ref($result) ne 'HASH') {
1398: $result = \%spareid;
1399: }
1400: }
1401: return $result;
1402: }
1403:
1404: sub spares_for_offload {
1405: my ($dom_in_use,$lonhost_in_use) = @_;
1406: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1407: if (defined($cached)) {
1408: return $result;
1409: } else {
1410: my $cachetime = 60*60*24;
1411: my %domconfig =
1412: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1413: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1414: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1415: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1416: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1417: }
1418: }
1419: }
1420: }
1421: return;
1422: }
1423:
1424: sub get_lonbalancer_config {
1425: my ($servers) = @_;
1426: my ($currbalancer,$currtargets);
1427: if (ref($servers) eq 'HASH') {
1428: foreach my $server (keys(%{$servers})) {
1429: my %what = (
1430: spareid => 1,
1431: perlvar => 1,
1432: );
1433: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1434: if ($result eq 'ok') {
1435: if (ref($returnhash) eq 'HASH') {
1436: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1437: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1438: $currbalancer = $server;
1439: $currtargets = {};
1440: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1441: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1442: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1443: }
1444: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1445: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1446: }
1447: }
1448: last;
1449: }
1450: }
1451: }
1452: }
1453: }
1454: }
1455: return ($currbalancer,$currtargets);
1456: }
1457:
1458: sub check_loadbalancing {
1459: my ($uname,$udom,$caller) = @_;
1460: my ($is_balancer,$currtargets,$currrules,$dom_in_use,$homeintdom,
1461: $rule_in_effect,$offloadto,$otherserver,$setcookie);
1462: my $lonhost = $perlvar{'lonHostID'};
1463: my @hosts = ¤t_machine_ids();
1464: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1465: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1466: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1467: my $serverhomedom = &host_domain($lonhost);
1468: my $domneedscache;
1469: my $cachetime = 60*60*24;
1470:
1471: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1472: $dom_in_use = $udom;
1473: $homeintdom = 1;
1474: } else {
1475: $dom_in_use = $serverhomedom;
1476: }
1477: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1478: unless (defined($cached)) {
1479: my %domconfig =
1480: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1481: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1482: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1483: } else {
1484: $domneedscache = $dom_in_use;
1485: }
1486: }
1487: if (ref($result) eq 'HASH') {
1488: ($is_balancer,$currtargets,$currrules,$setcookie) =
1489: &check_balancer_result($result,@hosts);
1490: if ($is_balancer) {
1491: if (ref($currrules) eq 'HASH') {
1492: if ($homeintdom) {
1493: if ($uname ne '') {
1494: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1495: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1496: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1497: $rule_in_effect = $currrules->{'_LC_author'};
1498: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1499: $rule_in_effect = $currrules->{'_LC_adv'}
1500: }
1501: }
1502: if ($rule_in_effect eq '') {
1503: my %userenv = &userenvironment($udom,$uname,'inststatus');
1504: if ($userenv{'inststatus'} ne '') {
1505: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1506: my ($othertitle,$usertypes,$types) =
1507: &Apache::loncommon::sorted_inst_types($udom);
1508: if (ref($types) eq 'ARRAY') {
1509: foreach my $type (@{$types}) {
1510: if (grep(/^\Q$type\E$/,@statuses)) {
1511: if (exists($currrules->{$type})) {
1512: $rule_in_effect = $currrules->{$type};
1513: }
1514: }
1515: }
1516: }
1517: } else {
1518: if (exists($currrules->{'default'})) {
1519: $rule_in_effect = $currrules->{'default'};
1520: }
1521: }
1522: }
1523: } else {
1524: if (exists($currrules->{'default'})) {
1525: $rule_in_effect = $currrules->{'default'};
1526: }
1527: }
1528: } else {
1529: if ($currrules->{'_LC_external'} ne '') {
1530: $rule_in_effect = $currrules->{'_LC_external'};
1531: }
1532: }
1533: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1534: $uname,$udom);
1535: }
1536: }
1537: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1538: ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1539: unless (defined($cached)) {
1540: my %domconfig =
1541: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1542: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1543: $result = &do_cache_new('loadbalancing',$serverhomedom,$domconfig{'loadbalancing'},$cachetime);
1544: } else {
1545: $domneedscache = $serverhomedom;
1546: }
1547: }
1548: if (ref($result) eq 'HASH') {
1549: ($is_balancer,$currtargets,$currrules,$setcookie) =
1550: &check_balancer_result($result,@hosts);
1551: if ($is_balancer) {
1552: if (ref($currrules) eq 'HASH') {
1553: if ($currrules->{'_LC_internetdom'} ne '') {
1554: $rule_in_effect = $currrules->{'_LC_internetdom'};
1555: }
1556: }
1557: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1558: $uname,$udom);
1559: }
1560: } else {
1561: if ($perlvar{'lonBalancer'} eq 'yes') {
1562: $is_balancer = 1;
1563: $offloadto = &this_host_spares($dom_in_use);
1564: }
1565: unless (defined($cached)) {
1566: $domneedscache = $serverhomedom;
1567: }
1568: }
1569: } else {
1570: if ($perlvar{'lonBalancer'} eq 'yes') {
1571: $is_balancer = 1;
1572: $offloadto = &this_host_spares($dom_in_use);
1573: }
1574: unless (defined($cached)) {
1575: $domneedscache = $serverhomedom;
1576: }
1577: }
1578: if ($domneedscache) {
1579: &do_cache_new('loadbalancing',$domneedscache,$is_balancer,$cachetime);
1580: }
1581: if ($is_balancer) {
1582: my $lowest_load = 30000;
1583: if (ref($offloadto) eq 'HASH') {
1584: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1585: foreach my $try_server (@{$offloadto->{'primary'}}) {
1586: ($otherserver,$lowest_load) =
1587: &compare_server_load($try_server,$otherserver,$lowest_load);
1588: }
1589: }
1590: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1591:
1592: if (!$found_server) {
1593: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1594: foreach my $try_server (@{$offloadto->{'default'}}) {
1595: ($otherserver,$lowest_load) =
1596: &compare_server_load($try_server,$otherserver,$lowest_load);
1597: }
1598: }
1599: }
1600: } elsif (ref($offloadto) eq 'ARRAY') {
1601: if (@{$offloadto} == 1) {
1602: $otherserver = $offloadto->[0];
1603: } elsif (@{$offloadto} > 1) {
1604: foreach my $try_server (@{$offloadto}) {
1605: ($otherserver,$lowest_load) =
1606: &compare_server_load($try_server,$otherserver,$lowest_load);
1607: }
1608: }
1609: }
1610: unless ($caller eq 'login') {
1611: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1612: $is_balancer = 0;
1613: if ($uname ne '' && $udom ne '') {
1614: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1615: &appenv({'user.loadbalexempt' => $lonhost,
1616: 'user.loadbalcheck.time' => time});
1617: }
1618: }
1619: }
1620: }
1621: unless ($homeintdom) {
1622: undef($setcookie);
1623: }
1624: }
1625: return ($is_balancer,$otherserver,$setcookie);
1626: }
1627:
1628: sub check_balancer_result {
1629: my ($result,@hosts) = @_;
1630: my ($is_balancer,$currtargets,$currrules,$setcookie);
1631: if (ref($result) eq 'HASH') {
1632: if ($result->{'lonhost'} ne '') {
1633: my $currbalancer = $result->{'lonhost'};
1634: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1635: $is_balancer = 1;
1636: $currtargets = $result->{'targets'};
1637: $currrules = $result->{'rules'};
1638: }
1639: } else {
1640: foreach my $key (keys(%{$result})) {
1641: if (($key ne '') && (grep(/^\Q$key\E$/,@hosts)) &&
1642: (ref($result->{$key}) eq 'HASH')) {
1643: $is_balancer = 1;
1644: $currrules = $result->{$key}{'rules'};
1645: $currtargets = $result->{$key}{'targets'};
1646: $setcookie = $result->{$key}{'cookie'};
1647: last;
1648: }
1649: }
1650: }
1651: }
1652: return ($is_balancer,$currtargets,$currrules,$setcookie);
1653: }
1654:
1655: sub get_loadbalancer_targets {
1656: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1657: my $offloadto;
1658: if ($rule_in_effect eq 'none') {
1659: return [$perlvar{'lonHostID'}];
1660: } elsif ($rule_in_effect eq '') {
1661: $offloadto = $currtargets;
1662: } else {
1663: if ($rule_in_effect eq 'homeserver') {
1664: my $homeserver = &homeserver($uname,$udom);
1665: if ($homeserver ne 'no_host') {
1666: $offloadto = [$homeserver];
1667: }
1668: } elsif ($rule_in_effect eq 'externalbalancer') {
1669: my %domconfig =
1670: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1671: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1672: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1673: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1674: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1675: }
1676: }
1677: } else {
1678: my %servers = &internet_dom_servers($udom);
1679: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1680: if (&hostname($remotebalancer) ne '') {
1681: $offloadto = [$remotebalancer];
1682: }
1683: }
1684: } elsif (&hostname($rule_in_effect) ne '') {
1685: $offloadto = [$rule_in_effect];
1686: }
1687: }
1688: return $offloadto;
1689: }
1690:
1691: sub internet_dom_servers {
1692: my ($dom) = @_;
1693: my (%uniqservers,%servers);
1694: my $primaryserver = &hostname(&domain($dom,'primary'));
1695: my @machinedoms = &machine_domains($primaryserver);
1696: foreach my $mdom (@machinedoms) {
1697: my %currservers = %servers;
1698: my %server = &get_servers($mdom);
1699: %servers = (%currservers,%server);
1700: }
1701: my %by_hostname;
1702: foreach my $id (keys(%servers)) {
1703: push(@{$by_hostname{$servers{$id}}},$id);
1704: }
1705: foreach my $hostname (sort(keys(%by_hostname))) {
1706: if (@{$by_hostname{$hostname}} > 1) {
1707: my $match = 0;
1708: foreach my $id (@{$by_hostname{$hostname}}) {
1709: if (&host_domain($id) eq $dom) {
1710: $uniqservers{$id} = $hostname;
1711: $match = 1;
1712: }
1713: }
1714: unless ($match) {
1715: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1716: }
1717: } else {
1718: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1719: }
1720: }
1721: return %uniqservers;
1722: }
1723:
1724: # ---------------------- Find the homebase for a user from domain's lib servers
1725:
1726: my %homecache;
1727: sub homeserver {
1728: my ($uname,$udom,$ignoreBadCache)=@_;
1729: my $index="$uname:$udom";
1730:
1731: if (exists($homecache{$index})) { return $homecache{$index}; }
1732:
1733: my %servers = &get_servers($udom,'library');
1734: foreach my $tryserver (keys(%servers)) {
1735: next if ($ignoreBadCache ne 'true' &&
1736: exists($badServerCache{$tryserver}));
1737:
1738: my $answer=reply("home:$udom:$uname",$tryserver);
1739: if ($answer eq 'found') {
1740: delete($badServerCache{$tryserver});
1741: return $homecache{$index}=$tryserver;
1742: } elsif ($answer eq 'no_host') {
1743: $badServerCache{$tryserver}=1;
1744: }
1745: }
1746: return 'no_host';
1747: }
1748:
1749: # ------------------------------------- Find the usernames behind a list of IDs
1750:
1751: sub idget {
1752: my ($udom,@ids)=@_;
1753: my %returnhash=();
1754:
1755: my %servers = &get_servers($udom,'library');
1756: foreach my $tryserver (keys(%servers)) {
1757: my $idlist=join('&', map { &escape($_); } @ids);
1758: $idlist=~tr/A-Z/a-z/;
1759: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1760: my @answer=();
1761: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1762: @answer=split(/\&/,$reply);
1763: } ;
1764: my $i;
1765: for ($i=0;$i<=$#ids;$i++) {
1766: if ($answer[$i]) {
1767: $returnhash{$ids[$i]}=&unescape($answer[$i]);
1768: }
1769: }
1770: }
1771: return %returnhash;
1772: }
1773:
1774: # ------------------------------------- Find the IDs behind a list of usernames
1775:
1776: sub idrget {
1777: my ($udom,@unames)=@_;
1778: my %returnhash=();
1779: foreach my $uname (@unames) {
1780: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1781: }
1782: return %returnhash;
1783: }
1784:
1785: # ------------------------------- Store away a list of names and associated IDs
1786:
1787: sub idput {
1788: my ($udom,%ids)=@_;
1789: my %servers=();
1790: foreach my $uname (keys(%ids)) {
1791: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1792: my $uhom=&homeserver($uname,$udom);
1793: if ($uhom ne 'no_host') {
1794: my $id=&escape($ids{$uname});
1795: $id=~tr/A-Z/a-z/;
1796: my $esc_unam=&escape($uname);
1797: if ($servers{$uhom}) {
1798: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1799: } else {
1800: $servers{$uhom}=$id.'='.$esc_unam;
1801: }
1802: }
1803: }
1804: foreach my $server (keys(%servers)) {
1805: &critical('idput:'.$udom.':'.$servers{$server},$server);
1806: }
1807: }
1808:
1809: # ---------------------------------------- Delete unwanted IDs from ids.db file
1810:
1811: sub iddel {
1812: my ($udom,$idshashref,$uhome)=@_;
1813: my %result=();
1814: unless (ref($idshashref) eq 'HASH') {
1815: return %result;
1816: }
1817: my %servers=();
1818: while (my ($id,$uname) = each(%{$idshashref})) {
1819: my $uhom;
1820: if ($uhome) {
1821: $uhom = $uhome;
1822: } else {
1823: $uhom=&homeserver($uname,$udom);
1824: }
1825: if ($uhom ne 'no_host') {
1826: if ($servers{$uhom}) {
1827: $servers{$uhom}.='&'.&escape($id);
1828: } else {
1829: $servers{$uhom}=&escape($id);
1830: }
1831: }
1832: }
1833: foreach my $server (keys(%servers)) {
1834: $result{$server} = &critical('iddel:'.$udom.':'.$servers{$server},$uhome);
1835: }
1836: return %result;
1837: }
1838:
1839: # ------------------------------dump from db file owned by domainconfig user
1840: sub dump_dom {
1841: my ($namespace, $udom, $regexp) = @_;
1842:
1843: $udom ||= $env{'user.domain'};
1844:
1845: return () unless $udom;
1846:
1847: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1848: }
1849:
1850: # ------------------------------------------ get items from domain db files
1851:
1852: sub get_dom {
1853: my ($namespace,$storearr,$udom,$uhome)=@_;
1854: return if ($udom eq 'public');
1855: my $items='';
1856: foreach my $item (@$storearr) {
1857: $items.=&escape($item).'&';
1858: }
1859: $items=~s/\&$//;
1860: if (!$udom) {
1861: $udom=$env{'user.domain'};
1862: return if ($udom eq 'public');
1863: if (defined(&domain($udom,'primary'))) {
1864: $uhome=&domain($udom,'primary');
1865: } else {
1866: undef($uhome);
1867: }
1868: } else {
1869: if (!$uhome) {
1870: if (defined(&domain($udom,'primary'))) {
1871: $uhome=&domain($udom,'primary');
1872: }
1873: }
1874: }
1875: if ($udom && $uhome && ($uhome ne 'no_host')) {
1876: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1877: my %returnhash;
1878: if ($rep eq '' || $rep =~ /^error: 2 /) {
1879: return %returnhash;
1880: }
1881: my @pairs=split(/\&/,$rep);
1882: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1883: return @pairs;
1884: }
1885: my $i=0;
1886: foreach my $item (@$storearr) {
1887: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1888: $i++;
1889: }
1890: return %returnhash;
1891: } else {
1892: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1893: }
1894: }
1895:
1896: # -------------------------------------------- put items in domain db files
1897:
1898: sub put_dom {
1899: my ($namespace,$storehash,$udom,$uhome)=@_;
1900: if (!$udom) {
1901: $udom=$env{'user.domain'};
1902: if (defined(&domain($udom,'primary'))) {
1903: $uhome=&domain($udom,'primary');
1904: } else {
1905: undef($uhome);
1906: }
1907: } else {
1908: if (!$uhome) {
1909: if (defined(&domain($udom,'primary'))) {
1910: $uhome=&domain($udom,'primary');
1911: }
1912: }
1913: }
1914: if ($udom && $uhome && ($uhome ne 'no_host')) {
1915: my $items='';
1916: foreach my $item (keys(%$storehash)) {
1917: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1918: }
1919: $items=~s/\&$//;
1920: return &reply("putdom:$udom:$namespace:$items",$uhome);
1921: } else {
1922: &logthis("put_dom failed - no homeserver and/or domain");
1923: }
1924: }
1925:
1926: # --------------------- newput for items in db file owned by domainconfig user
1927: sub newput_dom {
1928: my ($namespace,$storehash,$udom) = @_;
1929: my $result;
1930: if (!$udom) {
1931: $udom=$env{'user.domain'};
1932: }
1933: if ($udom) {
1934: my $uname = &get_domainconfiguser($udom);
1935: $result = &newput($namespace,$storehash,$udom,$uname);
1936: }
1937: return $result;
1938: }
1939:
1940: # --------------------- delete for items in db file owned by domainconfig user
1941: sub del_dom {
1942: my ($namespace,$storearr,$udom)=@_;
1943: if (ref($storearr) eq 'ARRAY') {
1944: if (!$udom) {
1945: $udom=$env{'user.domain'};
1946: }
1947: if ($udom) {
1948: my $uname = &get_domainconfiguser($udom);
1949: return &del($namespace,$storearr,$udom,$uname);
1950: }
1951: }
1952: }
1953:
1954: # ----------------------------------construct domainconfig user for a domain
1955: sub get_domainconfiguser {
1956: my ($udom) = @_;
1957: return $udom.'-domainconfig';
1958: }
1959:
1960: sub retrieve_inst_usertypes {
1961: my ($udom) = @_;
1962: my (%returnhash,@order);
1963: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1964: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1965: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1966: return ($domdefs{'inststatustypes'},$domdefs{'inststatusorder'});
1967: } else {
1968: if (defined(&domain($udom,'primary'))) {
1969: my $uhome=&domain($udom,'primary');
1970: my $rep=&reply("inst_usertypes:$udom",$uhome);
1971: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1972: &logthis("retrieve_inst_usertypes failed - $rep returned from $uhome in domain: $udom");
1973: return (\%returnhash,\@order);
1974: }
1975: my ($hashitems,$orderitems) = split(/:/,$rep);
1976: my @pairs=split(/\&/,$hashitems);
1977: foreach my $item (@pairs) {
1978: my ($key,$value)=split(/=/,$item,2);
1979: $key = &unescape($key);
1980: next if ($key =~ /^error: 2 /);
1981: $returnhash{$key}=&thaw_unescape($value);
1982: }
1983: my @esc_order = split(/\&/,$orderitems);
1984: foreach my $item (@esc_order) {
1985: push(@order,&unescape($item));
1986: }
1987: } else {
1988: &logthis("retrieve_inst_usertypes failed - no primary domain server for $udom");
1989: }
1990: return (\%returnhash,\@order);
1991: }
1992: }
1993:
1994: sub is_domainimage {
1995: my ($url) = @_;
1996: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+[^/]-) {
1997: if (&domain($1) ne '') {
1998: return '1';
1999: }
2000: }
2001: return;
2002: }
2003:
2004: sub inst_directory_query {
2005: my ($srch) = @_;
2006: my $udom = $srch->{'srchdomain'};
2007: my %results;
2008: my $homeserver = &domain($udom,'primary');
2009: my $outcome;
2010: if ($homeserver ne '') {
2011: unless ($homeserver eq $perlvar{'lonHostID'}) {
2012: if ($srch->{'srchby'} eq 'email') {
2013: my $lcrev = &get_server_loncaparev($udom,$homeserver);
2014: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2015: if (($major eq '' && $minor eq '') || ($major < 2) ||
2016: (($major == 2) && ($minor < 11)) ||
2017: (($major == 2) && ($minor == 11) && ($subver < 3))) {
2018: return;
2019: }
2020: }
2021: }
2022: my $queryid=&reply("querysend:instdirsearch:".
2023: &escape($srch->{'srchby'}).':'.
2024: &escape($srch->{'srchterm'}).':'.
2025: &escape($srch->{'srchtype'}),$homeserver);
2026: my $host=&hostname($homeserver);
2027: if ($queryid !~/^\Q$host\E\_/) {
2028: &logthis('institutional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.' in domain '.$udom);
2029: return;
2030: }
2031: my $response = &get_query_reply($queryid);
2032: my $maxtries = 5;
2033: my $tries = 1;
2034: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2035: $response = &get_query_reply($queryid);
2036: $tries ++;
2037: }
2038:
2039: if (!&error($response) && $response ne 'refused') {
2040: if ($response eq 'unavailable') {
2041: $outcome = $response;
2042: } else {
2043: $outcome = 'ok';
2044: my @matches = split(/\n/,$response);
2045: foreach my $match (@matches) {
2046: my ($key,$value) = split(/=/,$match);
2047: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
2048: }
2049: }
2050: }
2051: }
2052: return ($outcome,%results);
2053: }
2054:
2055: sub usersearch {
2056: my ($srch) = @_;
2057: my $dom = $srch->{'srchdomain'};
2058: my %results;
2059: my %libserv = &all_library();
2060: my $query = 'usersearch';
2061: foreach my $tryserver (keys(%libserv)) {
2062: if (&host_domain($tryserver) eq $dom) {
2063: unless ($tryserver eq $perlvar{'lonHostID'}) {
2064: if ($srch->{'srchby'} eq 'email') {
2065: my $lcrev = &get_server_loncaparev($dom,$tryserver);
2066: my ($major,$minor,$subver) = ($lcrev =~ /^\'?(\d+)\.(\d+)\.(\d+)[\w.\-]+\'?$/);
2067: next if (($major eq '' && $minor eq '') || ($major < 2) ||
2068: (($major == 2) && ($minor < 11)) ||
2069: (($major == 2) && ($minor == 11) && ($subver < 3)));
2070: }
2071: }
2072: my $host=&hostname($tryserver);
2073: my $queryid=
2074: &reply("querysend:".&escape($query).':'.
2075: &escape($srch->{'srchby'}).':'.
2076: &escape($srch->{'srchtype'}).':'.
2077: &escape($srch->{'srchterm'}),$tryserver);
2078: if ($queryid !~/^\Q$host\E\_/) {
2079: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
2080: next;
2081: }
2082: my $reply = &get_query_reply($queryid);
2083: my $maxtries = 1;
2084: my $tries = 1;
2085: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
2086: $reply = &get_query_reply($queryid);
2087: $tries ++;
2088: }
2089: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
2090: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
2091: } else {
2092: my @matches;
2093: if ($reply =~ /\n/) {
2094: @matches = split(/\n/,$reply);
2095: } else {
2096: @matches = split(/\&/,$reply);
2097: }
2098: foreach my $match (@matches) {
2099: my ($uname,$udom,%userhash);
2100: foreach my $entry (split(/:/,$match)) {
2101: my ($key,$value) =
2102: map {&unescape($_);} split(/=/,$entry);
2103: $userhash{$key} = $value;
2104: if ($key eq 'username') {
2105: $uname = $value;
2106: } elsif ($key eq 'domain') {
2107: $udom = $value;
2108: }
2109: }
2110: $results{$uname.':'.$udom} = \%userhash;
2111: }
2112: }
2113: }
2114: }
2115: return %results;
2116: }
2117:
2118: sub get_instuser {
2119: my ($udom,$uname,$id) = @_;
2120: my $homeserver = &domain($udom,'primary');
2121: my ($outcome,%results);
2122: if ($homeserver ne '') {
2123: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
2124: &escape($id).':'.&escape($udom),$homeserver);
2125: my $host=&hostname($homeserver);
2126: if ($queryid !~/^\Q$host\E\_/) {
2127: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
2128: return;
2129: }
2130: my $response = &get_query_reply($queryid);
2131: my $maxtries = 5;
2132: my $tries = 1;
2133: while (($response=~/^timeout/) && ($tries < $maxtries)) {
2134: $response = &get_query_reply($queryid);
2135: $tries ++;
2136: }
2137: if (!&error($response) && $response ne 'refused') {
2138: if ($response eq 'unavailable') {
2139: $outcome = $response;
2140: } else {
2141: $outcome = 'ok';
2142: my @matches = split(/\n/,$response);
2143: foreach my $match (@matches) {
2144: my ($key,$value) = split(/=/,$match);
2145: $results{&unescape($key)} = &thaw_unescape($value);
2146: }
2147: }
2148: }
2149: }
2150: my %userinfo;
2151: if (ref($results{$uname}) eq 'HASH') {
2152: %userinfo = %{$results{$uname}};
2153: }
2154: return ($outcome,%userinfo);
2155: }
2156:
2157: sub get_multiple_instusers {
2158: my ($udom,$users,$caller) = @_;
2159: my ($outcome,$results);
2160: if (ref($users) eq 'HASH') {
2161: my $count = keys(%{$users});
2162: my $requested = &freeze_escape($users);
2163: my $homeserver = &domain($udom,'primary');
2164: if ($homeserver ne '') {
2165: my $queryid=&reply('querysend:getmultinstusers:::'.$caller.'='.$requested,$homeserver);
2166: my $host=&hostname($homeserver);
2167: if ($queryid !~/^\Q$host\E\_/) {
2168: &logthis('get_multiple_instusers invalid queryid: '.$queryid.
2169: ' for host: '.$homeserver.'in domain '.$udom);
2170: return ($outcome,$results);
2171: }
2172: my $response = &get_query_reply($queryid);
2173: my $maxtries = 5;
2174: if ($count > 100) {
2175: $maxtries = 1+int($count/20);
2176: }
2177: my $tries = 1;
2178: while (($response=~/^timeout/) && ($tries <= $maxtries)) {
2179: $response = &get_query_reply($queryid);
2180: $tries ++;
2181: }
2182: if ($response eq '') {
2183: $results = {};
2184: foreach my $key (keys(%{$users})) {
2185: my ($uname,$id);
2186: if ($caller eq 'id') {
2187: $id = $key;
2188: } else {
2189: $uname = $key;
2190: }
2191: my ($resp,%info) = &get_instuser($udom,$uname,$id);
2192: $outcome = $resp;
2193: if ($resp eq 'ok') {
2194: %{$results} = (%{$results}, %info);
2195: } else {
2196: last;
2197: }
2198: }
2199: } elsif(!&error($response) && ($response ne 'refused')) {
2200: if (($response eq 'unavailable') || ($response eq 'invalid') || ($response eq 'timeout')) {
2201: $outcome = $response;
2202: } else {
2203: ($outcome,my $userdata) = split(/=/,$response,2);
2204: if ($outcome eq 'ok') {
2205: $results = &thaw_unescape($userdata);
2206: }
2207: }
2208: }
2209: }
2210: }
2211: return ($outcome,$results);
2212: }
2213:
2214: sub inst_rulecheck {
2215: my ($udom,$uname,$id,$item,$rules) = @_;
2216: my %returnhash;
2217: if ($udom ne '') {
2218: if (ref($rules) eq 'ARRAY') {
2219: @{$rules} = map {&escape($_);} (@{$rules});
2220: my $rulestr = join(':',@{$rules});
2221: my $homeserver=&domain($udom,'primary');
2222: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2223: my $response;
2224: if ($item eq 'username') {
2225: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
2226: ':'.&escape($uname).':'.$rulestr,
2227: $homeserver));
2228: } elsif ($item eq 'id') {
2229: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
2230: ':'.&escape($id).':'.$rulestr,
2231: $homeserver));
2232: } elsif ($item eq 'selfcreate') {
2233: $response=&unescape(&reply('instselfcreatecheck:'.
2234: &escape($udom).':'.&escape($uname).
2235: ':'.$rulestr,$homeserver));
2236: }
2237: if ($response ne 'refused') {
2238: my @pairs=split(/\&/,$response);
2239: foreach my $item (@pairs) {
2240: my ($key,$value)=split(/=/,$item,2);
2241: $key = &unescape($key);
2242: next if ($key =~ /^error: 2 /);
2243: $returnhash{$key}=&thaw_unescape($value);
2244: }
2245: }
2246: }
2247: }
2248: }
2249: return %returnhash;
2250: }
2251:
2252: sub inst_userrules {
2253: my ($udom,$check) = @_;
2254: my (%ruleshash,@ruleorder);
2255: if ($udom ne '') {
2256: my $homeserver=&domain($udom,'primary');
2257: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
2258: my $response;
2259: if ($check eq 'id') {
2260: $response=&reply('instidrules:'.&escape($udom),
2261: $homeserver);
2262: } elsif ($check eq 'email') {
2263: $response=&reply('instemailrules:'.&escape($udom),
2264: $homeserver);
2265: } else {
2266: $response=&reply('instuserrules:'.&escape($udom),
2267: $homeserver);
2268: }
2269: if (($response ne 'refused') && ($response ne 'error') &&
2270: ($response ne 'unknown_cmd') &&
2271: ($response ne 'no_such_host')) {
2272: my ($hashitems,$orderitems) = split(/:/,$response);
2273: my @pairs=split(/\&/,$hashitems);
2274: foreach my $item (@pairs) {
2275: my ($key,$value)=split(/=/,$item,2);
2276: $key = &unescape($key);
2277: next if ($key =~ /^error: 2 /);
2278: $ruleshash{$key}=&thaw_unescape($value);
2279: }
2280: my @esc_order = split(/\&/,$orderitems);
2281: foreach my $item (@esc_order) {
2282: push(@ruleorder,&unescape($item));
2283: }
2284: }
2285: }
2286: }
2287: return (\%ruleshash,\@ruleorder);
2288: }
2289:
2290: # ------------- Get Authentication, Language and User Tools Defaults for Domain
2291:
2292: sub get_domain_defaults {
2293: my ($domain,$ignore_cache) = @_;
2294: return if (($domain eq '') || ($domain eq 'public'));
2295: my $cachetime = 60*60*24;
2296: unless ($ignore_cache) {
2297: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
2298: if (defined($cached)) {
2299: if (ref($result) eq 'HASH') {
2300: return %{$result};
2301: }
2302: }
2303: }
2304: my %domdefaults;
2305: my %domconfig =
2306: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
2307: 'requestcourses','inststatus',
2308: 'coursedefaults','usersessions',
2309: 'requestauthor','selfenrollment',
2310: 'coursecategories','autoenroll',
2311: 'helpsettings'],$domain);
2312: my @coursetypes = ('official','unofficial','community','textbook');
2313: if (ref($domconfig{'defaults'}) eq 'HASH') {
2314: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
2315: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
2316: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
2317: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
2318: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
2319: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
2320: $domdefaults{'intauth_cost'} = $domconfig{'defaults'}{'intauth_cost'};
2321: $domdefaults{'intauth_switch'} = $domconfig{'defaults'}{'intauth_switch'};
2322: $domdefaults{'intauth_check'} = $domconfig{'defaults'}{'intauth_check'};
2323: } else {
2324: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
2325: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
2326: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
2327: }
2328: if (ref($domconfig{'quotas'}) eq 'HASH') {
2329: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
2330: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
2331: } else {
2332: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
2333: }
2334: my @usertools = ('aboutme','blog','webdav','portfolio');
2335: foreach my $item (@usertools) {
2336: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
2337: $domdefaults{$item} = $domconfig{'quotas'}{$item};
2338: }
2339: }
2340: if (ref($domconfig{'quotas'}{'authorquota'}) eq 'HASH') {
2341: $domdefaults{'authorquota'} = $domconfig{'quotas'}{'authorquota'};
2342: }
2343: }
2344: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
2345: foreach my $item ('official','unofficial','community','textbook') {
2346: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
2347: }
2348: }
2349: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
2350: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
2351: }
2352: if (ref($domconfig{'inststatus'}) eq 'HASH') {
2353: foreach my $item ('inststatustypes','inststatusorder','inststatusguest') {
2354: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
2355: }
2356: }
2357: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
2358: $domdefaults{'usejsme'} = $domconfig{'coursedefaults'}{'usejsme'};
2359: $domdefaults{'uselcmath'} = $domconfig{'coursedefaults'}{'uselcmath'};
2360: if (ref($domconfig{'coursedefaults'}{'postsubmit'}) eq 'HASH') {
2361: $domdefaults{'postsubmit'} = $domconfig{'coursedefaults'}{'postsubmit'}{'client'};
2362: }
2363: foreach my $type (@coursetypes) {
2364: if (ref($domconfig{'coursedefaults'}{'coursecredits'}) eq 'HASH') {
2365: unless ($type eq 'community') {
2366: $domdefaults{$type.'credits'} = $domconfig{'coursedefaults'}{'coursecredits'}{$type};
2367: }
2368: }
2369: if (ref($domconfig{'coursedefaults'}{'uploadquota'}) eq 'HASH') {
2370: $domdefaults{$type.'quota'} = $domconfig{'coursedefaults'}{'uploadquota'}{$type};
2371: }
2372: if ($domdefaults{'postsubmit'} eq 'on') {
2373: if (ref($domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}) eq 'HASH') {
2374: $domdefaults{$type.'postsubtimeout'} =
2375: $domconfig{'coursedefaults'}{'postsubmit'}{'timeout'}{$type};
2376: }
2377: }
2378: }
2379: if (ref($domconfig{'coursedefaults'}{'canclone'}) eq 'HASH') {
2380: if (ref($domconfig{'coursedefaults'}{'canclone'}{'instcode'}) eq 'ARRAY') {
2381: my @clonecodes = @{$domconfig{'coursedefaults'}{'canclone'}{'instcode'}};
2382: if (@clonecodes) {
2383: $domdefaults{'canclone'} = join('+',@clonecodes);
2384: }
2385: }
2386: } elsif ($domconfig{'coursedefaults'}{'canclone'}) {
2387: $domdefaults{'canclone'}=$domconfig{'coursedefaults'}{'canclone'};
2388: }
2389: if ($domconfig{'coursedefaults'}{'texengine'}) {
2390: $domdefaults{'texengine'} = $domconfig{'coursedefaults'}{'texengine'};
2391: }
2392: }
2393: if (ref($domconfig{'usersessions'}) eq 'HASH') {
2394: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
2395: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
2396: }
2397: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
2398: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
2399: }
2400: if (ref($domconfig{'usersessions'}{'offloadnow'}) eq 'HASH') {
2401: $domdefaults{'offloadnow'} = $domconfig{'usersessions'}{'offloadnow'};
2402: }
2403: }
2404: if (ref($domconfig{'selfenrollment'}) eq 'HASH') {
2405: if (ref($domconfig{'selfenrollment'}{'admin'}) eq 'HASH') {
2406: my @settings = ('types','registered','enroll_dates','access_dates','section',
2407: 'approval','limit');
2408: foreach my $type (@coursetypes) {
2409: if (ref($domconfig{'selfenrollment'}{'admin'}{$type}) eq 'HASH') {
2410: my @mgrdc = ();
2411: foreach my $item (@settings) {
2412: if ($domconfig{'selfenrollment'}{'admin'}{$type}{$item} eq '0') {
2413: push(@mgrdc,$item);
2414: }
2415: }
2416: if (@mgrdc) {
2417: $domdefaults{$type.'selfenrolladmdc'} = join(',',@mgrdc);
2418: }
2419: }
2420: }
2421: }
2422: if (ref($domconfig{'selfenrollment'}{'default'}) eq 'HASH') {
2423: foreach my $type (@coursetypes) {
2424: if (ref($domconfig{'selfenrollment'}{'default'}{$type}) eq 'HASH') {
2425: foreach my $item (keys(%{$domconfig{'selfenrollment'}{'default'}{$type}})) {
2426: $domdefaults{$type.'selfenroll'.$item} = $domconfig{'selfenrollment'}{'default'}{$type}{$item};
2427: }
2428: }
2429: }
2430: }
2431: }
2432: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2433: $domdefaults{'catauth'} = 'std';
2434: $domdefaults{'catunauth'} = 'std';
2435: if ($domconfig{'coursecategories'}{'auth'}) {
2436: $domdefaults{'catauth'} = $domconfig{'coursecategories'}{'auth'};
2437: }
2438: if ($domconfig{'coursecategories'}{'unauth'}) {
2439: $domdefaults{'catunauth'} = $domconfig{'coursecategories'}{'unauth'};
2440: }
2441: }
2442: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
2443: $domdefaults{'autofailsafe'} = $domconfig{'autoenroll'}{'autofailsafe'};
2444: }
2445: if (ref($domconfig{'helpsettings'}) eq 'HASH') {
2446: $domdefaults{'submitbugs'} = $domconfig{'helpsettings'}{'submitbugs'};
2447: if (ref($domconfig{'helpsettings'}{'adhoc'}) eq 'HASH') {
2448: $domdefaults{'adhocroles'} = $domconfig{'helpsettings'}{'adhoc'};
2449: }
2450: }
2451: &do_cache_new('domdefaults',$domain,\%domdefaults,$cachetime);
2452: return %domdefaults;
2453: }
2454:
2455: sub get_dom_cats {
2456: my ($dom) = @_;
2457: return unless (&domain($dom));
2458: my ($cats,$cached)=&is_cached_new('cats',$dom);
2459: unless (defined($cached)) {
2460: my %domconfig = &get_dom('configuration',['coursecategories'],$dom);
2461: if (ref($domconfig{'coursecategories'}) eq 'HASH') {
2462: if (ref($domconfig{'coursecategories'}{'cats'}) eq 'HASH') {
2463: %{$cats} = %{$domconfig{'coursecategories'}{'cats'}};
2464: } else {
2465: $cats = {};
2466: }
2467: } else {
2468: $cats = {};
2469: }
2470: &Apache::lonnet::do_cache_new('cats',$dom,$cats,3600);
2471: }
2472: return $cats;
2473: }
2474:
2475: sub get_dom_instcats {
2476: my ($dom) = @_;
2477: return unless (&domain($dom));
2478: my ($instcats,$cached)=&is_cached_new('instcats',$dom);
2479: unless (defined($cached)) {
2480: my (%coursecodes,%codes,@codetitles,%cat_titles,%cat_order);
2481: my $totcodes = &retrieve_instcodes(\%coursecodes,$dom);
2482: if ($totcodes > 0) {
2483: my $caller = 'global';
2484: if (&auto_instcode_format($caller,$dom,\%coursecodes,\%codes,
2485: \@codetitles,\%cat_titles,\%cat_order) eq 'ok') {
2486: $instcats = {
2487: codes => \%codes,
2488: codetitles => \@codetitles,
2489: cat_titles => \%cat_titles,
2490: cat_order => \%cat_order,
2491: };
2492: &do_cache_new('instcats',$dom,$instcats,3600);
2493: }
2494: }
2495: }
2496: return $instcats;
2497: }
2498:
2499: sub retrieve_instcodes {
2500: my ($coursecodes,$dom) = @_;
2501: my $totcodes;
2502: my %courses = &courseiddump($dom,'.',1,'.','.','.',undef,undef,'Course');
2503: foreach my $course (keys(%courses)) {
2504: if (ref($courses{$course}) eq 'HASH') {
2505: if ($courses{$course}{'inst_code'} ne '') {
2506: $$coursecodes{$course} = $courses{$course}{'inst_code'};
2507: $totcodes ++;
2508: }
2509: }
2510: }
2511: return $totcodes;
2512: }
2513:
2514: # --------------------------------------------- Get domain config for passwords
2515:
2516: sub get_passwdconf {
2517: my ($dom) = @_;
2518: my (%passwdconf,$gotconf,$lookup);
2519: my ($result,$cached)=&is_cached_new('passwdconf',$dom);
2520: if (defined($cached)) {
2521: if (ref($result) eq 'HASH') {
2522: %passwdconf = %{$result};
2523: $gotconf = 1;
2524: }
2525: }
2526: unless ($gotconf) {
2527: my %domconfig = &get_dom('configuration',['passwords'],$dom);
2528: if (ref($domconfig{'passwords'}) eq 'HASH') {
2529: %passwdconf = %{$domconfig{'passwords'}};
2530: }
2531: my $cachetime = 24*60*60;
2532: &do_cache_new('passwdconf',$dom,\%passwdconf,$cachetime);
2533: }
2534: return %passwdconf;
2535: }
2536:
2537: # --------------------------------------------------- Assign a key to a student
2538:
2539: sub assign_access_key {
2540: #
2541: # a valid key looks like uname:udom#comments
2542: # comments are being appended
2543: #
2544: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2545: $kdom=
2546: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
2547: $knum=
2548: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
2549: $cdom=
2550: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2551: $cnum=
2552: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2553: $udom=$env{'user.name'} unless (defined($udom));
2554: $uname=$env{'user.domain'} unless (defined($uname));
2555: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
2556: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
2557: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
2558: # assigned to this person
2559: # - this should not happen,
2560: # unless something went wrong
2561: # the first time around
2562: # ready to assign
2563: $logentry=$1.'; '.$logentry;
2564: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
2565: $kdom,$knum) eq 'ok') {
2566: # key now belongs to user
2567: my $envkey='key.'.$cdom.'_'.$cnum;
2568: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
2569: &appenv({'environment.'.$envkey => $ckey});
2570: return 'ok';
2571: } else {
2572: return
2573: 'error: Count not permanently assign key, will need to be re-entered later.';
2574: }
2575: } else {
2576: return 'error: Could not assign key, try again later.';
2577: }
2578: } elsif (!$existing{$ckey}) {
2579: # the key does not exist
2580: return 'error: The key does not exist';
2581: } else {
2582: # the key is somebody else's
2583: return 'error: The key is already in use';
2584: }
2585: }
2586:
2587: # ------------------------------------------ put an additional comment on a key
2588:
2589: sub comment_access_key {
2590: #
2591: # a valid key looks like uname:udom#comments
2592: # comments are being appended
2593: #
2594: my ($ckey,$cdom,$cnum,$logentry)=@_;
2595: $cdom=
2596: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2597: $cnum=
2598: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2599: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2600: if ($existing{$ckey}) {
2601: $existing{$ckey}.='; '.$logentry;
2602: # ready to assign
2603: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
2604: $cdom,$cnum) eq 'ok') {
2605: return 'ok';
2606: } else {
2607: return 'error: Count not store comment.';
2608: }
2609: } else {
2610: # the key does not exist
2611: return 'error: The key does not exist';
2612: }
2613: }
2614:
2615: # ------------------------------------------------------ Generate a set of keys
2616:
2617: sub generate_access_keys {
2618: my ($number,$cdom,$cnum,$logentry)=@_;
2619: $cdom=
2620: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2621: $cnum=
2622: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2623: unless (&allowed('mky',$cdom)) { return 0; }
2624: unless (($cdom) && ($cnum)) { return 0; }
2625: if ($number>10000) { return 0; }
2626: sleep(2); # make sure don't get same seed twice
2627: srand(time()^($$+($$<<15))); # from "Programming Perl"
2628: my $total=0;
2629: for (my $i=1;$i<=$number;$i++) {
2630: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2631: sprintf("%lx",int(100000*rand)).'-'.
2632: sprintf("%lx",int(100000*rand));
2633: $newkey=~s/1/g/g; # folks mix up 1 and l
2634: $newkey=~s/0/h/g; # and also 0 and O
2635: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2636: if ($existing{$newkey}) {
2637: $i--;
2638: } else {
2639: if (&put('accesskeys',
2640: { $newkey => '# generated '.localtime().
2641: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
2642: '; '.$logentry },
2643: $cdom,$cnum) eq 'ok') {
2644: $total++;
2645: }
2646: }
2647: }
2648: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
2649: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2650: return $total;
2651: }
2652:
2653: # ------------------------------------------------------- Validate an accesskey
2654:
2655: sub validate_access_key {
2656: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2657: $cdom=
2658: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
2659: $cnum=
2660: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2661: $udom=$env{'user.domain'} unless (defined($udom));
2662: $uname=$env{'user.name'} unless (defined($uname));
2663: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2664: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
2665: }
2666:
2667: # ------------------------------------- Find the section of student in a course
2668: sub devalidate_getsection_cache {
2669: my ($udom,$unam,$courseid)=@_;
2670: my $hashid="$udom:$unam:$courseid";
2671: &devalidate_cache_new('getsection',$hashid);
2672: }
2673:
2674: sub courseid_to_courseurl {
2675: my ($courseid) = @_;
2676: #already url style courseid
2677: return $courseid if ($courseid =~ m{^/});
2678:
2679: if (exists($env{'course.'.$courseid.'.num'})) {
2680: my $cnum = $env{'course.'.$courseid.'.num'};
2681: my $cdom = $env{'course.'.$courseid.'.domain'};
2682: return "/$cdom/$cnum";
2683: }
2684:
2685: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2686: if (exists($courseinfo{'num'})) {
2687: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2688: }
2689:
2690: return undef;
2691: }
2692:
2693: sub getsection {
2694: my ($udom,$unam,$courseid)=@_;
2695: my $cachetime=1800;
2696:
2697: my $hashid="$udom:$unam:$courseid";
2698: my ($result,$cached)=&is_cached_new('getsection',$hashid);
2699: if (defined($cached)) { return $result; }
2700:
2701: my %Pending;
2702: my %Expired;
2703: #
2704: # Each role can either have not started yet (pending), be active,
2705: # or have expired.
2706: #
2707: # If there is an active role, we are done.
2708: #
2709: # If there is more than one role which has not started yet,
2710: # choose the one which will start sooner
2711: # If there is one role which has not started yet, return it.
2712: #
2713: # If there is more than one expired role, choose the one which ended last.
2714: # If there is a role which has expired, return it.
2715: #
2716: $courseid = &courseid_to_courseurl($courseid);
2717: my %roleshash = &dump('roles',$udom,$unam,$courseid);
2718: foreach my $key (keys(%roleshash)) {
2719: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
2720: my $section=$1;
2721: if ($key eq $courseid.'_st') { $section=''; }
2722: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
2723: my $now=time;
2724: if (defined($end) && $end && ($now > $end)) {
2725: $Expired{$end}=$section;
2726: next;
2727: }
2728: if (defined($start) && $start && ($now < $start)) {
2729: $Pending{$start}=$section;
2730: next;
2731: }
2732: return &do_cache_new('getsection',$hashid,$section,$cachetime);
2733: }
2734: #
2735: # Presumedly there will be few matching roles from the above
2736: # loop and the sorting time will be negligible.
2737: if (scalar(keys(%Pending))) {
2738: my ($time) = sort {$a <=> $b} keys(%Pending);
2739: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
2740: }
2741: if (scalar(keys(%Expired))) {
2742: my @sorted = sort {$a <=> $b} keys(%Expired);
2743: my $time = pop(@sorted);
2744: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
2745: }
2746: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
2747: }
2748:
2749: sub save_cache {
2750: &purge_remembered();
2751: #&Apache::loncommon::validate_page();
2752: undef(%env);
2753: undef($env_loaded);
2754: }
2755:
2756: my $to_remember=-1;
2757: my %remembered;
2758: my %accessed;
2759: my $kicks=0;
2760: my $hits=0;
2761: sub make_key {
2762: my ($name,$id) = @_;
2763: if (length($id) > 65
2764: && length(&escape($id)) > 200) {
2765: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2766: }
2767: return &escape($name.':'.$id);
2768: }
2769:
2770: sub devalidate_cache_new {
2771: my ($name,$id,$debug) = @_;
2772: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
2773: my $remembered_id=$name.':'.$id;
2774: $id=&make_key($name,$id);
2775: $memcache->delete($id);
2776: delete($remembered{$remembered_id});
2777: delete($accessed{$remembered_id});
2778: }
2779:
2780: sub is_cached_new {
2781: my ($name,$id,$debug) = @_;
2782: my $remembered_id=$name.':'.$id; # this is to avoid make_key (which is slow) for
2783: # keys in %remembered hash, which persists for
2784: # duration of request (no restriction on key length).
2785: if (exists($remembered{$remembered_id})) {
2786: if ($debug) { &Apache::lonnet::logthis("Early return $remembered_id of $remembered{$remembered_id} "); }
2787: $accessed{$remembered_id}=[&gettimeofday()];
2788: $hits++;
2789: return ($remembered{$remembered_id},1);
2790: }
2791: $id=&make_key($name,$id);
2792: my $value = $memcache->get($id);
2793: if (!(defined($value))) {
2794: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
2795: return (undef,undef);
2796: }
2797: if ($value eq '__undef__') {
2798: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2799: $value=undef;
2800: }
2801: &make_room($remembered_id,$value,$debug);
2802: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2803: return ($value,1);
2804: }
2805:
2806: sub do_cache_new {
2807: my ($name,$id,$value,$time,$debug) = @_;
2808: my $remembered_id=$name.':'.$id;
2809: $id=&make_key($name,$id);
2810: my $setvalue=$value;
2811: if (!defined($setvalue)) {
2812: $setvalue='__undef__';
2813: }
2814: if (!defined($time) ) {
2815: $time=600;
2816: }
2817: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
2818: my $result = $memcache->set($id,$setvalue,$time);
2819: if (! $result) {
2820: &logthis("caching of id -> $id failed");
2821: $memcache->disconnect_all();
2822: }
2823: # need to make a copy of $value
2824: &make_room($remembered_id,$value,$debug);
2825: return $value;
2826: }
2827:
2828: sub make_room {
2829: my ($remembered_id,$value,$debug)=@_;
2830:
2831: $remembered{$remembered_id}= (ref($value)) ? &Storable::dclone($value)
2832: : $value;
2833: if ($to_remember<0) { return; }
2834: $accessed{$remembered_id}=[&gettimeofday()];
2835: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2836: my $to_kick;
2837: my $max_time=0;
2838: foreach my $other (keys(%accessed)) {
2839: if (&tv_interval($accessed{$other}) > $max_time) {
2840: $to_kick=$other;
2841: $max_time=&tv_interval($accessed{$other});
2842: }
2843: }
2844: delete($remembered{$to_kick});
2845: delete($accessed{$to_kick});
2846: $kicks++;
2847: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
2848: return;
2849: }
2850:
2851: sub purge_remembered {
2852: #&logthis("Tossing ".scalar(keys(%remembered)));
2853: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
2854: undef(%remembered);
2855: undef(%accessed);
2856: }
2857: # ------------------------------------- Read an entry from a user's environment
2858:
2859: sub userenvironment {
2860: my ($udom,$unam,@what)=@_;
2861: my $items;
2862: foreach my $item (@what) {
2863: $items.=&escape($item).'&';
2864: }
2865: $items=~s/\&$//;
2866: my %returnhash=();
2867: my $uhome = &homeserver($unam,$udom);
2868: unless ($uhome eq 'no_host') {
2869: my @answer=split(/\&/,
2870: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
2871: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2872: return %returnhash;
2873: }
2874: my $i;
2875: for ($i=0;$i<=$#what;$i++) {
2876: $returnhash{$what[$i]}=&unescape($answer[$i]);
2877: }
2878: }
2879: return %returnhash;
2880: }
2881:
2882: # ---------------------------------------------------------- Get a studentphoto
2883: sub studentphoto {
2884: my ($udom,$unam,$ext) = @_;
2885: my $home=&Apache::lonnet::homeserver($unam,$udom);
2886: if (defined($env{'request.course.id'})) {
2887: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
2888: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2889: return(&retrievestudentphoto($udom,$unam,$ext));
2890: } else {
2891: my ($result,$perm_reqd)=
2892: &Apache::lonnet::auto_photo_permission($unam,$udom);
2893: if ($result eq 'ok') {
2894: if (!($perm_reqd eq 'yes')) {
2895: return(&retrievestudentphoto($udom,$unam,$ext));
2896: }
2897: }
2898: }
2899: }
2900: } else {
2901: my ($result,$perm_reqd) =
2902: &Apache::lonnet::auto_photo_permission($unam,$udom);
2903: if ($result eq 'ok') {
2904: if (!($perm_reqd eq 'yes')) {
2905: return(&retrievestudentphoto($udom,$unam,$ext));
2906: }
2907: }
2908: }
2909: return '/adm/lonKaputt/lonlogo_broken.gif';
2910: }
2911:
2912: sub retrievestudentphoto {
2913: my ($udom,$unam,$ext,$type) = @_;
2914: my $home=&Apache::lonnet::homeserver($unam,$udom);
2915: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2916: if ($ret eq 'ok') {
2917: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2918: if ($type eq 'thumbnail') {
2919: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2920: }
2921: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2922: return $tokenurl;
2923: } else {
2924: if ($type eq 'thumbnail') {
2925: return '/adm/lonKaputt/genericstudent_tn.gif';
2926: } else {
2927: return '/adm/lonKaputt/lonlogo_broken.gif';
2928: }
2929: }
2930: }
2931:
2932: # -------------------------------------------------------------------- New chat
2933:
2934: sub chatsend {
2935: my ($newentry,$anon,$group)=@_;
2936: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2937: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2938: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
2939: &reply('chatsend:'.$cdom.':'.$cnum.':'.
2940: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
2941: &escape($newentry)).':'.$group,$chome);
2942: }
2943:
2944: # ------------------------------------------ Find current version of a resource
2945:
2946: sub getversion {
2947: my $fname=&clutter(shift);
2948: unless ($fname=~m{^(/adm/wrapper|)/res/}) { return -1; }
2949: return ¤tversion(&filelocation('',$fname));
2950: }
2951:
2952: sub currentversion {
2953: my $fname=shift;
2954: my $author=$fname;
2955: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2956: my ($udom,$uname)=split(/\//,$author);
2957: my $home=&homeserver($uname,$udom);
2958: if ($home eq 'no_host') {
2959: return -1;
2960: }
2961: my $answer=&reply("currentversion:$fname",$home);
2962: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2963: return -1;
2964: }
2965: return $answer;
2966: }
2967:
2968: #
2969: # Return special version number of resource if set by override, empty otherwise
2970: #
2971: sub usedversion {
2972: my $fname=shift;
2973: unless ($fname) { $fname=$env{'request.uri'}; }
2974: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2975: if ($urlversion) { return $urlversion; }
2976: return '';
2977: }
2978:
2979: # ----------------------------- Subscribe to a resource, return URL if possible
2980:
2981: sub subscribe {
2982: my $fname=shift;
2983: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
2984: $fname=~s/[\n\r]//g;
2985: my $author=$fname;
2986: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2987: my ($udom,$uname)=split(/\//,$author);
2988: my $home=homeserver($uname,$udom);
2989: if ($home eq 'no_host') {
2990: return 'not_found';
2991: }
2992: my $answer=reply("sub:$fname",$home);
2993: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2994: $answer.=' by '.$home;
2995: }
2996: return $answer;
2997: }
2998:
2999: # -------------------------------------------------------------- Replicate file
3000:
3001: sub repcopy {
3002: my $filename=shift;
3003: $filename=~s/\/+/\//g;
3004: my $londocroot = $perlvar{'lonDocRoot'};
3005: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
3006: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
3007: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
3008: $filename=~m{^/*(uploaded|editupload)/}) {
3009: return &repcopy_userfile($filename);
3010: }
3011: $filename=~s/[\n\r]//g;
3012: my $transname="$filename.in.transfer";
3013: # FIXME: this should flock
3014: if ((-e $filename) || (-e $transname)) { return 'ok'; }
3015: my $remoteurl=subscribe($filename);
3016: if ($remoteurl =~ /^con_lost by/) {
3017: &logthis("Subscribe returned $remoteurl: $filename");
3018: return 'unavailable';
3019: } elsif ($remoteurl eq 'not_found') {
3020: #&logthis("Subscribe returned not_found: $filename");
3021: return 'not_found';
3022: } elsif ($remoteurl =~ /^rejected by/) {
3023: &logthis("Subscribe returned $remoteurl: $filename");
3024: return 'forbidden';
3025: } elsif ($remoteurl eq 'directory') {
3026: return 'ok';
3027: } else {
3028: my $author=$filename;
3029: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
3030: my ($udom,$uname)=split(/\//,$author);
3031: my $home=homeserver($uname,$udom);
3032: unless ($home eq $perlvar{'lonHostID'}) {
3033: my @parts=split(/\//,$filename);
3034: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
3035: if ($path ne "$londocroot/res") {
3036: &logthis("Malconfiguration for replication: $filename");
3037: return 'bad_request';
3038: }
3039: my $count;
3040: for ($count=5;$count<$#parts;$count++) {
3041: $path.="/$parts[$count]";
3042: if ((-e $path)!=1) {
3043: mkdir($path,0777);
3044: }
3045: }
3046: my $ua=new LWP::UserAgent;
3047: my $request=new HTTP::Request('GET',"$remoteurl");
3048: my $response=$ua->request($request,$transname);
3049: if ($response->is_error()) {
3050: unlink($transname);
3051: my $message=$response->status_line;
3052: &logthis("<font color=\"blue\">WARNING:"
3053: ." LWP get: $message: $filename</font>");
3054: return 'unavailable';
3055: } else {
3056: if ($remoteurl!~/\.meta$/) {
3057: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
3058: my $mresponse=$ua->request($mrequest,$filename.'.meta');
3059: if ($mresponse->is_error()) {
3060: unlink($filename.'.meta');
3061: &logthis(
3062: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
3063: }
3064: }
3065: rename($transname,$filename);
3066: return 'ok';
3067: }
3068: }
3069: }
3070: }
3071:
3072: # ------------------------------------------------ Get server side include body
3073: sub ssi_body {
3074: my ($filelink,%form)=@_;
3075: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
3076: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
3077: }
3078: my $output='';
3079: my $response;
3080: if ($filelink=~/^https?\:/) {
3081: ($output,$response)=&externalssi($filelink);
3082: } else {
3083: $filelink .= $filelink=~/\?/ ? '&' : '?';
3084: $filelink .= 'inhibitmenu=yes';
3085: ($output,$response)=&ssi($filelink,%form);
3086: }
3087: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
3088: $output=~s/^.*?\<body[^\>]*\>//si;
3089: $output=~s/\<\/body\s*\>.*?$//si;
3090: if (wantarray) {
3091: return ($output, $response);
3092: } else {
3093: return $output;
3094: }
3095: }
3096:
3097: # --------------------------------------------------------- Server Side Include
3098:
3099: sub absolute_url {
3100: my ($host_name) = @_;
3101: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
3102: if ($host_name eq '') {
3103: $host_name = $ENV{'SERVER_NAME'};
3104: }
3105: return $protocol.$host_name;
3106: }
3107:
3108: #
3109: # Server side include.
3110: # Parameters:
3111: # fn Possibly encrypted resource name/id.
3112: # form Hash that describes how the rendering should be done
3113: # and other things.
3114: # Returns:
3115: # Scalar context: The content of the response.
3116: # Array context: 2 element list of the content and the full response object.
3117: #
3118: sub ssi {
3119:
3120: my ($fn,%form)=@_;
3121: my ($request,$response);
3122:
3123: $form{'no_update_last_known'}=1;
3124: &Apache::lonenc::check_encrypt(\$fn);
3125: if (%form) {
3126: $request=new HTTP::Request('POST',&absolute_url().$fn);
3127: $request->content(join('&',map {
3128: my $name = escape($_);
3129: "$name=" . ( ref($form{$_}) eq 'ARRAY'
3130: ? join("&$name=", map {escape($_) } @{$form{$_}})
3131: : &escape($form{$_}) );
3132: } keys(%form)));
3133: } else {
3134: $request=new HTTP::Request('GET',&absolute_url().$fn);
3135: }
3136:
3137: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
3138:
3139: if (($env{'request.course.id'}) &&
3140: ($form{'grade_courseid'} eq $env{'request.course.id'}) &&
3141: ($form{'grade_username'} ne '') && ($form{'grade_domain'} ne '') &&
3142: ($form{'grade_symb'} ne '') &&
3143: (&Apache::lonnet::allowed('mgr',$env{'request.course.id'}.
3144: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:'')))) {
3145: if (LWP::UserAgent->VERSION >= 5.834) {
3146: my $ua=new LWP::UserAgent;
3147: $ua->local_address('127.0.0.1');
3148: $response = $ua->request($request);
3149: } else {
3150: {
3151: require LWP::Protocol::http;
3152: local @LWP::Protocol::http::EXTRA_SOCK_OPTS = (LocalAddr => '127.0.0.1');
3153: my $ua=new LWP::UserAgent;
3154: $response = $ua->request($request);
3155: @LWP::Protocol::http::EXTRA_SOCK_OPTS = ();
3156: }
3157: }
3158: } else {
3159: my $ua=new LWP::UserAgent;
3160: $response = $ua->request($request);
3161: }
3162: if (wantarray) {
3163: return ($response->content, $response);
3164: } else {
3165: return $response->content;
3166: }
3167: }
3168:
3169: sub externalssi {
3170: my ($url)=@_;
3171: my $ua=new LWP::UserAgent;
3172: my $request=new HTTP::Request('GET',$url);
3173: my $response=$ua->request($request);
3174: if (wantarray) {
3175: return ($response->content, $response);
3176: } else {
3177: return $response->content;
3178: }
3179: }
3180:
3181: # If the local copy of a replicated resource is outdated, trigger a
3182: # connection from the homeserver to flush the delayed queue. If no update
3183: # happens, remove local copies of outdated resource (and corresponding
3184: # metadata file).
3185:
3186: sub remove_stale_resfile {
3187: my ($url) = @_;
3188: my $removed;
3189: if ($url=~m{^/res/($match_domain)/($match_username)/}) {
3190: my $audom = $1;
3191: my $auname = $2;
3192: unless (($url =~ /\.\d+\.\w+$/) || ($url =~ m{^/res/lib/templates/})) {
3193: my $homeserver = &homeserver($auname,$audom);
3194: unless (($homeserver eq 'no_host') ||
3195: (grep { $_ eq $homeserver } ¤t_machine_ids())) {
3196: my $fname = &filelocation('',$url);
3197: if (-e $fname) {
3198: my $hostname = &hostname($homeserver);
3199: if ($hostname) {
3200: my $protocol = $protocol{$homeserver};
3201: $protocol = 'http' if ($protocol ne 'https');
3202: my $uri = $protocol.'://'.$hostname.'/raw/'.&declutter($url);
3203: my $ua=new LWP::UserAgent;
3204: $ua->timeout(5);
3205: my $request=new HTTP::Request('HEAD',$uri);
3206: my $response=$ua->request($request);
3207: if ($response->is_success()) {
3208: my $remmodtime = &HTTP::Date::str2time( $response->header('Last-modified') );
3209: my $locmodtime = (stat($fname))[9];
3210: if ($locmodtime < $remmodtime) {
3211: my $stale;
3212: my $answer = &reply('pong',$homeserver);
3213: if ($answer eq $homeserver.':'.$perlvar{'lonHostID'}) {
3214: sleep(0.2);
3215: $locmodtime = (stat($fname))[9];
3216: if ($locmodtime < $remmodtime) {
3217: my $posstransfer = $fname.'.in.transfer';
3218: if ((-e $posstransfer) && ($remmodtime < (stat($posstransfer))[9])) {
3219: $removed = 1;
3220: } else {
3221: $stale = 1;
3222: }
3223: } else {
3224: $removed = 1;
3225: }
3226: } else {
3227: $stale = 1;
3228: }
3229: if ($stale) {
3230: unlink($fname);
3231: if ($uri!~/\.meta$/) {
3232: unlink($fname.'.meta');
3233: }
3234: &reply("unsub:$fname",$homeserver);
3235: $removed = 1;
3236: }
3237: }
3238: }
3239: }
3240: }
3241: }
3242: }
3243: }
3244: return $removed;
3245: }
3246:
3247: # -------------------------------- Allow a /uploaded/ URI to be vouched for
3248:
3249: sub allowuploaded {
3250: my ($srcurl,$url)=@_;
3251: $url=&clutter(&declutter($url));
3252: my $dir=$url;
3253: $dir=~s/\/[^\/]+$//;
3254: my %httpref=();
3255: my $httpurl=&hreflocation('',$url);
3256: $httpref{'httpref.'.$httpurl}=$srcurl;
3257: &Apache::lonnet::appenv(\%httpref);
3258: }
3259:
3260: #
3261: # Determine if the current user should be able to edit a particular resource,
3262: # when viewing in course context.
3263: # (a) When viewing resource used to determine if "Edit" item is included in
3264: # Functions.
3265: # (b) When displaying folder contents in course editor, used to determine if
3266: # "Edit" link will be displayed alongside resource.
3267: #
3268: # input: six args -- filename (decluttered), course number, course domain,
3269: # url, symb (if registered) and group (if this is a group
3270: # item -- e.g., bulletin board, group page etc.).
3271: # output: array of five scalars --
3272: # $cfile -- url for file editing if editable on current server
3273: # $home -- homeserver of resource (i.e., for author if published,
3274: # or course if uploaded.).
3275: # $switchserver -- 1 if server switch will be needed.
3276: # $forceedit -- 1 if icon/link should be to go to edit mode
3277: # $forceview -- 1 if icon/link should be to go to view mode
3278: #
3279:
3280: sub can_edit_resource {
3281: my ($file,$cnum,$cdom,$resurl,$symb,$group) = @_;
3282: my ($cfile,$home,$switchserver,$forceedit,$forceview,$uploaded,$incourse);
3283: #
3284: # For aboutme pages user can only edit his/her own.
3285: #
3286: if ($resurl =~ m{^/?adm/($match_domain)/($match_username)/aboutme$}) {
3287: my ($sdom,$sname) = ($1,$2);
3288: if (($sdom eq $env{'user.domain'}) && ($sname eq $env{'user.name'})) {
3289: $home = $env{'user.home'};
3290: $cfile = $resurl;
3291: if ($env{'form.forceedit'}) {
3292: $forceview = 1;
3293: } else {
3294: $forceedit = 1;
3295: }
3296: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3297: } else {
3298: return;
3299: }
3300: }
3301:
3302: if ($env{'request.course.id'}) {
3303: my $crsedit = &Apache::lonnet::allowed('mdc',$env{'request.course.id'});
3304: if ($group ne '') {
3305: # if this is a group homepage or group bulletin board, check group privs
3306: my $allowed = 0;
3307: if ($resurl =~ m{^/?adm/$cdom/$cnum/$group/smppg$}) {
3308: if ((&allowed('mdg',$env{'request.course.id'}.
3309: ($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3310: (&allowed('mgh',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3311: $allowed = 1;
3312: }
3313: } elsif ($resurl =~ m{^/?adm/$cdom/$cnum/\d+/bulletinboard$}) {
3314: if ((&allowed('mdg',$env{'request.course.id'}.($env{'request.course.sec'}?'/'.$env{'request.course.sec'}:''))) ||
3315: (&allowed('cgb',$env{'request.course.id'}.'/'.$group)) || $crsedit) {
3316: $allowed = 1;
3317: }
3318: }
3319: if ($allowed) {
3320: $home=&homeserver($cnum,$cdom);
3321: if ($env{'form.forceedit'}) {
3322: $forceview = 1;
3323: } else {
3324: $forceedit = 1;
3325: }
3326: $cfile = $resurl;
3327: } else {
3328: return;
3329: }
3330: } else {
3331: if ($resurl =~ m{^/?adm/viewclasslist$}) {
3332: unless (&Apache::lonnet::allowed('opa',$env{'request.course.id'})) {
3333: return;
3334: }
3335: } elsif (!$crsedit) {
3336: #
3337: # No edit allowed where CC has switched to student role.
3338: #
3339: return;
3340: }
3341: }
3342: }
3343:
3344: if ($file ne '') {
3345: if (($cnum =~ /$match_courseid/) && ($cdom =~ /$match_domain/)) {
3346: if (&is_course_upload($file,$cnum,$cdom)) {
3347: $uploaded = 1;
3348: $incourse = 1;
3349: if ($file =~/\.(htm|html|css|js|txt)$/) {
3350: $cfile = &hreflocation('',$file);
3351: if ($env{'form.forceedit'}) {
3352: $forceview = 1;
3353: } else {
3354: $forceedit = 1;
3355: }
3356: }
3357: } elsif ($resurl =~ m{^/public/$cdom/$cnum/syllabus}) {
3358: $incourse = 1;
3359: if ($env{'form.forceedit'}) {
3360: $forceview = 1;
3361: } else {
3362: $forceedit = 1;
3363: }
3364: $cfile = $resurl;
3365: } elsif (($resurl ne '') && (&is_on_map($resurl))) {
3366: if ($resurl =~ m{^/adm/$match_domain/$match_username/\d+/smppg|bulletinboard$}) {
3367: $incourse = 1;
3368: if ($env{'form.forceedit'}) {
3369: $forceview = 1;
3370: } else {
3371: $forceedit = 1;
3372: }
3373: $cfile = $resurl;
3374: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem') {
3375: $incourse = 1;
3376: $cfile = $resurl.'/smpedit';
3377: } elsif ($resurl =~ m{^/adm/wrapper/ext/}) {
3378: $incourse = 1;
3379: if ($env{'form.forceedit'}) {
3380: $forceview = 1;
3381: } else {
3382: $forceedit = 1;
3383: }
3384: $cfile = $resurl;
3385: } elsif (($resurl =~ m{^/ext/}) && ($symb ne '')) {
3386: my ($map,$id,$res) = &decode_symb($symb);
3387: if ($map =~ /\.page$/) {
3388: $incourse = 1;
3389: if ($env{'form.forceedit'}) {
3390: $forceview = 1;
3391: $cfile = $map;
3392: } else {
3393: $forceedit = 1;
3394: $cfile = '/adm/wrapper'.$resurl;
3395: }
3396: }
3397: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3398: $incourse = 1;
3399: if ($env{'form.forceedit'}) {
3400: $forceview = 1;
3401: } else {
3402: $forceedit = 1;
3403: }
3404: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3405: }
3406: } elsif ($resurl eq '/res/lib/templates/simpleproblem.problem/smpedit') {
3407: my $template = '/res/lib/templates/simpleproblem.problem';
3408: if (&is_on_map($template)) {
3409: $incourse = 1;
3410: $forceview = 1;
3411: $cfile = $template;
3412: }
3413: } elsif (($resurl =~ m{^/adm/wrapper/ext/}) && ($env{'form.folderpath'} =~ /^supplemental/)) {
3414: $incourse = 1;
3415: if ($env{'form.forceedit'}) {
3416: $forceview = 1;
3417: } else {
3418: $forceedit = 1;
3419: }
3420: $cfile = $resurl;
3421: } elsif (($resurl eq '/adm/extresedit') && ($symb || $env{'form.folderpath'})) {
3422: $incourse = 1;
3423: $forceview = 1;
3424: if ($symb) {
3425: my ($map,$id,$res)=&decode_symb($symb);
3426: $env{'request.symb'} = $symb;
3427: $cfile = &clutter($res);
3428: } else {
3429: $cfile = $env{'form.suppurl'};
3430: $cfile =~ s{^http://}{};
3431: $cfile = '/adm/wrapper/ext/'.$cfile;
3432: }
3433: } elsif ($resurl =~ m{^/?adm/viewclasslist$}) {
3434: if ($env{'form.forceedit'}) {
3435: $forceview = 1;
3436: } else {
3437: $forceedit = 1;
3438: }
3439: $cfile = ($resurl =~ m{^/} ? $resurl : "/$resurl");
3440: }
3441: }
3442: if ($uploaded || $incourse) {
3443: $home=&homeserver($cnum,$cdom);
3444: } elsif ($file !~ m{/$}) {
3445: $file=~s{^(priv/$match_domain/$match_username)}{/$1};
3446: $file=~s{^($match_domain/$match_username)}{/priv/$1};
3447: # Check that the user has permission to edit this resource
3448: my $setpriv = 1;
3449: my ($cfuname,$cfudom)=&constructaccess($file,$setpriv);
3450: if (defined($cfudom)) {
3451: $home=&homeserver($cfuname,$cfudom);
3452: $cfile=$file;
3453: }
3454: }
3455: if (($cfile ne '') && (!$incourse || $uploaded) &&
3456: (($home ne '') && ($home ne 'no_host'))) {
3457: my @ids=¤t_machine_ids();
3458: unless (grep(/^\Q$home\E$/,@ids)) {
3459: $switchserver=1;
3460: }
3461: }
3462: }
3463: return ($cfile,$home,$switchserver,$forceedit,$forceview);
3464: }
3465:
3466: sub is_course_upload {
3467: my ($file,$cnum,$cdom) = @_;
3468: my $uploadpath = &LONCAPA::propath($cdom,$cnum);
3469: $uploadpath =~ s{^\/}{};
3470: if (($file =~ m{^\Q$uploadpath\E/userfiles/(docs|supplemental)/}) ||
3471: ($file =~ m{^userfiles/\Q$cdom\E/\Q$cnum\E/(docs|supplemental)/})) {
3472: return 1;
3473: }
3474: return;
3475: }
3476:
3477: sub in_course {
3478: my ($udom,$uname,$cdom,$cnum,$type,$hideprivileged) = @_;
3479: if ($hideprivileged) {
3480: my $skipuser;
3481: my %coursehash = &coursedescription($cdom.'_'.$cnum);
3482: my @possdoms = ($cdom);
3483: if ($coursehash{'checkforpriv'}) {
3484: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
3485: }
3486: if (&privileged($uname,$udom,\@possdoms)) {
3487: $skipuser = 1;
3488: if ($coursehash{'nothideprivileged'}) {
3489: foreach my $item (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3490: my $user;
3491: if ($item =~ /:/) {
3492: $user = $item;
3493: } else {
3494: $user = join(':',split(/[\@]/,$item));
3495: }
3496: if ($user eq $uname.':'.$udom) {
3497: undef($skipuser);
3498: last;
3499: }
3500: }
3501: }
3502: if ($skipuser) {
3503: return 0;
3504: }
3505: }
3506: }
3507: $type ||= 'any';
3508: if (!defined($cdom) || !defined($cnum)) {
3509: my $cid = $env{'request.course.id'};
3510: $cdom = $env{'course.'.$cid.'.domain'};
3511: $cnum = $env{'course.'.$cid.'.num'};
3512: }
3513: my $typesref;
3514: if (($type eq 'any') || ($type eq 'all')) {
3515: $typesref = ['active','previous','future'];
3516: } elsif ($type eq 'previous' || $type eq 'future') {
3517: $typesref = [$type];
3518: }
3519: my %roles = &get_my_roles($uname,$udom,'userroles',
3520: $typesref,undef,[$cdom]);
3521: my ($tmp) = keys(%roles);
3522: return 0 if ($tmp =~ /^(con_lost|error|no_such_host)/i);
3523: my @course_roles = grep(/^\Q$cnum\E:\Q$cdom\E:/, keys(%roles));
3524: if (@course_roles > 0) {
3525: return 1;
3526: }
3527: return 0;
3528: }
3529:
3530: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
3531: # input: action, courseID, current domain, intended
3532: # path to file, source of file, instruction to parse file for objects,
3533: # ref to hash for embedded objects,
3534: # ref to hash for codebase of java objects.
3535: # reference to scalar to accommodate mime type determined
3536: # from File::MMagic if $parser = parse.
3537: #
3538: # output: url to file (if action was uploaddoc),
3539: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
3540: #
3541: # Allows directory structure to be used within lonUsers/../userfiles/ for a
3542: # course.
3543: #
3544: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3545: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
3546: # course's home server.
3547: #
3548: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
3549: # be copied from $source (current location) to
3550: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3551: # and will then be copied to
3552: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
3553: # course's home server.
3554: #
3555: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3556: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
3557: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
3558: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
3559: # in course's home server.
3560: #
3561:
3562: sub process_coursefile {
3563: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
3564: $mimetype)=@_;
3565: my $fetchresult;
3566: my $home=&homeserver($docuname,$docudom);
3567: if ($action eq 'propagate') {
3568: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3569: $home);
3570: } else {
3571: my $fpath = '';
3572: my $fname = $file;
3573: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3574: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3575: my $filepath = &build_filepath($fpath);
3576: if ($action eq 'copy') {
3577: if ($source eq '') {
3578: $fetchresult = 'no source file';
3579: return $fetchresult;
3580: } else {
3581: my $destination = $filepath.'/'.$fname;
3582: rename($source,$destination);
3583: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3584: $home);
3585: }
3586: } elsif ($action eq 'uploaddoc') {
3587: open(my $fh,'>',$filepath.'/'.$fname);
3588: print $fh $env{'form.'.$source};
3589: close($fh);
3590: if ($parser eq 'parse') {
3591: my $mm = new File::MMagic;
3592: my $type = $mm->checktype_filename($filepath.'/'.$fname);
3593: if ($type eq 'text/html') {
3594: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
3595: unless ($parse_result eq 'ok') {
3596: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
3597: }
3598: }
3599: if (ref($mimetype)) {
3600: $$mimetype = $type;
3601: }
3602: }
3603: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3604: $home);
3605: if ($fetchresult eq 'ok') {
3606: return '/uploaded/'.$fpath.'/'.$fname;
3607: } else {
3608: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3609: ' to host '.$home.': '.$fetchresult);
3610: return '/adm/notfound.html';
3611: }
3612: }
3613: }
3614: unless ( $fetchresult eq 'ok') {
3615: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3616: ' to host '.$home.': '.$fetchresult);
3617: }
3618: return $fetchresult;
3619: }
3620:
3621: sub build_filepath {
3622: my ($fpath) = @_;
3623: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
3624: unless ($fpath eq '') {
3625: my @parts=split('/',$fpath);
3626: foreach my $part (@parts) {
3627: $filepath.= '/'.$part;
3628: if ((-e $filepath)!=1) {
3629: mkdir($filepath,0777);
3630: }
3631: }
3632: }
3633: return $filepath;
3634: }
3635:
3636: sub store_edited_file {
3637: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
3638: my $file = $primary_url;
3639: $file =~ s#^/uploaded/$docudom/$docuname/##;
3640: my $fpath = '';
3641: my $fname = $file;
3642: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
3643: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
3644: my $filepath = &build_filepath($fpath);
3645: open(my $fh,'>',$filepath.'/'.$fname);
3646: print $fh $content;
3647: close($fh);
3648: my $home=&homeserver($docuname,$docudom);
3649: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
3650: $home);
3651: if ($$fetchresult eq 'ok') {
3652: return '/uploaded/'.$fpath.'/'.$fname;
3653: } else {
3654: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
3655: ' to host '.$home.': '.$$fetchresult);
3656: return '/adm/notfound.html';
3657: }
3658: }
3659:
3660: sub clean_filename {
3661: my ($fname,$args)=@_;
3662: # Replace Windows backslashes by forward slashes
3663: $fname=~s/\\/\//g;
3664: if (!$args->{'keep_path'}) {
3665: # Get rid of everything but the actual filename
3666: $fname=~s/^.*\/([^\/]+)$/$1/;
3667: }
3668: # Replace spaces by underscores
3669: $fname=~s/\s+/\_/g;
3670: # Transliterate non-ascii text to ascii
3671: my $lang = &Apache::lonlocal::current_language();
3672: $fname = &LONCAPA::transliterate::fname_to_ascii($fname,$lang);
3673: # Replace all other weird characters by nothing
3674: $fname=~s{[^/\w\.\-]}{}g;
3675: # Replace all .\d. sequences with _\d. so they no longer look like version
3676: # numbers
3677: $fname=~s/\.(\d+)(?=\.)/_$1/g;
3678: return $fname;
3679: }
3680:
3681: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
3682: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
3683: # image with the same aspect ratio as the original, but with dimensions which do
3684: # not exceed $resizewidth and $resizeheight.
3685:
3686: sub resizeImage {
3687: my ($img_path,$resizewidth,$resizeheight) = @_;
3688: my $ima = Image::Magick->new;
3689: my $resized;
3690: if (-e $img_path) {
3691: $ima->Read($img_path);
3692: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
3693: my $width = $ima->Get('width');
3694: my $height = $ima->Get('height');
3695: if ($width > $resizewidth) {
3696: my $factor = $width/$resizewidth;
3697: my $newheight = $height/$factor;
3698: $ima->Scale(width=>$resizewidth,height=>$newheight);
3699: $resized = 1;
3700: }
3701: }
3702: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
3703: my $width = $ima->Get('width');
3704: my $height = $ima->Get('height');
3705: if ($height > $resizeheight) {
3706: my $factor = $height/$resizeheight;
3707: my $newwidth = $width/$factor;
3708: $ima->Scale(width=>$newwidth,height=>$resizeheight);
3709: $resized = 1;
3710: }
3711: }
3712: if ($resized) {
3713: $ima->Write($img_path);
3714: }
3715: }
3716: return;
3717: }
3718:
3719: # --------------- Take an uploaded file and put it into the userfiles directory
3720: # input: $formname - the contents of the file are in $env{"form.$formname"}
3721: # the desired filename is in $env{"form.$formname.filename"}
3722: # $context - possible values: coursedoc, existingfile, overwrite,
3723: # canceloverwrite, scantron or ''.
3724: # if 'coursedoc': upload to the current course
3725: # if 'existingfile': write file to tmp/overwrites directory
3726: # if 'canceloverwrite': delete file written to tmp/overwrites directory
3727: # $context is passed as argument to &finishuserfileupload
3728: # $subdir - directory in userfile to store the file into
3729: # $parser - instruction to parse file for objects ($parser = parse) or
3730: # if context is 'scantron', $parser is hashref of csv column mapping
3731: # (e.g.,{ PaperID => 0, LastName => 1, FirstName => 2, ID => 3,
3732: # Section => 4, CODE => 5, FirstQuestion => 9 }).
3733: # $allfiles - reference to hash for embedded objects
3734: # $codebase - reference to hash for codebase of java objects
3735: # $desuname - username for permanent storage of uploaded file
3736: # $dsetudom - domain for permanaent storage of uploaded file
3737: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
3738: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
3739: # $resizewidth - width (pixels) to which to resize uploaded image
3740: # $resizeheight - height (pixels) to which to resize uploaded image
3741: # $mimetype - reference to scalar to accommodate mime type determined
3742: # from File::MMagic.
3743: #
3744: # output: url of file in userspace, or error: <message>
3745: # or /adm/notfound.html if failure to upload occurse
3746:
3747: sub userfileupload {
3748: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
3749: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
3750: if (!defined($subdir)) { $subdir='unknown'; }
3751: my $fname=$env{'form.'.$formname.'.filename'};
3752: $fname=&clean_filename($fname);
3753: # See if there is anything left
3754: unless ($fname) { return 'error: no uploaded file'; }
3755: # If filename now begins with a . prepend unix timestamp _ milliseconds
3756: if ($fname =~ /^\./) {
3757: my ($s,$usec) = &gettimeofday();
3758: while (length($usec) < 6) {
3759: $usec = '0'.$usec;
3760: }
3761: $fname = $s.'_'.substr($usec,0,3).$fname;
3762: }
3763: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
3764: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
3765: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
3766: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3767: my $now = time;
3768: my $filepath;
3769: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
3770: $filepath = 'tmp/helprequests/'.$now;
3771: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
3772: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
3773: '_'.$env{'user.domain'}.'/pending';
3774: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
3775: my ($docuname,$docudom);
3776: if ($destudom =~ /^$match_domain$/) {
3777: $docudom = $destudom;
3778: } else {
3779: $docudom = $env{'user.domain'};
3780: }
3781: if ($destuname =~ /^$match_username$/) {
3782: $docuname = $destuname;
3783: } else {
3784: $docuname = $env{'user.name'};
3785: }
3786: if (exists($env{'form.group'})) {
3787: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3788: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3789: }
3790: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
3791: if ($context eq 'canceloverwrite') {
3792: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
3793: if (-e $tempfile) {
3794: my @info = stat($tempfile);
3795: if ($info[9] eq $env{'form.timestamp'}) {
3796: unlink($tempfile);
3797: }
3798: }
3799: return;
3800: }
3801: }
3802: # Create the directory if not present
3803: my @parts=split(/\//,$filepath);
3804: my $fullpath = $perlvar{'lonDaemons'};
3805: for (my $i=0;$i<@parts;$i++) {
3806: $fullpath .= '/'.$parts[$i];
3807: if ((-e $fullpath)!=1) {
3808: mkdir($fullpath,0777);
3809: }
3810: }
3811: open(my $fh,'>',$fullpath.'/'.$fname);
3812: print $fh $env{'form.'.$formname};
3813: close($fh);
3814: if ($context eq 'existingfile') {
3815: my @info = stat($fullpath.'/'.$fname);
3816: return ($fullpath.'/'.$fname,$info[9]);
3817: } else {
3818: return $fullpath.'/'.$fname;
3819: }
3820: }
3821: if ($subdir eq 'scantron') {
3822: $fname = 'scantron_orig_'.$fname;
3823: } else {
3824: $fname="$subdir/$fname";
3825: }
3826: if ($context eq 'coursedoc') {
3827: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3828: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3829: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
3830: return &finishuserfileupload($docuname,$docudom,
3831: $formname,$fname,$parser,$allfiles,
3832: $codebase,$thumbwidth,$thumbheight,
3833: $resizewidth,$resizeheight,$context,$mimetype);
3834: } else {
3835: if ($env{'form.folder'}) {
3836: $fname=$env{'form.folder'}.'/'.$fname;
3837: }
3838: return &process_coursefile('uploaddoc',$docuname,$docudom,
3839: $fname,$formname,$parser,
3840: $allfiles,$codebase,$mimetype);
3841: }
3842: } elsif (defined($destuname)) {
3843: my $docuname=$destuname;
3844: my $docudom=$destudom;
3845: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3846: $parser,$allfiles,$codebase,
3847: $thumbwidth,$thumbheight,
3848: $resizewidth,$resizeheight,$context,$mimetype);
3849: } else {
3850: my $docuname=$env{'user.name'};
3851: my $docudom=$env{'user.domain'};
3852: if ((exists($env{'form.group'})) || ($context eq 'syllabus')) {
3853: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
3854: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
3855: }
3856: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
3857: $parser,$allfiles,$codebase,
3858: $thumbwidth,$thumbheight,
3859: $resizewidth,$resizeheight,$context,$mimetype);
3860: }
3861: }
3862:
3863: sub finishuserfileupload {
3864: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
3865: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
3866: my $path=$docudom.'/'.$docuname.'/';
3867: my $filepath=$perlvar{'lonDocRoot'};
3868:
3869: my ($fnamepath,$file,$fetchthumb);
3870: $file=$fname;
3871: if ($fname=~m|/|) {
3872: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
3873: $path.=$fnamepath.'/';
3874: }
3875: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
3876: my $count;
3877: for ($count=4;$count<=$#parts;$count++) {
3878: $filepath.="/$parts[$count]";
3879: if ((-e $filepath)!=1) {
3880: mkdir($filepath,0777);
3881: }
3882: }
3883:
3884: # Save the file
3885: {
3886: if (!open(FH,'>',$filepath.'/'.$file)) {
3887: &logthis('Failed to create '.$filepath.'/'.$file);
3888: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
3889: return '/adm/notfound.html';
3890: }
3891: if ($context eq 'overwrite') {
3892: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
3893: my $target = $filepath.'/'.$file;
3894: if (-e $source) {
3895: my @info = stat($source);
3896: if ($info[9] eq $env{'form.timestamp'}) {
3897: unless (&File::Copy::move($source,$target)) {
3898: &logthis('Failed to overwrite '.$filepath.'/'.$file);
3899: return "Moving from $source failed";
3900: }
3901: } else {
3902: return "Temporary file: $source had unexpected date/time for last modification";
3903: }
3904: } else {
3905: return "Temporary file: $source missing";
3906: }
3907: } elsif (!print FH ($env{'form.'.$formname})) {
3908: &logthis('Failed to write to '.$filepath.'/'.$file);
3909: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
3910: return '/adm/notfound.html';
3911: }
3912: close(FH);
3913: if ($resizewidth && $resizeheight) {
3914: my $mm = new File::MMagic;
3915: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
3916: if ($mime_type =~ m{^image/}) {
3917: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
3918: }
3919: }
3920: }
3921: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3922: if (ref($mimetype)) {
3923: if ($$mimetype eq '') {
3924: my $mm = new File::MMagic;
3925: my $type = $mm->checktype_filename($filepath.'/'.$file);
3926: $$mimetype = $type;
3927: }
3928: }
3929: }
3930: if (($context ne 'scantron') && ($parser eq 'parse')) {
3931: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
3932: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3933: $allfiles,$codebase);
3934: unless ($parse_result eq 'ok') {
3935: &logthis('Failed to parse '.$filepath.$file.
3936: ' for embedded media: '.$parse_result);
3937: }
3938: }
3939: } elsif (($context eq 'scantron') && (ref($parser) eq 'HASH')) {
3940: my $format = $env{'form.scantron_format'};
3941: &bubblesheet_converter($docudom,$filepath.'/'.$file,$parser,$format);
3942: }
3943: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3944: my $input = $filepath.'/'.$file;
3945: my $output = $filepath.'/'.'tn-'.$file;
3946: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3947: my @args = ('convert','-sample',$thumbsize,$input,$output);
3948: system({$args[0]} @args);
3949: if (-e $filepath.'/'.'tn-'.$file) {
3950: $fetchthumb = 1;
3951: }
3952: }
3953:
3954: # Notify homeserver to grep it
3955: #
3956: my $docuhome=&homeserver($docuname,$docudom);
3957: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
3958: if ($fetchresult eq 'ok') {
3959: if ($fetchthumb) {
3960: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3961: if ($thumbresult ne 'ok') {
3962: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3963: $docuhome.': '.$thumbresult);
3964: }
3965: }
3966: #
3967: # Return the URL to it
3968: return '/uploaded/'.$path.$file;
3969: } else {
3970: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3971: ': '.$fetchresult);
3972: return '/adm/notfound.html';
3973: }
3974: }
3975:
3976: sub extract_embedded_items {
3977: my ($fullpath,$allfiles,$codebase,$content) = @_;
3978: my @state = ();
3979: my (%lastids,%related,%shockwave,%flashvars);
3980: my %javafiles = (
3981: codebase => '',
3982: code => '',
3983: archive => ''
3984: );
3985: my %mediafiles = (
3986: src => '',
3987: movie => '',
3988: );
3989: my $p;
3990: if ($content) {
3991: $p = HTML::LCParser->new($content);
3992: } else {
3993: $p = HTML::LCParser->new($fullpath);
3994: }
3995: while (my $t=$p->get_token()) {
3996: if ($t->[0] eq 'S') {
3997: my ($tagname, $attr) = ($t->[1],$t->[2]);
3998: push(@state, $tagname);
3999: if (lc($tagname) eq 'allow') {
4000: &add_filetype($allfiles,$attr->{'src'},'src');
4001: }
4002: if (lc($tagname) eq 'img') {
4003: &add_filetype($allfiles,$attr->{'src'},'src');
4004: }
4005: if (lc($tagname) eq 'a') {
4006: unless (($attr->{'href'} =~ /^#/) || ($attr->{'href'} eq '')) {
4007: &add_filetype($allfiles,$attr->{'href'},'href');
4008: }
4009: }
4010: if (lc($tagname) eq 'script') {
4011: my $src;
4012: if ($attr->{'archive'} =~ /\.jar$/i) {
4013: &add_filetype($allfiles,$attr->{'archive'},'archive');
4014: } else {
4015: if ($attr->{'src'} ne '') {
4016: $src = $attr->{'src'};
4017: &add_filetype($allfiles,$src,'src');
4018: }
4019: }
4020: my $text = $p->get_trimmed_text();
4021: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
4022: my @swfargs = split(/,/,$1);
4023: foreach my $item (@swfargs) {
4024: $item =~ s/["']//g;
4025: $item =~ s/^\s+//;
4026: $item =~ s/\s+$//;
4027: }
4028: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
4029: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
4030: push(@{$related{$swfargs[0]}},$swfargs[2]);
4031: } else {
4032: $related{$swfargs[0]} = [$swfargs[2]];
4033: }
4034: }
4035: }
4036: }
4037: if (lc($tagname) eq 'link') {
4038: if (lc($attr->{'rel'}) eq 'stylesheet') {
4039: &add_filetype($allfiles,$attr->{'href'},'href');
4040: }
4041: }
4042: if (lc($tagname) eq 'object' ||
4043: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
4044: foreach my $item (keys(%javafiles)) {
4045: $javafiles{$item} = '';
4046: }
4047: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
4048: $lastids{lc($tagname)} = $attr->{'id'};
4049: }
4050: }
4051: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
4052: my $name = lc($attr->{'name'});
4053: foreach my $item (keys(%javafiles)) {
4054: if ($name eq $item) {
4055: $javafiles{$item} = $attr->{'value'};
4056: last;
4057: }
4058: }
4059: my $pathfrom;
4060: foreach my $item (keys(%mediafiles)) {
4061: if ($name eq $item) {
4062: $pathfrom = $attr->{'value'};
4063: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
4064: &add_filetype($allfiles,$pathfrom,$name);
4065: last;
4066: }
4067: }
4068: if ($name eq 'flashvars') {
4069: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
4070: }
4071: if ($pathfrom ne '') {
4072: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
4073: $pathfrom);
4074: }
4075: }
4076: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
4077: foreach my $item (keys(%javafiles)) {
4078: if ($attr->{$item}) {
4079: $javafiles{$item} = $attr->{$item};
4080: last;
4081: }
4082: }
4083: foreach my $item (keys(%mediafiles)) {
4084: if ($attr->{$item}) {
4085: &add_filetype($allfiles,$attr->{$item},$item);
4086: last;
4087: }
4088: }
4089: if (lc($tagname) eq 'embed') {
4090: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
4091: &embedded_dependency($allfiles,\%related,$attr->{'name'},
4092: $attr->{'src'});
4093: }
4094: }
4095: }
4096: if (lc($tagname) eq 'iframe') {
4097: my $src = $attr->{'src'} ;
4098: if (($src ne '') && ($src !~ m{^(/|https?://)})) {
4099: &add_filetype($allfiles,$src,'src');
4100: } elsif ($src =~ m{^/}) {
4101: if ($env{'request.course.id'}) {
4102: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4103: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4104: my $url = &hreflocation('',$fullpath);
4105: if ($url =~ m{^/uploaded/$cdom/$cnum/docs/(\w+/\d+)/}) {
4106: my $relpath = $1;
4107: if ($src =~ m{^/uploaded/$cdom/$cnum/docs/\Q$relpath\E/(.+)$}) {
4108: &add_filetype($allfiles,$1,'src');
4109: }
4110: }
4111: }
4112: }
4113: }
4114: if ($t->[4] =~ m{/>$}) {
4115: pop(@state);
4116: }
4117: } elsif ($t->[0] eq 'E') {
4118: my ($tagname) = ($t->[1]);
4119: if ($javafiles{'codebase'} ne '') {
4120: $javafiles{'codebase'} .= '/';
4121: }
4122: if (lc($tagname) eq 'applet' ||
4123: lc($tagname) eq 'object' ||
4124: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
4125: ) {
4126: foreach my $item (keys(%javafiles)) {
4127: if ($item ne 'codebase' && $javafiles{$item} ne '') {
4128: my $file=$javafiles{'codebase'}.$javafiles{$item};
4129: &add_filetype($allfiles,$file,$item);
4130: }
4131: }
4132: }
4133: pop @state;
4134: }
4135: }
4136: foreach my $id (sort(keys(%flashvars))) {
4137: if ($shockwave{$id} ne '') {
4138: my @pairs = split(/\&/,$flashvars{$id});
4139: foreach my $pair (@pairs) {
4140: my ($key,$value) = split(/\=/,$pair);
4141: if ($key eq 'thumb') {
4142: &add_filetype($allfiles,$value,$key);
4143: } elsif ($key eq 'content') {
4144: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
4145: my ($ext) = ($value =~ /\.([^.]+)$/);
4146: if ($ext ne '') {
4147: &add_filetype($allfiles,$path.$value,$ext);
4148: }
4149: }
4150: }
4151: }
4152: }
4153: return 'ok';
4154: }
4155:
4156: sub add_filetype {
4157: my ($allfiles,$file,$type)=@_;
4158: if (exists($allfiles->{$file})) {
4159: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
4160: push(@{$allfiles->{$file}}, &escape($type));
4161: }
4162: } else {
4163: @{$allfiles->{$file}} = (&escape($type));
4164: }
4165: }
4166:
4167: sub embedded_dependency {
4168: my ($allfiles,$related,$identifier,$pathfrom) = @_;
4169: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
4170: if (($identifier ne '') &&
4171: (ref($related->{$identifier}) eq 'ARRAY') &&
4172: ($pathfrom ne '')) {
4173: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
4174: foreach my $dep (@{$related->{$identifier}}) {
4175: &add_filetype($allfiles,$path.$dep,'object');
4176: }
4177: }
4178: }
4179: return;
4180: }
4181:
4182: sub bubblesheet_converter {
4183: my ($cdom,$fullpath,$config,$format) = @_;
4184: if ((&domain($cdom) ne '') &&
4185: ($fullpath =~ m{^\Q$perlvar{'lonDocRoot'}/userfiles/$cdom/\E$match_courseid/scantron_orig}) &&
4186: (-e $fullpath) && (ref($config) eq 'HASH') && ($format ne '')) {
4187: my (%csvcols,%csvoptions);
4188: if (ref($config->{'fields'}) eq 'HASH') {
4189: %csvcols = %{$config->{'fields'}};
4190: }
4191: if (ref($config->{'options'}) eq 'HASH') {
4192: %csvoptions = %{$config->{'options'}};
4193: }
4194: my %csvbynum = reverse(%csvcols);
4195: my %scantronconf = &get_scantron_config($format,$cdom);
4196: if (keys(%scantronconf)) {
4197: my %bynum = (
4198: $scantronconf{CODEstart} => 'CODEstart',
4199: $scantronconf{IDstart} => 'IDstart',
4200: $scantronconf{PaperID} => 'PaperID',
4201: $scantronconf{FirstName} => 'FirstName',
4202: $scantronconf{LastName} => 'LastName',
4203: $scantronconf{Qstart} => 'Qstart',
4204: );
4205: my @ordered;
4206: foreach my $item (sort { $a <=> $b } keys(%bynum)) {
4207: push(@ordered,$bynum{$item});
4208: }
4209: my %mapstart = (
4210: CODEstart => 'CODE',
4211: IDstart => 'ID',
4212: PaperID => 'PaperID',
4213: FirstName => 'FirstName',
4214: LastName => 'LastName',
4215: Qstart => 'FirstQuestion',
4216: );
4217: my %maplength = (
4218: CODEstart => 'CODElength',
4219: IDstart => 'IDlength',
4220: PaperID => 'PaperIDlength',
4221: FirstName => 'FirstNamelength',
4222: LastName => 'LastNamelength',
4223: );
4224: if (open(my $fh,'<',$fullpath)) {
4225: my $output;
4226: my %lettdig = &letter_to_digits();
4227: my %diglett = reverse(%lettdig);
4228: my $numletts = scalar(keys(%lettdig));
4229: my $num = 0;
4230: while (my $line=<$fh>) {
4231: $num ++;
4232: next if (($num == 1) && ($csvoptions{'hdr'} == 1));
4233: $line =~ s{[\r\n]+$}{};
4234: my %found;
4235: my @values = split(/,/,$line);
4236: my ($qstart,$record);
4237: for (my $i=0; $i<@values; $i++) {
4238: if ((($qstart ne '') && ($i > $qstart)) ||
4239: ($csvbynum{$i} eq 'FirstQuestion')) {
4240: if ($values[$i] eq '') {
4241: $values[$i] = $scantronconf{'Qoff'};
4242: } elsif ($scantronconf{'Qon'} eq 'number') {
4243: if ($values[$i] =~ /^[A-Ja-j]$/) {
4244: $values[$i] = $lettdig{uc($values[$i])};
4245: }
4246: } elsif ($scantronconf{'Qon'} eq 'letter') {
4247: if ($values[$i] =~ /^[0-9]$/) {
4248: $values[$i] = $diglett{$values[$i]};
4249: }
4250: } else {
4251: if ($values[$i] =~ /^[0-9A-Ja-j]$/) {
4252: my $digit;
4253: if ($values[$i] =~ /^[A-Ja-j]$/) {
4254: $digit = $lettdig{uc($values[$i])}-1;
4255: if ($values[$i] eq 'J') {
4256: $digit += $numletts;
4257: }
4258: } elsif ($values[$i] =~ /^[0-9]$/) {
4259: $digit = $values[$i]-1;
4260: if ($values[$i] eq '0') {
4261: $digit += $numletts;
4262: }
4263: }
4264: my $qval='';
4265: for (my $j=0; $j<$scantronconf{'Qlength'}; $j++) {
4266: if ($j == $digit) {
4267: $qval .= $scantronconf{'Qon'};
4268: } else {
4269: $qval .= $scantronconf{'Qoff'};
4270: }
4271: }
4272: $values[$i] = $qval;
4273: }
4274: }
4275: if (length($values[$i]) > $scantronconf{'Qlength'}) {
4276: $values[$i] = substr($values[$i],0,$scantronconf{'Qlength'});
4277: }
4278: my $numblank = $scantronconf{'Qlength'} - length($values[$i]);
4279: if ($numblank > 0) {
4280: $values[$i] .= ($scantronconf{'Qoff'} x $numblank);
4281: }
4282: if ($csvbynum{$i} eq 'FirstQuestion') {
4283: $qstart = $i;
4284: $found{$csvbynum{$i}} = $values[$i];
4285: } else {
4286: $found{'FirstQuestion'} .= $values[$i];
4287: }
4288: } elsif (exists($csvbynum{$i})) {
4289: if ($csvoptions{'rem'}) {
4290: $values[$i] =~ s/^\s+//;
4291: }
4292: if (($csvbynum{$i} eq 'PaperID') && ($csvoptions{'pad'})) {
4293: while (length($values[$i]) < $scantronconf{$maplength{$csvbynum{$i}}}) {
4294: $values[$i] = '0'.$values[$i];
4295: }
4296: }
4297: $found{$csvbynum{$i}} = $values[$i];
4298: }
4299: }
4300: foreach my $item (@ordered) {
4301: my $currlength = 1+length($record);
4302: my $numspaces = $scantronconf{$item} - $currlength;
4303: if ($numspaces > 0) {
4304: $record .= (' ' x $numspaces);
4305: }
4306: if (($mapstart{$item} ne '') && (exists($found{$mapstart{$item}}))) {
4307: unless ($item eq 'Qstart') {
4308: if (length($found{$mapstart{$item}}) > $scantronconf{$maplength{$item}}) {
4309: $found{$mapstart{$item}} = substr($found{$mapstart{$item}},0,$scantronconf{$maplength{$item}});
4310: }
4311: }
4312: $record .= $found{$mapstart{$item}};
4313: }
4314: }
4315: $output .= "$record\n";
4316: }
4317: close($fh);
4318: if ($output) {
4319: if (open(my $fh,'>',$fullpath)) {
4320: print $fh $output;
4321: close($fh);
4322: }
4323: }
4324: }
4325: }
4326: return;
4327: }
4328: }
4329:
4330: sub letter_to_digits {
4331: my %lettdig = (
4332: A => 1,
4333: B => 2,
4334: C => 3,
4335: D => 4,
4336: E => 5,
4337: F => 6,
4338: G => 7,
4339: H => 8,
4340: I => 9,
4341: J => 0,
4342: );
4343: return %lettdig;
4344: }
4345:
4346: sub get_scantron_config {
4347: my ($which,$cdom) = @_;
4348: my @lines = &get_scantronformat_file($cdom);
4349: my %config;
4350: #FIXME probably should move to XML it has already gotten a bit much now
4351: foreach my $line (@lines) {
4352: my ($name,$descrip)=split(/:/,$line);
4353: if ($name ne $which ) { next; }
4354: chomp($line);
4355: my @config=split(/:/,$line);
4356: $config{'name'}=$config[0];
4357: $config{'description'}=$config[1];
4358: $config{'CODElocation'}=$config[2];
4359: $config{'CODEstart'}=$config[3];
4360: $config{'CODElength'}=$config[4];
4361: $config{'IDstart'}=$config[5];
4362: $config{'IDlength'}=$config[6];
4363: $config{'Qstart'}=$config[7];
4364: $config{'Qlength'}=$config[8];
4365: $config{'Qoff'}=$config[9];
4366: $config{'Qon'}=$config[10];
4367: $config{'PaperID'}=$config[11];
4368: $config{'PaperIDlength'}=$config[12];
4369: $config{'FirstName'}=$config[13];
4370: $config{'FirstNamelength'}=$config[14];
4371: $config{'LastName'}=$config[15];
4372: $config{'LastNamelength'}=$config[16];
4373: $config{'BubblesPerRow'}=$config[17];
4374: last;
4375: }
4376: return %config;
4377: }
4378:
4379: sub get_scantronformat_file {
4380: my ($cdom) = @_;
4381: if ($cdom eq '') {
4382: $cdom= $env{'course.'.$env{'request.course.id'}.'.domain'};
4383: }
4384: my %domconfig = &get_dom('configuration',['scantron'],$cdom);
4385: my $gottab = 0;
4386: my @lines;
4387: if (ref($domconfig{'scantron'}) eq 'HASH') {
4388: if ($domconfig{'scantron'}{'scantronformat'} ne '') {
4389: my $formatfile = &getfile($perlvar{'lonDocRoot'}.$domconfig{'scantron'}{'scantronformat'});
4390: if ($formatfile ne '-1') {
4391: @lines = split("\n",$formatfile,-1);
4392: $gottab = 1;
4393: }
4394: }
4395: }
4396: if (!$gottab) {
4397: my $confname = $cdom.'-domainconfig';
4398: my $default = $perlvar{'lonDocRoot'}.'/res/'.$cdom.'/'.$confname.'/default.tab';
4399: my $formatfile = &getfile($default);
4400: if ($formatfile ne '-1') {
4401: @lines = split("\n",$formatfile,-1);
4402: $gottab = 1;
4403: }
4404: }
4405: if (!$gottab) {
4406: my @domains = ¤t_machine_domains();
4407: if (grep(/^\Q$cdom\E$/,@domains)) {
4408: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/scantronformat.tab')) {
4409: @lines = <$fh>;
4410: close($fh);
4411: }
4412: } else {
4413: if (open(my $fh,'<',$perlvar{'lonTabDir'}.'/default_scantronformat.tab')) {
4414: @lines = <$fh>;
4415: close($fh);
4416: }
4417: }
4418: }
4419: return @lines;
4420: }
4421:
4422: sub removeuploadedurl {
4423: my ($url)=@_;
4424: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
4425: return &removeuserfile($uname,$udom,$fname);
4426: }
4427:
4428: sub removeuserfile {
4429: my ($docuname,$docudom,$fname)=@_;
4430: my $home=&homeserver($docuname,$docudom);
4431: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
4432: if ($result eq 'ok') {
4433: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
4434: my $metafile = $fname.'.meta';
4435: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
4436: my $url = "/uploaded/$docudom/$docuname/$fname";
4437: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4438: my $sqlresult =
4439: &update_portfolio_table($docuname,$docudom,$file,
4440: 'portfolio_metadata',$group,
4441: 'delete');
4442: }
4443: }
4444: return $result;
4445: }
4446:
4447: sub mkdiruserfile {
4448: my ($docuname,$docudom,$dir)=@_;
4449: my $home=&homeserver($docuname,$docudom);
4450: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
4451: }
4452:
4453: sub renameuserfile {
4454: my ($docuname,$docudom,$old,$new)=@_;
4455: my $home=&homeserver($docuname,$docudom);
4456: my $result = &reply("renameuserfile:$docudom:$docuname:".
4457: &escape("$old").':'.&escape("$new"),$home);
4458: if ($result eq 'ok') {
4459: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
4460: my $oldmeta = $old.'.meta';
4461: my $newmeta = $new.'.meta';
4462: my $metaresult =
4463: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
4464: my $url = "/uploaded/$docudom/$docuname/$old";
4465: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
4466: my $sqlresult =
4467: &update_portfolio_table($docuname,$docudom,$file,
4468: 'portfolio_metadata',$group,
4469: 'delete');
4470: }
4471: }
4472: return $result;
4473: }
4474:
4475: # ------------------------------------------------------------------------- Log
4476:
4477: sub log {
4478: my ($dom,$nam,$hom,$what)=@_;
4479: return critical("log:$dom:$nam:$what",$hom);
4480: }
4481:
4482: # ------------------------------------------------------------------ Course Log
4483: #
4484: # This routine flushes several buffers of non-mission-critical nature
4485: #
4486:
4487: sub flushcourselogs {
4488: &logthis('Flushing log buffers');
4489: #
4490: # course logs
4491: # This is a log of all transactions in a course, which can be used
4492: # for data mining purposes
4493: #
4494: # It also collects the courseid database, which lists last transaction
4495: # times and course titles for all courseids
4496: #
4497: my %courseidbuffer=();
4498: foreach my $crsid (keys(%courselogs)) {
4499: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
4500: &escape($courselogs{$crsid}),
4501: $coursehombuf{$crsid}) eq 'ok') {
4502: delete $courselogs{$crsid};
4503: } else {
4504: &logthis('Failed to flush log buffer for '.$crsid);
4505: if (length($courselogs{$crsid})>40000) {
4506: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
4507: " exceeded maximum size, deleting.</font>");
4508: delete $courselogs{$crsid};
4509: }
4510: }
4511: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
4512: 'description' => $coursedescrbuf{$crsid},
4513: 'inst_code' => $courseinstcodebuf{$crsid},
4514: 'type' => $coursetypebuf{$crsid},
4515: 'owner' => $courseownerbuf{$crsid},
4516: };
4517: }
4518: #
4519: # Write course id database (reverse lookup) to homeserver of courses
4520: # Is used in pickcourse
4521: #
4522: foreach my $crs_home (keys(%courseidbuffer)) {
4523: my $response = &courseidput(&host_domain($crs_home),
4524: $courseidbuffer{$crs_home},
4525: $crs_home,'timeonly');
4526: }
4527: #
4528: # File accesses
4529: # Writes to the dynamic metadata of resources to get hit counts, etc.
4530: #
4531: foreach my $entry (keys(%accesshash)) {
4532: if ($entry =~ /___count$/) {
4533: my ($dom,$name);
4534: ($dom,$name,undef)=
4535: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
4536: if (! defined($dom) || $dom eq '' ||
4537: ! defined($name) || $name eq '') {
4538: my $cid = $env{'request.course.id'};
4539: $dom = $env{'request.'.$cid.'.domain'};
4540: $name = $env{'request.'.$cid.'.num'};
4541: }
4542: my $value = $accesshash{$entry};
4543: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
4544: my %temphash=($url => $value);
4545: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
4546: if ($result eq 'ok') {
4547: delete $accesshash{$entry};
4548: }
4549: } else {
4550: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
4551: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
4552: my %temphash=($entry => $accesshash{$entry});
4553: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
4554: delete $accesshash{$entry};
4555: }
4556: }
4557: }
4558: #
4559: # Roles
4560: # Reverse lookup of user roles for course faculty/staff and co-authorship
4561: #
4562: foreach my $entry (keys(%userrolehash)) {
4563: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
4564: split(/\:/,$entry);
4565: if (&Apache::lonnet::put('nohist_userroles',
4566: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
4567: $rudom,$runame) eq 'ok') {
4568: delete $userrolehash{$entry};
4569: }
4570: }
4571: #
4572: # Reverse lookup of domain roles (dc, ad, li, sc, dh, da, au)
4573: #
4574: my %domrolebuffer = ();
4575: foreach my $entry (keys(%domainrolehash)) {
4576: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
4577: if ($domrolebuffer{$rudom}) {
4578: $domrolebuffer{$rudom}.='&'.&escape($entry).
4579: '='.&escape($domainrolehash{$entry});
4580: } else {
4581: $domrolebuffer{$rudom}.=&escape($entry).
4582: '='.&escape($domainrolehash{$entry});
4583: }
4584: delete $domainrolehash{$entry};
4585: }
4586: foreach my $dom (keys(%domrolebuffer)) {
4587: my %servers;
4588: if (defined(&domain($dom,'primary'))) {
4589: my $primary=&domain($dom,'primary');
4590: my $hostname=&hostname($primary);
4591: $servers{$primary} = $hostname;
4592: } else {
4593: %servers = &get_servers($dom,'library');
4594: }
4595: foreach my $tryserver (keys(%servers)) {
4596: if (&reply('domroleput:'.$dom.':'.
4597: $domrolebuffer{$dom},$tryserver) eq 'ok') {
4598: last;
4599: } else {
4600: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
4601: }
4602: }
4603: }
4604: $dumpcount++;
4605: }
4606:
4607: sub courselog {
4608: my $what=shift;
4609: $what=time.':'.$what;
4610: unless ($env{'request.course.id'}) { return ''; }
4611: $coursedombuf{$env{'request.course.id'}}=
4612: $env{'course.'.$env{'request.course.id'}.'.domain'};
4613: $coursenumbuf{$env{'request.course.id'}}=
4614: $env{'course.'.$env{'request.course.id'}.'.num'};
4615: $coursehombuf{$env{'request.course.id'}}=
4616: $env{'course.'.$env{'request.course.id'}.'.home'};
4617: $coursedescrbuf{$env{'request.course.id'}}=
4618: $env{'course.'.$env{'request.course.id'}.'.description'};
4619: $courseinstcodebuf{$env{'request.course.id'}}=
4620: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
4621: $courseownerbuf{$env{'request.course.id'}}=
4622: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
4623: $coursetypebuf{$env{'request.course.id'}}=
4624: $env{'course.'.$env{'request.course.id'}.'.type'};
4625: if (defined $courselogs{$env{'request.course.id'}}) {
4626: $courselogs{$env{'request.course.id'}}.='&'.$what;
4627: } else {
4628: $courselogs{$env{'request.course.id'}}.=$what;
4629: }
4630: if (length($courselogs{$env{'request.course.id'}})>4048) {
4631: &flushcourselogs();
4632: }
4633: }
4634:
4635: sub courseacclog {
4636: my $fnsymb=shift;
4637: unless ($env{'request.course.id'}) { return ''; }
4638: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
4639: if ($fnsymb=~/$LONCAPA::assess_re/) {
4640: $what.=':POST';
4641: # FIXME: Probably ought to escape things....
4642: foreach my $key (keys(%env)) {
4643: if ($key=~/^form\.(.*)/) {
4644: my $formitem = $1;
4645: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
4646: $what.=':'.$formitem.'='.$env{$key};
4647: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
4648: $what.=':'.$formitem.'='.$env{$key};
4649: }
4650: }
4651: }
4652: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
4653: # FIXME: We should not be depending on a form parameter that someone
4654: # editing lonsearchcat.pm might change in the future.
4655: if ($env{'form.phase'} eq 'course_search') {
4656: $what.= ':POST';
4657: # FIXME: Probably ought to escape things....
4658: foreach my $element ('courseexp','crsfulltext','crsrelated',
4659: 'crsdiscuss') {
4660: $what.=':'.$element.'='.$env{'form.'.$element};
4661: }
4662: }
4663: }
4664: &courselog($what);
4665: }
4666:
4667: sub countacc {
4668: my $url=&declutter(shift);
4669: return if (! defined($url) || $url eq '');
4670: unless ($env{'request.course.id'}) { return ''; }
4671: #
4672: # Mark that this url was used in this course
4673: #
4674: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
4675: #
4676: # Increase the access count for this resource in this child process
4677: #
4678: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
4679: $accesshash{$key}++;
4680: }
4681:
4682: sub linklog {
4683: my ($from,$to)=@_;
4684: $from=&declutter($from);
4685: $to=&declutter($to);
4686: $accesshash{$from.'___'.$to.'___comefrom'}=1;
4687: $accesshash{$to.'___'.$from.'___goto'}=1;
4688: }
4689:
4690: sub statslog {
4691: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
4692: if ($users<2) { return; }
4693: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
4694: 'course' => $env{'request.course.id'},
4695: 'sections' => '"all"',
4696: 'num_students' => $users,
4697: 'part' => $part,
4698: 'symb' => $symb,
4699: 'mean_tries' => $av_attempts,
4700: 'deg_of_diff' => $degdiff});
4701: foreach my $key (keys(%dynstore)) {
4702: $accesshash{$key}=$dynstore{$key};
4703: }
4704: }
4705:
4706: sub userrolelog {
4707: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
4708: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
4709: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4710: $userrolehash
4711: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4712: =$tend.':'.$tstart;
4713: }
4714: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
4715: $userrolehash
4716: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
4717: =$tend.':'.$tstart;
4718: }
4719: if ($trole =~ /^(dc|ad|li|au|dg|sc|dh|da)/ ) {
4720: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
4721: $domainrolehash
4722: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
4723: = $tend.':'.$tstart;
4724: }
4725: }
4726:
4727: sub courserolelog {
4728: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
4729: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
4730: my $cdom = $1;
4731: my $cnum = $2;
4732: my $sec = $3;
4733: my $namespace = 'rolelog';
4734: my %storehash = (
4735: role => $trole,
4736: start => $tstart,
4737: end => $tend,
4738: selfenroll => $selfenroll,
4739: context => $context,
4740: );
4741: if ($trole eq 'gr') {
4742: $namespace = 'groupslog';
4743: $storehash{'group'} = $sec;
4744: } else {
4745: $storehash{'section'} = $sec;
4746: }
4747: &write_log('course',$namespace,\%storehash,$delflag,$username,
4748: $domain,$cnum,$cdom);
4749: if (($trole ne 'st') || ($sec ne '')) {
4750: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
4751: }
4752: }
4753: return;
4754: }
4755:
4756: sub domainrolelog {
4757: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4758: if ($area =~ m{^/($match_domain)/$}) {
4759: my $cdom = $1;
4760: my $domconfiguser = &Apache::lonnet::get_domainconfiguser($cdom);
4761: my $namespace = 'rolelog';
4762: my %storehash = (
4763: role => $trole,
4764: start => $tstart,
4765: end => $tend,
4766: context => $context,
4767: );
4768: &write_log('domain',$namespace,\%storehash,$delflag,$username,
4769: $domain,$domconfiguser,$cdom);
4770: }
4771: return;
4772:
4773: }
4774:
4775: sub coauthorrolelog {
4776: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$context)=@_;
4777: if ($area =~ m{^/($match_domain)/($match_username)$}) {
4778: my $audom = $1;
4779: my $auname = $2;
4780: my $namespace = 'rolelog';
4781: my %storehash = (
4782: role => $trole,
4783: start => $tstart,
4784: end => $tend,
4785: context => $context,
4786: );
4787: &write_log('author',$namespace,\%storehash,$delflag,$username,
4788: $domain,$auname,$audom);
4789: }
4790: return;
4791: }
4792:
4793: sub get_course_adv_roles {
4794: my ($cid,$codes) = @_;
4795: $cid=$env{'request.course.id'} unless (defined($cid));
4796: my %coursehash=&coursedescription($cid);
4797: my $crstype = &Apache::loncommon::course_type($cid);
4798: my %nothide=();
4799: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4800: if ($user !~ /:/) {
4801: $nothide{join(':',split(/[\@]/,$user))}=1;
4802: } else {
4803: $nothide{$user}=1;
4804: }
4805: }
4806: my @possdoms = ($coursehash{'domain'});
4807: if ($coursehash{'checkforpriv'}) {
4808: push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
4809: }
4810: my %returnhash=();
4811: my %dumphash=
4812: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
4813: my $now=time;
4814: my %privileged;
4815: foreach my $entry (keys(%dumphash)) {
4816: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4817: if (($tstart) && ($tstart<0)) { next; }
4818: if (($tend) && ($tend<$now)) { next; }
4819: if (($tstart) && ($now<$tstart)) { next; }
4820: my ($role,$username,$domain,$section)=split(/\:/,$entry);
4821: if ($username eq '' || $domain eq '') { next; }
4822: if ((&privileged($username,$domain,\@possdoms)) &&
4823: (!$nothide{$username.':'.$domain})) { next; }
4824: if ($role eq 'cr') { next; }
4825: if ($codes) {
4826: if ($section) { $role .= ':'.$section; }
4827: if ($returnhash{$role}) {
4828: $returnhash{$role}.=','.$username.':'.$domain;
4829: } else {
4830: $returnhash{$role}=$username.':'.$domain;
4831: }
4832: } else {
4833: my $key=&plaintext($role,$crstype);
4834: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
4835: if ($returnhash{$key}) {
4836: $returnhash{$key}.=','.$username.':'.$domain;
4837: } else {
4838: $returnhash{$key}=$username.':'.$domain;
4839: }
4840: }
4841: }
4842: return %returnhash;
4843: }
4844:
4845: sub get_my_roles {
4846: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
4847: unless (defined($uname)) { $uname=$env{'user.name'}; }
4848: unless (defined($udom)) { $udom=$env{'user.domain'}; }
4849: my (%dumphash,%nothide);
4850: if ($context eq 'userroles') {
4851: %dumphash = &dump('roles',$udom,$uname);
4852: } else {
4853: %dumphash = &dump('nohist_userroles',$udom,$uname);
4854: if ($hidepriv) {
4855: my %coursehash=&coursedescription($udom.'_'.$uname);
4856: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
4857: if ($user !~ /:/) {
4858: $nothide{join(':',split(/[\@]/,$user))} = 1;
4859: } else {
4860: $nothide{$user} = 1;
4861: }
4862: }
4863: }
4864: }
4865: my %returnhash=();
4866: my $now=time;
4867: my %privileged;
4868: foreach my $entry (keys(%dumphash)) {
4869: my ($role,$tend,$tstart);
4870: if ($context eq 'userroles') {
4871: next if ($entry =~ /^rolesdef/);
4872: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
4873: } else {
4874: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
4875: }
4876: if (($tstart) && ($tstart<0)) { next; }
4877: my $status = 'active';
4878: if (($tend) && ($tend<=$now)) {
4879: $status = 'previous';
4880: }
4881: if (($tstart) && ($now<$tstart)) {
4882: $status = 'future';
4883: }
4884: if (ref($types) eq 'ARRAY') {
4885: if (!grep(/^\Q$status\E$/,@{$types})) {
4886: next;
4887: }
4888: } else {
4889: if ($status ne 'active') {
4890: next;
4891: }
4892: }
4893: my ($rolecode,$username,$domain,$section,$area);
4894: if ($context eq 'userroles') {
4895: ($area,$rolecode) = ($entry =~ /^(.+)_([^_]+)$/);
4896: (undef,$domain,$username,$section) = split(/\//,$area);
4897: } else {
4898: ($role,$username,$domain,$section) = split(/\:/,$entry);
4899: }
4900: if (ref($roledoms) eq 'ARRAY') {
4901: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
4902: next;
4903: }
4904: }
4905: if (ref($roles) eq 'ARRAY') {
4906: if (!grep(/^\Q$role\E$/,@{$roles})) {
4907: if ($role =~ /^cr\//) {
4908: if (!grep(/^cr$/,@{$roles})) {
4909: next;
4910: }
4911: } elsif ($role =~ /^gr\//) {
4912: if (!grep(/^gr$/,@{$roles})) {
4913: next;
4914: }
4915: } else {
4916: next;
4917: }
4918: }
4919: }
4920: if ($hidepriv) {
4921: my @privroles = ('dc','su');
4922: if ($context eq 'userroles') {
4923: next if (grep(/^\Q$role\E$/,@privroles));
4924: } else {
4925: my $possdoms = [$domain];
4926: if (ref($roledoms) eq 'ARRAY') {
4927: push(@{$possdoms},@{$roledoms});
4928: }
4929: if (&privileged($username,$domain,$possdoms,\@privroles)) {
4930: if (!$nothide{$username.':'.$domain}) {
4931: next;
4932: }
4933: }
4934: }
4935: }
4936: if ($withsec) {
4937: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
4938: $tstart.':'.$tend;
4939: } else {
4940: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
4941: }
4942: }
4943: return %returnhash;
4944: }
4945:
4946: sub get_all_adhocroles {
4947: my ($dom) = @_;
4948: my @roles_by_num = ();
4949: my %domdefaults = &get_domain_defaults($dom);
4950: my (%description,%access_in_dom,%access_info);
4951: if (ref($domdefaults{'adhocroles'}) eq 'HASH') {
4952: my $count = 0;
4953: my %domcurrent = %{$domdefaults{'adhocroles'}};
4954: my %ordered;
4955: foreach my $role (sort(keys(%domcurrent))) {
4956: my ($order,$desc,$access_in_dom);
4957: if (ref($domcurrent{$role}) eq 'HASH') {
4958: $order = $domcurrent{$role}{'order'};
4959: $desc = $domcurrent{$role}{'desc'};
4960: $access_in_dom{$role} = $domcurrent{$role}{'access'};
4961: $access_info{$role} = $domcurrent{$role}{$access_in_dom{$role}};
4962: }
4963: if ($order eq '') {
4964: $order = $count;
4965: }
4966: $ordered{$order} = $role;
4967: if ($desc ne '') {
4968: $description{$role} = $desc;
4969: } else {
4970: $description{$role}= $role;
4971: }
4972: $count++;
4973: }
4974: foreach my $item (sort {$a <=> $b } (keys(%ordered))) {
4975: push(@roles_by_num,$ordered{$item});
4976: }
4977: }
4978: return (\@roles_by_num,\%description,\%access_in_dom,\%access_info);
4979: }
4980:
4981: sub get_my_adhocroles {
4982: my ($cid,$checkreg) = @_;
4983: my ($cdom,$cnum,%info,@possroles,$description,$roles_by_num);
4984: if ($env{'request.course.id'} eq $cid) {
4985: $cdom = $env{'course.'.$cid.'.domain'};
4986: $cnum = $env{'course.'.$cid.'.num'};
4987: $info{'internal.coursecode'} = $env{'course.'.$cid.'.internal.coursecode'};
4988: } elsif ($cid =~ /^($match_domain)_($match_courseid)$/) {
4989: $cdom = $1;
4990: $cnum = $2;
4991: %info = &Apache::lonnet::get('environment',['internal.coursecode'],
4992: $cdom,$cnum);
4993: }
4994: if (($info{'internal.coursecode'} ne '') && ($checkreg)) {
4995: my $user = $env{'user.name'}.':'.$env{'user.domain'};
4996: my %rosterhash = &get('classlist',[$user],$cdom,$cnum);
4997: if ($rosterhash{$user} ne '') {
4998: my $type = (split(/:/,$rosterhash{$user}))[5];
4999: return ([],{}) if ($type eq 'auto');
5000: }
5001: }
5002: if (($cdom ne '') && ($cnum ne '')) {
5003: if (($env{"user.role.dh./$cdom/"}) || ($env{"user.role.da./$cdom/"})) {
5004: my $then=$env{'user.login.time'};
5005: my $update=$env{'user.update.time'};
5006: if (!$update) {
5007: $update = $then;
5008: }
5009: my @liveroles;
5010: foreach my $role ('dh','da') {
5011: if ($env{"user.role.$role./$cdom/"}) {
5012: my ($tstart,$tend)=split(/\./,$env{"user.role.$role./$cdom/"});
5013: my $limit = $update;
5014: if ($env{'request.role'} eq "$role./$cdom/") {
5015: $limit = $then;
5016: }
5017: my $activerole = 1;
5018: if ($tstart && $tstart>$limit) { $activerole = 0; }
5019: if ($tend && $tend <$limit) { $activerole = 0; }
5020: if ($activerole) {
5021: push(@liveroles,$role);
5022: }
5023: }
5024: }
5025: if (@liveroles) {
5026: if (&homeserver($cnum,$cdom) ne 'no_host') {
5027: my ($accessref,$accessinfo,%access_in_dom);
5028: ($roles_by_num,$description,$accessref,$accessinfo) = &get_all_adhocroles($cdom);
5029: if (ref($roles_by_num) eq 'ARRAY') {
5030: if (@{$roles_by_num}) {
5031: my %settings;
5032: if ($env{'request.course.id'} eq $cid) {
5033: foreach my $envkey (keys(%env)) {
5034: if ($envkey =~ /^\Qcourse.$cid.\E(internal\.adhoc.+)$/) {
5035: $settings{$1} = $env{$envkey};
5036: }
5037: }
5038: } else {
5039: %settings = &dump('environment',$cdom,$cnum,'internal\.adhoc');
5040: }
5041: my %setincrs;
5042: if ($settings{'internal.adhocaccess'}) {
5043: map { $setincrs{$_} = 1; } split(/,/,$settings{'internal.adhocaccess'});
5044: }
5045: my @statuses;
5046: if ($env{'environment.inststatus'}) {
5047: @statuses = split(/,/,$env{'environment.inststatus'});
5048: }
5049: my $user = $env{'user.name'}.':'.$env{'user.domain'};
5050: if (ref($accessref) eq 'HASH') {
5051: %access_in_dom = %{$accessref};
5052: }
5053: foreach my $role (@{$roles_by_num}) {
5054: my ($curraccess,@okstatus,@personnel);
5055: if ($setincrs{$role}) {
5056: ($curraccess,my $rest) = split(/=/,$settings{'internal.adhoc.'.$role});
5057: if ($curraccess eq 'status') {
5058: @okstatus = split(/\&/,$rest);
5059: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5060: @personnel = split(/\&/,$rest);
5061: }
5062: } else {
5063: $curraccess = $access_in_dom{$role};
5064: if (ref($accessinfo) eq 'HASH') {
5065: if ($curraccess eq 'status') {
5066: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5067: @okstatus = @{$accessinfo->{$role}};
5068: }
5069: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5070: if (ref($accessinfo->{$role}) eq 'ARRAY') {
5071: @personnel = @{$accessinfo->{$role}};
5072: }
5073: }
5074: }
5075: }
5076: if ($curraccess eq 'none') {
5077: next;
5078: } elsif ($curraccess eq 'all') {
5079: push(@possroles,$role);
5080: } elsif ($curraccess eq 'dh') {
5081: if (grep(/^dh$/,@liveroles)) {
5082: push(@possroles,$role);
5083: } else {
5084: next;
5085: }
5086: } elsif ($curraccess eq 'da') {
5087: if (grep(/^da$/,@liveroles)) {
5088: push(@possroles,$role);
5089: } else {
5090: next;
5091: }
5092: } elsif ($curraccess eq 'status') {
5093: if (@okstatus) {
5094: if (!@statuses) {
5095: if (grep(/^default$/,@okstatus)) {
5096: push(@possroles,$role);
5097: }
5098: } else {
5099: foreach my $status (@okstatus) {
5100: if (grep(/^\Q$status\E$/,@statuses)) {
5101: push(@possroles,$role);
5102: last;
5103: }
5104: }
5105: }
5106: }
5107: } elsif (($curraccess eq 'exc') || ($curraccess eq 'inc')) {
5108: if (grep(/^\Q$user\E$/,@personnel)) {
5109: if ($curraccess eq 'exc') {
5110: push(@possroles,$role);
5111: }
5112: } elsif ($curraccess eq 'inc') {
5113: push(@possroles,$role);
5114: }
5115: }
5116: }
5117: }
5118: }
5119: }
5120: }
5121: }
5122: }
5123: unless (ref($description) eq 'HASH') {
5124: if (ref($roles_by_num) eq 'ARRAY') {
5125: my %desc;
5126: map { $desc{$_} = $_; } (@{$roles_by_num});
5127: $description = \%desc;
5128: } else {
5129: $description = {};
5130: }
5131: }
5132: return (\@possroles,$description);
5133: }
5134:
5135: # ----------------------------------------------------- Frontpage Announcements
5136: #
5137: #
5138:
5139: sub postannounce {
5140: my ($server,$text)=@_;
5141: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
5142: unless ($text=~/\w/) { $text=''; }
5143: return &reply('setannounce:'.&escape($text),$server);
5144: }
5145:
5146: sub getannounce {
5147:
5148: if (open(my $fh,"<",$perlvar{'lonDocRoot'}.'/announcement.txt')) {
5149: my $announcement='';
5150: while (my $line = <$fh>) { $announcement .= $line; }
5151: close($fh);
5152: if ($announcement=~/\w/) {
5153: return
5154: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
5155: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
5156: } else {
5157: return '';
5158: }
5159: } else {
5160: return '';
5161: }
5162: }
5163:
5164: # ---------------------------------------------------------- Course ID routines
5165: # Deal with domain's nohist_courseid.db files
5166: #
5167:
5168: sub courseidput {
5169: my ($domain,$storehash,$coursehome,$caller) = @_;
5170: return unless (ref($storehash) eq 'HASH');
5171: my $outcome;
5172: if ($caller eq 'timeonly') {
5173: my $cids = '';
5174: foreach my $item (keys(%$storehash)) {
5175: $cids.=&escape($item).'&';
5176: }
5177: $cids=~s/\&$//;
5178: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
5179: $coursehome);
5180: } else {
5181: my $items = '';
5182: foreach my $item (keys(%$storehash)) {
5183: $items.= &escape($item).'='.
5184: &freeze_escape($$storehash{$item}).'&';
5185: }
5186: $items=~s/\&$//;
5187: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
5188: $coursehome);
5189: }
5190: if ($outcome eq 'unknown_cmd') {
5191: my $what;
5192: foreach my $cid (keys(%$storehash)) {
5193: $what .= &escape($cid).'=';
5194: foreach my $item ('description','inst_code','owner','type') {
5195: $what .= &escape($storehash->{$cid}{$item}).':';
5196: }
5197: $what =~ s/\:$/&/;
5198: }
5199: $what =~ s/\&$//;
5200: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
5201: } else {
5202: return $outcome;
5203: }
5204: }
5205:
5206: sub courseiddump {
5207: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
5208: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
5209: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
5210: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner,
5211: $hasuniquecode,$reqcrsdom,$reqinstcode)=@_;
5212: my $as_hash = 1;
5213: my %returnhash;
5214: if (!$domfilter) { $domfilter=''; }
5215: my %libserv = &all_library();
5216: foreach my $tryserver (keys(%libserv)) {
5217: if ( ( $hostidflag == 1
5218: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
5219: || (!defined($hostidflag)) ) {
5220:
5221: if (($domfilter eq '') ||
5222: (&host_domain($tryserver) eq $domfilter)) {
5223: my $rep;
5224: if (grep { $_ eq $tryserver } ¤t_machine_ids()) {
5225: $rep = &LONCAPA::Lond::dump_course_id_handler(
5226: join(":", (&host_domain($tryserver), $sincefilter,
5227: &escape($descfilter), &escape($instcodefilter),
5228: &escape($ownerfilter), &escape($coursefilter),
5229: &escape($typefilter), &escape($regexp_ok),
5230: $as_hash, &escape($selfenrollonly),
5231: &escape($catfilter), $showhidden, $caller,
5232: &escape($cloner), &escape($cc_clone), $cloneonly,
5233: &escape($createdbefore), &escape($createdafter),
5234: &escape($creationcontext),$domcloner,$hasuniquecode,
5235: $reqcrsdom,&escape($reqinstcode))));
5236: } else {
5237: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
5238: $sincefilter.':'.&escape($descfilter).':'.
5239: &escape($instcodefilter).':'.&escape($ownerfilter).
5240: ':'.&escape($coursefilter).':'.&escape($typefilter).
5241: ':'.&escape($regexp_ok).':'.$as_hash.':'.
5242: &escape($selfenrollonly).':'.&escape($catfilter).':'.
5243: $showhidden.':'.$caller.':'.&escape($cloner).':'.
5244: &escape($cc_clone).':'.$cloneonly.':'.
5245: &escape($createdbefore).':'.&escape($createdafter).':'.
5246: &escape($creationcontext).':'.$domcloner.':'.$hasuniquecode.
5247: ':'.$reqcrsdom.':'.&escape($reqinstcode),$tryserver);
5248: }
5249:
5250: my @pairs=split(/\&/,$rep);
5251: foreach my $item (@pairs) {
5252: my ($key,$value)=split(/\=/,$item,2);
5253: $key = &unescape($key);
5254: next if ($key =~ /^error: 2 /);
5255: my $result = &thaw_unescape($value);
5256: if (ref($result) eq 'HASH') {
5257: $returnhash{$key}=$result;
5258: } else {
5259: my @responses = split(/:/,$value);
5260: my @items = ('description','inst_code','owner','type');
5261: for (my $i=0; $i<@responses; $i++) {
5262: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
5263: }
5264: }
5265: }
5266: }
5267: }
5268: }
5269: return %returnhash;
5270: }
5271:
5272: sub courselastaccess {
5273: my ($cdom,$cnum,$hostidref) = @_;
5274: my %returnhash;
5275: if ($cdom && $cnum) {
5276: my $chome = &homeserver($cnum,$cdom);
5277: if ($chome ne 'no_host') {
5278: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
5279: &extract_lastaccess(\%returnhash,$rep);
5280: }
5281: } else {
5282: if (!$cdom) { $cdom=''; }
5283: my %libserv = &all_library();
5284: foreach my $tryserver (keys(%libserv)) {
5285: if (ref($hostidref) eq 'ARRAY') {
5286: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
5287: }
5288: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
5289: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
5290: &extract_lastaccess(\%returnhash,$rep);
5291: }
5292: }
5293: }
5294: return %returnhash;
5295: }
5296:
5297: sub extract_lastaccess {
5298: my ($returnhash,$rep) = @_;
5299: if (ref($returnhash) eq 'HASH') {
5300: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
5301: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
5302: $rep eq '') {
5303: my @pairs=split(/\&/,$rep);
5304: foreach my $item (@pairs) {
5305: my ($key,$value)=split(/\=/,$item,2);
5306: $key = &unescape($key);
5307: next if ($key =~ /^error: 2 /);
5308: $returnhash->{$key} = &thaw_unescape($value);
5309: }
5310: }
5311: }
5312: return;
5313: }
5314:
5315: # ---------------------------------------------------------- DC e-mail
5316:
5317: sub dcmailput {
5318: my ($domain,$msgid,$message,$server)=@_;
5319: my $status = &Apache::lonnet::critical(
5320: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
5321: &escape($message),$server);
5322: return $status;
5323: }
5324:
5325: sub dcmaildump {
5326: my ($dom,$startdate,$enddate,$senders) = @_;
5327: my %returnhash=();
5328:
5329: if (defined(&domain($dom,'primary'))) {
5330: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
5331: &escape($enddate).':';
5332: my @esc_senders=map { &escape($_)} @$senders;
5333: $cmd.=&escape(join('&',@esc_senders));
5334: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
5335: my ($key,$value) = split(/\=/,$line,2);
5336: if (($key) && ($value)) {
5337: $returnhash{&unescape($key)} = &unescape($value);
5338: }
5339: }
5340: }
5341: return %returnhash;
5342: }
5343: # ---------------------------------------------------------- Domain roles
5344:
5345: sub get_domain_roles {
5346: my ($dom,$roles,$startdate,$enddate)=@_;
5347: if ((!defined($startdate)) || ($startdate eq '')) {
5348: $startdate = '.';
5349: }
5350: if ((!defined($enddate)) || ($enddate eq '')) {
5351: $enddate = '.';
5352: }
5353: my $rolelist;
5354: if (ref($roles) eq 'ARRAY') {
5355: $rolelist = join('&',@{$roles});
5356: }
5357: my %personnel = ();
5358:
5359: my %servers = &get_servers($dom,'library');
5360: foreach my $tryserver (keys(%servers)) {
5361: %{$personnel{$tryserver}}=();
5362: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
5363: &escape($startdate).':'.
5364: &escape($enddate).':'.
5365: &escape($rolelist), $tryserver))) {
5366: my ($key,$value) = split(/\=/,$line,2);
5367: if (($key) && ($value)) {
5368: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
5369: }
5370: }
5371: }
5372: return %personnel;
5373: }
5374:
5375: sub get_active_domroles {
5376: my ($dom,$roles) = @_;
5377: return () unless (ref($roles) eq 'ARRAY');
5378: my $now = time;
5379: my %dompersonnel = &get_domain_roles($dom,$roles,$now,$now);
5380: my %domroles;
5381: foreach my $server (keys(%dompersonnel)) {
5382: foreach my $user (sort(keys(%{$dompersonnel{$server}}))) {
5383: my ($trole,$uname,$udom,$runame,$rudom,$rsec) = split(/:/,$user);
5384: $domroles{$uname.':'.$udom} = $dompersonnel{$server}{$user};
5385: }
5386: }
5387: return %domroles;
5388: }
5389:
5390: # ----------------------------------------------------------- Interval timing
5391:
5392: {
5393: # Caches needed for speedup of navmaps
5394: # We don't want to cache this for very long at all (5 seconds at most)
5395: #
5396: # The user for whom we cache
5397: my $cachedkey='';
5398: # The cached times for this user
5399: my %cachedtimes=();
5400: # When this was last done
5401: my $cachedtime='';
5402:
5403: sub load_all_first_access {
5404: my ($uname,$udom)=@_;
5405: if (($cachedkey eq $uname.':'.$udom) &&
5406: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
5407: return;
5408: }
5409: $cachedtime=time;
5410: $cachedkey=$uname.':'.$udom;
5411: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
5412: }
5413:
5414: sub get_first_access {
5415: my ($type,$argsymb,$argmap)=@_;
5416: my ($symb,$courseid,$udom,$uname)=&whichuser();
5417: if ($argsymb) { $symb=$argsymb; }
5418: my ($map,$id,$res)=&decode_symb($symb);
5419: if ($argmap) { $map = $argmap; }
5420: if ($type eq 'course') {
5421: $res='course';
5422: } elsif ($type eq 'map') {
5423: $res=&symbread($map);
5424: } else {
5425: $res=$symb;
5426: }
5427: &load_all_first_access($uname,$udom);
5428: return $cachedtimes{"$courseid\0$res"};
5429: }
5430:
5431: sub set_first_access {
5432: my ($type,$interval)=@_;
5433: my ($symb,$courseid,$udom,$uname)=&whichuser();
5434: my ($map,$id,$res)=&decode_symb($symb);
5435: if ($type eq 'course') {
5436: $res='course';
5437: } elsif ($type eq 'map') {
5438: $res=&symbread($map);
5439: } else {
5440: $res=$symb;
5441: }
5442: $cachedkey='';
5443: my $firstaccess=&get_first_access($type,$symb,$map);
5444: if ($firstaccess) {
5445: &logthis("First access time already set ($firstaccess) when attempting ".
5446: "to set new value (type: $type, extent: $res) for $uname:$udom ".
5447: "in $courseid");
5448: return 'already_set';
5449: } else {
5450: my $start = time;
5451: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
5452: $udom,$uname);
5453: if ($putres eq 'ok') {
5454: &put('timerinterval',{"$courseid\0$res"=>$interval},
5455: $udom,$uname);
5456: &appenv(
5457: {
5458: 'course.'.$courseid.'.firstaccess.'.$res => $start,
5459: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
5460: }
5461: );
5462: if (($cachedtime) && (abs($start-$cachedtime) < 5)) {
5463: $cachedtimes{"$courseid\0$res"} = $start;
5464: }
5465: } elsif ($putres ne 'refused') {
5466: &logthis("Result: $putres when attempting to set first access time ".
5467: "(type: $type, extent: $res) for $uname:$udom in $courseid");
5468: }
5469: return $putres;
5470: }
5471: return 'already_set';
5472: }
5473: }
5474:
5475: sub checkout {
5476: my ($symb,$tuname,$tudom,$tcrsid)=@_;
5477: my $now=time;
5478: my $lonhost=$perlvar{'lonHostID'};
5479: my $infostr=&escape(
5480: 'CHECKOUTTOKEN&'.
5481: $tuname.'&'.
5482: $tudom.'&'.
5483: $tcrsid.'&'.
5484: $symb.'&'.
5485: $now.'&'.$ENV{'REMOTE_ADDR'});
5486: my $token=&reply('tmpput:'.$infostr,$lonhost);
5487: if ($token=~/^error\:/) {
5488: &logthis("<font color=\"blue\">WARNING: ".
5489: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
5490: "</font>");
5491: return '';
5492: }
5493:
5494: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
5495: $token=~tr/a-z/A-Z/;
5496:
5497: my %infohash=('resource.0.outtoken' => $token,
5498: 'resource.0.checkouttime' => $now,
5499: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
5500:
5501: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5502: return '';
5503: } else {
5504: &logthis("<font color=\"blue\">WARNING: ".
5505: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
5506: "</font>");
5507: }
5508:
5509: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5510: &escape('Checkout '.$infostr.' - '.
5511: $token)) ne 'ok') {
5512: return '';
5513: } else {
5514: &logthis("<font color=\"blue\">WARNING: ".
5515: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
5516: "</font>");
5517: }
5518: return $token;
5519: }
5520:
5521: # ------------------------------------------------------------ Check in an item
5522:
5523: sub checkin {
5524: my $token=shift;
5525: my $now=time;
5526: my ($ta,$tb,$lonhost)=split(/\*/,$token);
5527: $lonhost=~tr/A-Z/a-z/;
5528: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
5529: $dtoken=~s/\W/\_/g;
5530: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
5531: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
5532:
5533: unless (($tuname) && ($tudom)) {
5534: &logthis('Check in '.$token.' ('.$dtoken.') failed');
5535: return '';
5536: }
5537:
5538: unless (&allowed('mgr',$tcrsid)) {
5539: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
5540: $env{'user.name'}.' - '.$env{'user.domain'});
5541: return '';
5542: }
5543:
5544: my %infohash=('resource.0.intoken' => $token,
5545: 'resource.0.checkintime' => $now,
5546: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
5547:
5548: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
5549: return '';
5550: }
5551:
5552: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
5553: &escape('Checkin - '.$token)) ne 'ok') {
5554: return '';
5555: }
5556:
5557: return ($symb,$tuname,$tudom,$tcrsid);
5558: }
5559:
5560: # --------------------------------------------- Set Expire Date for Spreadsheet
5561:
5562: sub expirespread {
5563: my ($uname,$udom,$stype,$usymb)=@_;
5564: my $cid=$env{'request.course.id'};
5565: if ($cid) {
5566: my $now=time;
5567: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
5568: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
5569: $env{'course.'.$cid.'.num'}.
5570: ':nohist_expirationdates:'.
5571: &escape($key).'='.$now,
5572: $env{'course.'.$cid.'.home'})
5573: }
5574: return 'ok';
5575: }
5576:
5577: # ----------------------------------------------------- Devalidate Spreadsheets
5578:
5579: sub devalidate {
5580: my ($symb,$uname,$udom)=@_;
5581: my $cid=$env{'request.course.id'};
5582: if ($cid) {
5583: # delete the stored spreadsheets for
5584: # - the student level sheet of this user in course's homespace
5585: # - the assessment level sheet for this resource
5586: # for this user in user's homespace
5587: # - current conditional state info
5588: my $key=$uname.':'.$udom.':';
5589: my $status=
5590: &del('nohist_calculatedsheets',
5591: [$key.'studentcalc:'],
5592: $env{'course.'.$cid.'.domain'},
5593: $env{'course.'.$cid.'.num'})
5594: .' '.
5595: &del('nohist_calculatedsheets_'.$cid,
5596: [$key.'assesscalc:'.$symb],$udom,$uname);
5597: unless ($status eq 'ok ok') {
5598: &logthis('Could not devalidate spreadsheet '.
5599: $uname.' at '.$udom.' for '.
5600: $symb.': '.$status);
5601: }
5602: &delenv('user.state.'.$cid);
5603: }
5604: }
5605:
5606: sub get_scalar {
5607: my ($string,$end) = @_;
5608: my $value;
5609: if ($$string =~ s/^([^&]*?)($end)/$2/) {
5610: $value = $1;
5611: } elsif ($$string =~ s/^([^&]*?)&//) {
5612: $value = $1;
5613: }
5614: return &unescape($value);
5615: }
5616:
5617: sub array2str {
5618: my (@array) = @_;
5619: my $result=&arrayref2str(\@array);
5620: $result=~s/^__ARRAY_REF__//;
5621: $result=~s/__END_ARRAY_REF__$//;
5622: return $result;
5623: }
5624:
5625: sub arrayref2str {
5626: my ($arrayref) = @_;
5627: my $result='__ARRAY_REF__';
5628: foreach my $elem (@$arrayref) {
5629: if(ref($elem) eq 'ARRAY') {
5630: $result.=&arrayref2str($elem).'&';
5631: } elsif(ref($elem) eq 'HASH') {
5632: $result.=&hashref2str($elem).'&';
5633: } elsif(ref($elem)) {
5634: #print("Got a ref of ".(ref($elem))." skipping.");
5635: } else {
5636: $result.=&escape($elem).'&';
5637: }
5638: }
5639: $result=~s/\&$//;
5640: $result .= '__END_ARRAY_REF__';
5641: return $result;
5642: }
5643:
5644: sub hash2str {
5645: my (%hash) = @_;
5646: my $result=&hashref2str(\%hash);
5647: $result=~s/^__HASH_REF__//;
5648: $result=~s/__END_HASH_REF__$//;
5649: return $result;
5650: }
5651:
5652: sub hashref2str {
5653: my ($hashref)=@_;
5654: my $result='__HASH_REF__';
5655: foreach my $key (sort(keys(%$hashref))) {
5656: if (ref($key) eq 'ARRAY') {
5657: $result.=&arrayref2str($key).'=';
5658: } elsif (ref($key) eq 'HASH') {
5659: $result.=&hashref2str($key).'=';
5660: } elsif (ref($key)) {
5661: $result.='=';
5662: #print("Got a ref of ".(ref($key))." skipping.");
5663: } else {
5664: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
5665: }
5666:
5667: if(ref($hashref->{$key}) eq 'ARRAY') {
5668: $result.=&arrayref2str($hashref->{$key}).'&';
5669: } elsif(ref($hashref->{$key}) eq 'HASH') {
5670: $result.=&hashref2str($hashref->{$key}).'&';
5671: } elsif(ref($hashref->{$key})) {
5672: $result.='&';
5673: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
5674: } else {
5675: $result.=&escape($hashref->{$key}).'&';
5676: }
5677: }
5678: $result=~s/\&$//;
5679: $result .= '__END_HASH_REF__';
5680: return $result;
5681: }
5682:
5683: sub str2hash {
5684: my ($string)=@_;
5685: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
5686: return %$hash;
5687: }
5688:
5689: sub str2hashref {
5690: my ($string) = @_;
5691:
5692: my %hash;
5693:
5694: if($string !~ /^__HASH_REF__/) {
5695: if (! ($string eq '' || !defined($string))) {
5696: $hash{'error'}='Not hash reference';
5697: }
5698: return (\%hash, $string);
5699: }
5700:
5701: $string =~ s/^__HASH_REF__//;
5702:
5703: while($string !~ /^__END_HASH_REF__/) {
5704: #key
5705: my $key='';
5706: if($string =~ /^__HASH_REF__/) {
5707: ($key, $string)=&str2hashref($string);
5708: if(defined($key->{'error'})) {
5709: $hash{'error'}='Bad data';
5710: return (\%hash, $string);
5711: }
5712: } elsif($string =~ /^__ARRAY_REF__/) {
5713: ($key, $string)=&str2arrayref($string);
5714: if($key->[0] eq 'Array reference error') {
5715: $hash{'error'}='Bad data';
5716: return (\%hash, $string);
5717: }
5718: } else {
5719: $string =~ s/^(.*?)=//;
5720: $key=&unescape($1);
5721: }
5722: $string =~ s/^=//;
5723:
5724: #value
5725: my $value='';
5726: if($string =~ /^__HASH_REF__/) {
5727: ($value, $string)=&str2hashref($string);
5728: if(defined($value->{'error'})) {
5729: $hash{'error'}='Bad data';
5730: return (\%hash, $string);
5731: }
5732: } elsif($string =~ /^__ARRAY_REF__/) {
5733: ($value, $string)=&str2arrayref($string);
5734: if($value->[0] eq 'Array reference error') {
5735: $hash{'error'}='Bad data';
5736: return (\%hash, $string);
5737: }
5738: } else {
5739: $value=&get_scalar(\$string,'__END_HASH_REF__');
5740: }
5741: $string =~ s/^&//;
5742:
5743: $hash{$key}=$value;
5744: }
5745:
5746: $string =~ s/^__END_HASH_REF__//;
5747:
5748: return (\%hash, $string);
5749: }
5750:
5751: sub str2array {
5752: my ($string)=@_;
5753: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
5754: return @$array;
5755: }
5756:
5757: sub str2arrayref {
5758: my ($string) = @_;
5759: my @array;
5760:
5761: if($string !~ /^__ARRAY_REF__/) {
5762: if (! ($string eq '' || !defined($string))) {
5763: $array[0]='Array reference error';
5764: }
5765: return (\@array, $string);
5766: }
5767:
5768: $string =~ s/^__ARRAY_REF__//;
5769:
5770: while($string !~ /^__END_ARRAY_REF__/) {
5771: my $value='';
5772: if($string =~ /^__HASH_REF__/) {
5773: ($value, $string)=&str2hashref($string);
5774: if(defined($value->{'error'})) {
5775: $array[0] ='Array reference error';
5776: return (\@array, $string);
5777: }
5778: } elsif($string =~ /^__ARRAY_REF__/) {
5779: ($value, $string)=&str2arrayref($string);
5780: if($value->[0] eq 'Array reference error') {
5781: $array[0] ='Array reference error';
5782: return (\@array, $string);
5783: }
5784: } else {
5785: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
5786: }
5787: $string =~ s/^&//;
5788:
5789: push(@array, $value);
5790: }
5791:
5792: $string =~ s/^__END_ARRAY_REF__//;
5793:
5794: return (\@array, $string);
5795: }
5796:
5797: # -------------------------------------------------------------------Temp Store
5798:
5799: sub tmpreset {
5800: my ($symb,$namespace,$domain,$stuname) = @_;
5801: if (!$symb) {
5802: $symb=&symbread();
5803: if (!$symb) { $symb= $env{'request.url'}; }
5804: }
5805: $symb=escape($symb);
5806:
5807: if (!$namespace) { $namespace=$env{'request.state'}; }
5808: $namespace=~s/\//\_/g;
5809: $namespace=~s/\W//g;
5810:
5811: if (!$domain) { $domain=$env{'user.domain'}; }
5812: if (!$stuname) { $stuname=$env{'user.name'}; }
5813: if ($domain eq 'public' && $stuname eq 'public') {
5814: $stuname=$ENV{'REMOTE_ADDR'};
5815: }
5816: my $path=LONCAPA::tempdir();
5817: my %hash;
5818: if (tie(%hash,'GDBM_File',
5819: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5820: &GDBM_WRCREAT(),0640)) {
5821: foreach my $key (keys(%hash)) {
5822: if ($key=~ /:$symb/) {
5823: delete($hash{$key});
5824: }
5825: }
5826: }
5827: }
5828:
5829: sub tmpstore {
5830: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
5831:
5832: if (!$symb) {
5833: $symb=&symbread();
5834: if (!$symb) { $symb= $env{'request.url'}; }
5835: }
5836: $symb=escape($symb);
5837:
5838: if (!$namespace) {
5839: # I don't think we would ever want to store this for a course.
5840: # it seems this will only be used if we don't have a course.
5841: #$namespace=$env{'request.course.id'};
5842: #if (!$namespace) {
5843: $namespace=$env{'request.state'};
5844: #}
5845: }
5846: $namespace=~s/\//\_/g;
5847: $namespace=~s/\W//g;
5848: if (!$domain) { $domain=$env{'user.domain'}; }
5849: if (!$stuname) { $stuname=$env{'user.name'}; }
5850: if ($domain eq 'public' && $stuname eq 'public') {
5851: $stuname=$ENV{'REMOTE_ADDR'};
5852: }
5853: my $now=time;
5854: my %hash;
5855: my $path=LONCAPA::tempdir();
5856: if (tie(%hash,'GDBM_File',
5857: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5858: &GDBM_WRCREAT(),0640)) {
5859: $hash{"version:$symb"}++;
5860: my $version=$hash{"version:$symb"};
5861: my $allkeys='';
5862: foreach my $key (keys(%$storehash)) {
5863: $allkeys.=$key.':';
5864: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
5865: }
5866: $hash{"$version:$symb:timestamp"}=$now;
5867: $allkeys.='timestamp';
5868: $hash{"$version:keys:$symb"}=$allkeys;
5869: if (untie(%hash)) {
5870: return 'ok';
5871: } else {
5872: return "error:$!";
5873: }
5874: } else {
5875: return "error:$!";
5876: }
5877: }
5878:
5879: # -----------------------------------------------------------------Temp Restore
5880:
5881: sub tmprestore {
5882: my ($symb,$namespace,$domain,$stuname) = @_;
5883:
5884: if (!$symb) {
5885: $symb=&symbread();
5886: if (!$symb) { $symb= $env{'request.url'}; }
5887: }
5888: $symb=escape($symb);
5889:
5890: if (!$namespace) { $namespace=$env{'request.state'}; }
5891:
5892: if (!$domain) { $domain=$env{'user.domain'}; }
5893: if (!$stuname) { $stuname=$env{'user.name'}; }
5894: if ($domain eq 'public' && $stuname eq 'public') {
5895: $stuname=$ENV{'REMOTE_ADDR'};
5896: }
5897: my %returnhash;
5898: $namespace=~s/\//\_/g;
5899: $namespace=~s/\W//g;
5900: my %hash;
5901: my $path=LONCAPA::tempdir();
5902: if (tie(%hash,'GDBM_File',
5903: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
5904: &GDBM_READER(),0640)) {
5905: my $version=$hash{"version:$symb"};
5906: $returnhash{'version'}=$version;
5907: my $scope;
5908: for ($scope=1;$scope<=$version;$scope++) {
5909: my $vkeys=$hash{"$scope:keys:$symb"};
5910: my @keys=split(/:/,$vkeys);
5911: my $key;
5912: $returnhash{"$scope:keys"}=$vkeys;
5913: foreach $key (@keys) {
5914: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5915: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
5916: }
5917: }
5918: if (!(untie(%hash))) {
5919: return "error:$!";
5920: }
5921: } else {
5922: return "error:$!";
5923: }
5924: return %returnhash;
5925: }
5926:
5927: # ----------------------------------------------------------------------- Store
5928:
5929: sub store {
5930: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5931: my $home='';
5932:
5933: if ($stuname) { $home=&homeserver($stuname,$domain); }
5934:
5935: $symb=&symbclean($symb);
5936: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5937:
5938: if (!$domain) { $domain=$env{'user.domain'}; }
5939: if (!$stuname) { $stuname=$env{'user.name'}; }
5940:
5941: &devalidate($symb,$stuname,$domain);
5942:
5943: $symb=escape($symb);
5944: if (!$namespace) {
5945: unless ($namespace=$env{'request.course.id'}) {
5946: return '';
5947: }
5948: }
5949: if (!$home) { $home=$env{'user.home'}; }
5950:
5951: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5952: $$storehash{'host'}=$perlvar{'lonHostID'};
5953:
5954: my $namevalue='';
5955: foreach my $key (keys(%$storehash)) {
5956: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5957: }
5958: $namevalue=~s/\&$//;
5959: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
5960: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5961: }
5962:
5963: # -------------------------------------------------------------- Critical Store
5964:
5965: sub cstore {
5966: my ($storehash,$symb,$namespace,$domain,$stuname,$laststore) = @_;
5967: my $home='';
5968:
5969: if ($stuname) { $home=&homeserver($stuname,$domain); }
5970:
5971: $symb=&symbclean($symb);
5972: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
5973:
5974: if (!$domain) { $domain=$env{'user.domain'}; }
5975: if (!$stuname) { $stuname=$env{'user.name'}; }
5976:
5977: &devalidate($symb,$stuname,$domain);
5978:
5979: $symb=escape($symb);
5980: if (!$namespace) {
5981: unless ($namespace=$env{'request.course.id'}) {
5982: return '';
5983: }
5984: }
5985: if (!$home) { $home=$env{'user.home'}; }
5986:
5987: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
5988: $$storehash{'host'}=$perlvar{'lonHostID'};
5989:
5990: my $namevalue='';
5991: foreach my $key (keys(%$storehash)) {
5992: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5993: }
5994: $namevalue=~s/\&$//;
5995: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
5996: return critical
5997: ("store:$domain:$stuname:$namespace:$symb:$namevalue:$laststore","$home");
5998: }
5999:
6000: # --------------------------------------------------------------------- Restore
6001:
6002: sub restore {
6003: my ($symb,$namespace,$domain,$stuname) = @_;
6004: my $home='';
6005:
6006: if ($stuname) { $home=&homeserver($stuname,$domain); }
6007:
6008: if (!$symb) {
6009: return if ($namespace eq 'courserequests');
6010: unless ($symb=escape(&symbread())) { return ''; }
6011: } else {
6012: unless ($namespace eq 'courserequests') {
6013: $symb=&escape(&symbclean($symb));
6014: }
6015: }
6016: if (!$namespace) {
6017: unless ($namespace=$env{'request.course.id'}) {
6018: return '';
6019: }
6020: }
6021: if (!$domain) { $domain=$env{'user.domain'}; }
6022: if (!$stuname) { $stuname=$env{'user.name'}; }
6023: if (!$home) { $home=$env{'user.home'}; }
6024: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
6025:
6026: my %returnhash=();
6027: foreach my $line (split(/\&/,$answer)) {
6028: my ($name,$value)=split(/\=/,$line);
6029: $returnhash{&unescape($name)}=&thaw_unescape($value);
6030: }
6031: my $version;
6032: for ($version=1;$version<=$returnhash{'version'};$version++) {
6033: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
6034: $returnhash{$item}=$returnhash{$version.':'.$item};
6035: }
6036: }
6037: return %returnhash;
6038: }
6039:
6040: # ---------------------------------------------------------- Course Description
6041: #
6042: #
6043:
6044: sub coursedescription {
6045: my ($courseid,$args)=@_;
6046: $courseid=~s/^\///;
6047: $courseid=~s/\_/\//g;
6048: my ($cdomain,$cnum)=split(/\//,$courseid);
6049: my $chome=&homeserver($cnum,$cdomain);
6050: my $normalid=$cdomain.'_'.$cnum;
6051: # need to always cache even if we get errors otherwise we keep
6052: # trying and trying and trying to get the course description.
6053: my %envhash=();
6054: my %returnhash=();
6055:
6056: my $expiretime=600;
6057: if ($env{'request.course.id'} eq $normalid) {
6058: $expiretime=120;
6059: }
6060:
6061: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
6062: if (!$args->{'freshen_cache'}
6063: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
6064: foreach my $key (keys(%env)) {
6065: next if ($key !~ /^\Q$prefix\E(.*)/);
6066: my ($setting) = $1;
6067: $returnhash{$setting} = $env{$key};
6068: }
6069: return %returnhash;
6070: }
6071:
6072: # get the data again
6073:
6074: if (!$args->{'one_time'}) {
6075: $envhash{'course.'.$normalid.'.last_cache'}=time;
6076: }
6077:
6078: if ($chome ne 'no_host') {
6079: %returnhash=&dump('environment',$cdomain,$cnum);
6080: if (!exists($returnhash{'con_lost'})) {
6081: my $username = $env{'user.name'}; # Defult username
6082: if(defined $args->{'user'}) {
6083: $username = $args->{'user'};
6084: }
6085: $returnhash{'home'}= $chome;
6086: $returnhash{'domain'} = $cdomain;
6087: $returnhash{'num'} = $cnum;
6088: if (!defined($returnhash{'type'})) {
6089: $returnhash{'type'} = 'Course';
6090: }
6091: while (my ($name,$value) = each %returnhash) {
6092: $envhash{'course.'.$normalid.'.'.$name}=$value;
6093: }
6094: $returnhash{'url'}=&clutter($returnhash{'url'});
6095: $returnhash{'fn'}=LONCAPA::tempdir() .
6096: $username.'_'.$cdomain.'_'.$cnum;
6097: $envhash{'course.'.$normalid.'.home'}=$chome;
6098: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
6099: $envhash{'course.'.$normalid.'.num'}=$cnum;
6100: }
6101: }
6102: if (!$args->{'one_time'}) {
6103: &appenv(\%envhash);
6104: }
6105: return %returnhash;
6106: }
6107:
6108: sub update_released_required {
6109: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
6110: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
6111: $cid = $env{'request.course.id'};
6112: $cdom = $env{'course.'.$cid.'.domain'};
6113: $cnum = $env{'course.'.$cid.'.num'};
6114: $chome = $env{'course.'.$cid.'.home'};
6115: }
6116: if ($needsrelease) {
6117: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
6118: my $needsupdate;
6119: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
6120: $needsupdate = 1;
6121: } else {
6122: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
6123: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
6124: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
6125: $needsupdate = 1;
6126: }
6127: }
6128: if ($needsupdate) {
6129: my %needshash = (
6130: 'internal.releaserequired' => $needsrelease,
6131: );
6132: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
6133: if ($putresult eq 'ok') {
6134: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
6135: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
6136: if (ref($crsinfo{$cid}) eq 'HASH') {
6137: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
6138: &courseidput($cdom,\%crsinfo,$chome,'notime');
6139: }
6140: }
6141: }
6142: }
6143: return;
6144: }
6145:
6146: # -------------------------------------------------See if a user is privileged
6147:
6148: sub privileged {
6149: my ($username,$domain,$possdomains,$possroles)=@_;
6150: my $now = time;
6151: my $roles;
6152: if (ref($possroles) eq 'ARRAY') {
6153: $roles = $possroles;
6154: } else {
6155: $roles = ['dc','su'];
6156: }
6157: if (ref($possdomains) eq 'ARRAY') {
6158: my %privileged = &privileged_by_domain($possdomains,$roles);
6159: foreach my $dom (@{$possdomains}) {
6160: if (($username =~ /^$match_username$/) && ($domain =~ /^$match_domain$/) &&
6161: (ref($privileged{$dom}) eq 'HASH')) {
6162: foreach my $role (@{$roles}) {
6163: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6164: if (exists($privileged{$dom}{$role}{$username.':'.$domain})) {
6165: my ($end,$start) = split(/:/,$privileged{$dom}{$role}{$username.':'.$domain});
6166: return 1 unless (($end && $end < $now) ||
6167: ($start && $start > $now));
6168: }
6169: }
6170: }
6171: }
6172: }
6173: } else {
6174: my %rolesdump = &dump("roles", $domain, $username) or return 0;
6175: my $now = time;
6176:
6177: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys(%rolesdump)}) {
6178: my ($trole, $tend, $tstart) = split(/_/, $role);
6179: if (grep(/^\Q$trole\E$/,@{$roles})) {
6180: return 1 unless ($tend && $tend < $now)
6181: or ($tstart && $tstart > $now);
6182: }
6183: }
6184: }
6185: return 0;
6186: }
6187:
6188: sub privileged_by_domain {
6189: my ($domains,$roles) = @_;
6190: my %privileged = ();
6191: my $cachetime = 60*60*24;
6192: my $now = time;
6193: unless ((ref($domains) eq 'ARRAY') && (ref($roles) eq 'ARRAY')) {
6194: return %privileged;
6195: }
6196: foreach my $dom (@{$domains}) {
6197: next if (ref($privileged{$dom}) eq 'HASH');
6198: my $needroles;
6199: foreach my $role (@{$roles}) {
6200: my ($result,$cached)=&is_cached_new('priv_'.$role,$dom);
6201: if (defined($cached)) {
6202: if (ref($result) eq 'HASH') {
6203: $privileged{$dom}{$role} = $result;
6204: }
6205: } else {
6206: $needroles = 1;
6207: }
6208: }
6209: if ($needroles) {
6210: my %dompersonnel = &get_domain_roles($dom,$roles);
6211: $privileged{$dom} = {};
6212: foreach my $server (keys(%dompersonnel)) {
6213: if (ref($dompersonnel{$server}) eq 'HASH') {
6214: foreach my $item (keys(%{$dompersonnel{$server}})) {
6215: my ($trole,$uname,$udom,$rest) = split(/:/,$item,4);
6216: my ($end,$start) = split(/:/,$dompersonnel{$server}{$item});
6217: next if ($end && $end < $now);
6218: $privileged{$dom}{$trole}{$uname.':'.$udom} =
6219: $dompersonnel{$server}{$item};
6220: }
6221: }
6222: }
6223: if (ref($privileged{$dom}) eq 'HASH') {
6224: foreach my $role (@{$roles}) {
6225: if (ref($privileged{$dom}{$role}) eq 'HASH') {
6226: &do_cache_new('priv_'.$role,$dom,$privileged{$dom}{$role},$cachetime);
6227: } else {
6228: my %hash = ();
6229: &do_cache_new('priv_'.$role,$dom,\%hash,$cachetime);
6230: }
6231: }
6232: }
6233: }
6234: }
6235: return %privileged;
6236: }
6237:
6238: # -------------------------------------------------------- Get user privileges
6239:
6240: sub rolesinit {
6241: my ($domain, $username) = @_;
6242: my %userroles = ('user.login.time' => time);
6243: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
6244:
6245: # firstaccess and timerinterval are related to timed maps/resources.
6246: # also, blocking can be triggered by an activating timer
6247: # it's saved in the user's %env.
6248: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
6249: my %timerinterval = &dump('timerinterval', $domain, $username);
6250: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
6251: %timerintchk, %timerintenv);
6252:
6253: foreach my $key (keys(%firstaccess)) {
6254: my ($cid, $rest) = split(/\0/, $key);
6255: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
6256: }
6257:
6258: foreach my $key (keys(%timerinterval)) {
6259: my ($cid,$rest) = split(/\0/,$key);
6260: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
6261: }
6262:
6263: my %allroles=();
6264: my %allgroups=();
6265:
6266: for my $area (grep { ! /^rolesdef_/ } keys(%rolesdump)) {
6267: my $role = $rolesdump{$area};
6268: $area =~ s/\_\w\w$//;
6269:
6270: my ($trole, $tend, $tstart, $group_privs);
6271:
6272: if ($role =~ /^cr/) {
6273: # Custom role, defined by a user
6274: # e.g., user.role.cr/msu/smith/mynewrole
6275: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
6276: $trole = $1;
6277: ($tend, $tstart) = split('_', $2);
6278: } else {
6279: $trole = $role;
6280: }
6281: } elsif ($role =~ m|^gr/|) {
6282: # Role of member in a group, defined within a course/community
6283: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
6284: ($trole, $tend, $tstart) = split(/_/, $role);
6285: next if $tstart eq '-1';
6286: ($trole, $group_privs) = split(/\//, $trole);
6287: $group_privs = &unescape($group_privs);
6288: } else {
6289: # Just a normal role, defined in roles.tab
6290: ($trole, $tend, $tstart) = split(/_/,$role);
6291: }
6292:
6293: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
6294: $username);
6295: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
6296:
6297: # role expired or not available yet?
6298: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
6299: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
6300:
6301: next if $area eq '' or $trole eq '';
6302:
6303: my $spec = "$trole.$area";
6304: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
6305:
6306: if ($trole =~ /^cr\//) {
6307: # Custom role, defined by a user
6308: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
6309: } elsif ($trole eq 'gr') {
6310: # Role of a member in a group, defined within a course/community
6311: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
6312: next;
6313: } else {
6314: # Normal role, defined in roles.tab
6315: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
6316: }
6317:
6318: my $cid = $tdomain.'_'.$trest;
6319: unless ($firstaccchk{$cid}) {
6320: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
6321: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
6322: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
6323: $coursetimerstarts{$cid}{$item};
6324: }
6325: }
6326: $firstaccchk{$cid} = 1;
6327: }
6328: unless ($timerintchk{$cid}) {
6329: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
6330: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
6331: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
6332: $coursetimerintervals{$cid}{$item};
6333: }
6334: }
6335: $timerintchk{$cid} = 1;
6336: }
6337: }
6338:
6339: @userroles{'user.author','user.adv','user.rar'} = &set_userprivs(\%userroles,
6340: \%allroles, \%allgroups);
6341: $env{'user.adv'} = $userroles{'user.adv'};
6342: $env{'user.rar'} = $userroles{'user.rar'};
6343:
6344: return (\%userroles,\%firstaccenv,\%timerintenv);
6345: }
6346:
6347: sub set_arearole {
6348: my ($trole,$area,$tstart,$tend,$domain,$username,$nolog) = @_;
6349: unless ($nolog) {
6350: # log the associated role with the area
6351: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
6352: }
6353: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
6354: }
6355:
6356: sub custom_roleprivs {
6357: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
6358: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
6359: my $homsvr = &homeserver($rauthor,$rdomain);
6360: if (&hostname($homsvr) ne '') {
6361: my ($rdummy,$roledef)=
6362: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
6363: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
6364: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
6365: if (defined($syspriv)) {
6366: if ($trest =~ /^$match_community$/) {
6367: $syspriv =~ s/bre\&S//;
6368: }
6369: $$allroles{'cm./'}.=':'.$syspriv;
6370: $$allroles{$spec.'./'}.=':'.$syspriv;
6371: }
6372: if ($tdomain ne '') {
6373: if (defined($dompriv)) {
6374: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
6375: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
6376: }
6377: if (($trest ne '') && (defined($coursepriv))) {
6378: if ($trole =~ m{^cr/$tdomain/$tdomain\Q-domainconfig\E/([^/]+)$}) {
6379: my $rolename = $1;
6380: $coursepriv = &course_adhocrole_privs($rolename,$tdomain,$trest,$coursepriv);
6381: }
6382: $$allroles{'cm.'.$area}.=':'.$coursepriv;
6383: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
6384: }
6385: }
6386: }
6387: }
6388: }
6389:
6390: sub course_adhocrole_privs {
6391: my ($rolename,$cdom,$cnum,$coursepriv) = @_;
6392: my %overrides = &get('environment',["internal.adhocpriv.$rolename"],$cdom,$cnum);
6393: if ($overrides{"internal.adhocpriv.$rolename"}) {
6394: my (%currprivs,%storeprivs);
6395: foreach my $item (split(/:/,$coursepriv)) {
6396: my ($priv,$restrict) = split(/\&/,$item);
6397: $currprivs{$priv} = $restrict;
6398: }
6399: my (%possadd,%possremove,%full);
6400: foreach my $item (split(/\:/,$Apache::lonnet::pr{'cr:c'})) {
6401: my ($priv,$restrict)=split(/\&/,$item);
6402: $full{$priv} = $restrict;
6403: }
6404: foreach my $item (split(/,/,$overrides{"internal.adhocpriv.$rolename"})) {
6405: next if ($item eq '');
6406: my ($rule,$rest) = split(/=/,$item);
6407: next unless (($rule eq 'off') || ($rule eq 'on'));
6408: foreach my $priv (split(/:/,$rest)) {
6409: if ($priv ne '') {
6410: if ($rule eq 'off') {
6411: $possremove{$priv} = 1;
6412: } else {
6413: $possadd{$priv} = 1;
6414: }
6415: }
6416: }
6417: }
6418: foreach my $priv (sort(keys(%full))) {
6419: if (exists($currprivs{$priv})) {
6420: unless (exists($possremove{$priv})) {
6421: $storeprivs{$priv} = $currprivs{$priv};
6422: }
6423: } elsif (exists($possadd{$priv})) {
6424: $storeprivs{$priv} = $full{$priv};
6425: }
6426: }
6427: $coursepriv = ':'.join(':',map { $_.'&'.$storeprivs{$_}; } sort(keys(%storeprivs)));
6428: }
6429: return $coursepriv;
6430: }
6431:
6432: sub group_roleprivs {
6433: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
6434: my $access = 1;
6435: my $now = time;
6436: if (($tend!=0) && ($tend<$now)) { $access = 0; }
6437: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
6438: if ($access) {
6439: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
6440: $$allgroups{$course}{$group} .=':'.$group_privs;
6441: }
6442: }
6443:
6444: sub standard_roleprivs {
6445: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
6446: if (defined($pr{$trole.':s'})) {
6447: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
6448: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
6449: }
6450: if ($tdomain ne '') {
6451: if (defined($pr{$trole.':d'})) {
6452: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6453: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
6454: }
6455: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
6456: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
6457: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
6458: }
6459: }
6460: }
6461:
6462: sub set_userprivs {
6463: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
6464: my $author=0;
6465: my $adv=0;
6466: my $rar=0;
6467: my %grouproles = ();
6468: if (keys(%{$allgroups}) > 0) {
6469: my @groupkeys;
6470: foreach my $role (keys(%{$allroles})) {
6471: push(@groupkeys,$role);
6472: }
6473: if (ref($groups_roles) eq 'HASH') {
6474: foreach my $key (keys(%{$groups_roles})) {
6475: unless (grep(/^\Q$key\E$/,@groupkeys)) {
6476: push(@groupkeys,$key);
6477: }
6478: }
6479: }
6480: if (@groupkeys > 0) {
6481: foreach my $role (@groupkeys) {
6482: my ($trole,$area,$sec,$extendedarea);
6483: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
6484: $trole = $1;
6485: $area = $2;
6486: $sec = $3;
6487: $extendedarea = $area.$sec;
6488: if (exists($$allgroups{$area})) {
6489: foreach my $group (keys(%{$$allgroups{$area}})) {
6490: my $spec = $trole.'.'.$extendedarea;
6491: $grouproles{$spec.'.'.$area.'/'.$group} =
6492: $$allgroups{$area}{$group};
6493: }
6494: }
6495: }
6496: }
6497: }
6498: }
6499: foreach my $group (keys(%grouproles)) {
6500: $$allroles{$group} = $grouproles{$group};
6501: }
6502: foreach my $role (keys(%{$allroles})) {
6503: my %thesepriv;
6504: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
6505: foreach my $item (split(/:/,$$allroles{$role})) {
6506: if ($item ne '') {
6507: my ($privilege,$restrictions)=split(/&/,$item);
6508: if ($restrictions eq '') {
6509: $thesepriv{$privilege}='F';
6510: } elsif ($thesepriv{$privilege} ne 'F') {
6511: $thesepriv{$privilege}.=$restrictions;
6512: }
6513: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
6514: if ($thesepriv{'rar'} eq 'F') { $rar=1; }
6515: }
6516: }
6517: my $thesestr='';
6518: foreach my $priv (sort(keys(%thesepriv))) {
6519: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
6520: }
6521: $userroles->{'user.priv.'.$role} = $thesestr;
6522: }
6523: return ($author,$adv,$rar);
6524: }
6525:
6526: sub role_status {
6527: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
6528: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
6529: my ($one,$two) = split(m{\./},$rolekey,2);
6530: (undef,undef,$$role) = split(/\./,$one,3);
6531: unless (!defined($$role) || $$role eq '') {
6532: $$where = '/'.$two;
6533: $$trolecode=$$role.'.'.$$where;
6534: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
6535: $$tstatus='is';
6536: if ($$tstart && $$tstart>$update) {
6537: $$tstatus='future';
6538: if ($$tstart<$now) {
6539: if ($$tstart && $$tstart>$refresh) {
6540: if (($$where ne '') && ($$role ne '')) {
6541: my (%allroles,%allgroups,$group_privs,
6542: %groups_roles,@rolecodes);
6543: my %userroles = (
6544: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
6545: );
6546: @rolecodes = ('cm');
6547: my $spec=$$role.'.'.$$where;
6548: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
6549: if ($$role =~ /^cr\//) {
6550: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
6551: push(@rolecodes,'cr');
6552: } elsif ($$role eq 'gr') {
6553: push(@rolecodes,$$role);
6554: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
6555: $env{'user.name'});
6556: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
6557: (undef,my $group_privs) = split(/\//,$trole);
6558: $group_privs = &unescape($group_privs);
6559: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
6560: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
6561: &get_groups_roles($tdomain,$trest,
6562: \%course_roles,\@rolecodes,
6563: \%groups_roles);
6564: } else {
6565: push(@rolecodes,$$role);
6566: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
6567: }
6568: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%allroles,\%allgroups,
6569: \%groups_roles);
6570: &appenv(\%userroles,\@rolecodes);
6571: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6572: }
6573: }
6574: $$tstatus = 'is';
6575: }
6576: }
6577: if ($$tend) {
6578: if ($$tend<$update) {
6579: $$tstatus='expired';
6580: } elsif ($$tend<$now) {
6581: $$tstatus='will_not';
6582: }
6583: }
6584: }
6585: }
6586: }
6587:
6588: sub get_groups_roles {
6589: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
6590: return unless((ref($cdom_courseroles) eq 'HASH') &&
6591: (ref($rolecodes) eq 'ARRAY') &&
6592: (ref($groups_roles) eq 'HASH'));
6593: if (keys(%{$cdom_courseroles}) > 0) {
6594: my ($cnum) = ($rest =~ /^($match_courseid)/);
6595: if ($cdom ne '' && $cnum ne '') {
6596: foreach my $key (keys(%{$cdom_courseroles})) {
6597: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
6598: my $crsrole = $1;
6599: my $crssec = $2;
6600: if ($crsrole =~ /^cr/) {
6601: unless (grep(/^cr$/,@{$rolecodes})) {
6602: push(@{$rolecodes},'cr');
6603: }
6604: } else {
6605: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
6606: push(@{$rolecodes},$crsrole);
6607: }
6608: }
6609: my $rolekey = "$crsrole./$cdom/$cnum";
6610: if ($crssec ne '') {
6611: $rolekey .= "/$crssec";
6612: }
6613: $rolekey .= './';
6614: $groups_roles->{$rolekey} = $rolecodes;
6615: }
6616: }
6617: }
6618: }
6619: return;
6620: }
6621:
6622: sub delete_env_groupprivs {
6623: my ($where,$courseroles,$possroles) = @_;
6624: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
6625: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
6626: unless (ref($courseroles->{$udom}) eq 'HASH') {
6627: %{$courseroles->{$udom}} =
6628: &get_my_roles('','','userroles',['active'],
6629: $possroles,[$udom],1);
6630: }
6631: if (ref($courseroles->{$udom}) eq 'HASH') {
6632: foreach my $item (keys(%{$courseroles->{$udom}})) {
6633: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
6634: my $area = '/'.$cdom.'/'.$cnum;
6635: my $privkey = "user.priv.$crsrole.$area";
6636: if ($crssec ne '') {
6637: $privkey .= '/'.$crssec;
6638: }
6639: $privkey .= ".$area/$group";
6640: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
6641: }
6642: }
6643: return;
6644: }
6645:
6646: sub check_adhoc_privs {
6647: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller,$sec) = @_;
6648: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
6649: if ($sec) {
6650: $cckey .= '/'.$sec;
6651: }
6652: my $setprivs;
6653: if ($env{$cckey}) {
6654: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
6655: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
6656: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
6657: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6658: $setprivs = 1;
6659: }
6660: } else {
6661: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller,$sec);
6662: $setprivs = 1;
6663: }
6664: return $setprivs;
6665: }
6666:
6667: sub set_adhoc_privileges {
6668: # role can be cc, ca, or cr/<dom>/<dom>-domainconfig/role
6669: my ($dcdom,$pickedcourse,$role,$caller,$sec) = @_;
6670: my $area = '/'.$dcdom.'/'.$pickedcourse;
6671: if ($sec ne '') {
6672: $area .= '/'.$sec;
6673: }
6674: my $spec = $role.'.'.$area;
6675: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
6676: $env{'user.name'},1);
6677: my %rolehash = ();
6678: if ($role =~ m{^\Qcr/$dcdom/$dcdom\E\-domainconfig/(\w+)$}) {
6679: my $rolename = $1;
6680: &custom_roleprivs(\%rolehash,$role,$dcdom,$pickedcourse,$spec,$area);
6681: my %domdef = &get_domain_defaults($dcdom);
6682: if (ref($domdef{'adhocroles'}) eq 'HASH') {
6683: if (ref($domdef{'adhocroles'}{$rolename}) eq 'HASH') {
6684: &appenv({'request.role.desc' => $domdef{'adhocroles'}{$rolename}{'desc'},});
6685: }
6686: }
6687: } else {
6688: &standard_roleprivs(\%rolehash,$role,$dcdom,$spec,$pickedcourse,$area);
6689: }
6690: my ($author,$adv,$rar)= &set_userprivs(\%userroles,\%rolehash);
6691: &appenv(\%userroles,[$role,'cm']);
6692: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$spec);
6693: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
6694: &appenv( {'request.role' => $spec,
6695: 'request.role.domain' => $dcdom,
6696: 'request.course.sec' => $sec,
6697: }
6698: );
6699: my $tadv=0;
6700: if (&allowed('adv') eq 'F') { $tadv=1; }
6701: &appenv({'request.role.adv' => $tadv});
6702: }
6703: }
6704:
6705: # --------------------------------------------------------------- get interface
6706:
6707: sub get {
6708: my ($namespace,$storearr,$udomain,$uname)=@_;
6709: my $items='';
6710: foreach my $item (@$storearr) {
6711: $items.=&escape($item).'&';
6712: }
6713: $items=~s/\&$//;
6714: if (!$udomain) { $udomain=$env{'user.domain'}; }
6715: if (!$uname) { $uname=$env{'user.name'}; }
6716: my $uhome=&homeserver($uname,$udomain);
6717:
6718: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
6719: my @pairs=split(/\&/,$rep);
6720: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
6721: return @pairs;
6722: }
6723: my %returnhash=();
6724: my $i=0;
6725: foreach my $item (@$storearr) {
6726: $returnhash{$item}=&thaw_unescape($pairs[$i]);
6727: $i++;
6728: }
6729: return %returnhash;
6730: }
6731:
6732: # --------------------------------------------------------------- del interface
6733:
6734: sub del {
6735: my ($namespace,$storearr,$udomain,$uname)=@_;
6736: my $items='';
6737: foreach my $item (@$storearr) {
6738: $items.=&escape($item).'&';
6739: }
6740:
6741: $items=~s/\&$//;
6742: if (!$udomain) { $udomain=$env{'user.domain'}; }
6743: if (!$uname) { $uname=$env{'user.name'}; }
6744: my $uhome=&homeserver($uname,$udomain);
6745: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
6746: }
6747:
6748: # -------------------------------------------------------------- dump interface
6749:
6750: sub unserialize {
6751: my ($rep, $escapedkeys) = @_;
6752:
6753: return {} if $rep =~ /^error/;
6754:
6755: my %returnhash=();
6756: foreach my $item (split(/\&/,$rep)) {
6757: my ($key, $value) = split(/=/, $item, 2);
6758: $key = unescape($key) unless $escapedkeys;
6759: next if $key =~ /^error: 2 /;
6760: $returnhash{$key} = &thaw_unescape($value);
6761: }
6762: return \%returnhash;
6763: }
6764:
6765: # see Lond::dump_with_regexp
6766: # if $escapedkeys hash keys won't get unescaped.
6767: sub dump {
6768: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
6769: if (!$udomain) { $udomain=$env{'user.domain'}; }
6770: if (!$uname) { $uname=$env{'user.name'}; }
6771: my $uhome=&homeserver($uname,$udomain);
6772:
6773: if ($regexp) {
6774: $regexp=&escape($regexp);
6775: } else {
6776: $regexp='.';
6777: }
6778: if (grep { $_ eq $uhome } ¤t_machine_ids()) {
6779: # user is hosted on this machine
6780: my $reply = LONCAPA::Lond::dump_with_regexp(join(':', ($udomain,
6781: $uname, $namespace, $regexp, $range)), $perlvar{'lonVersion'});
6782: return %{&unserialize($reply, $escapedkeys)};
6783: }
6784: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
6785: my @pairs=split(/\&/,$rep);
6786: my %returnhash=();
6787: if (!($rep =~ /^error/ )) {
6788: foreach my $item (@pairs) {
6789: my ($key,$value)=split(/=/,$item,2);
6790: $key = &unescape($key) unless ($escapedkeys);
6791: next if ($key =~ /^error: 2 /);
6792: $returnhash{$key}=&thaw_unescape($value);
6793: }
6794: }
6795: return %returnhash;
6796: }
6797:
6798:
6799: # --------------------------------------------------------- dumpstore interface
6800:
6801: sub dumpstore {
6802: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
6803: # same as dump but keys must be escaped. They may contain colon separated
6804: # lists of values that may themself contain colons (e.g. symbs).
6805: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
6806: }
6807:
6808: # -------------------------------------------------------------- keys interface
6809:
6810: sub getkeys {
6811: my ($namespace,$udomain,$uname)=@_;
6812: if (!$udomain) { $udomain=$env{'user.domain'}; }
6813: if (!$uname) { $uname=$env{'user.name'}; }
6814: my $uhome=&homeserver($uname,$udomain);
6815: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
6816: my @keyarray=();
6817: foreach my $key (split(/\&/,$rep)) {
6818: next if ($key =~ /^error: 2 /);
6819: push(@keyarray,&unescape($key));
6820: }
6821: return @keyarray;
6822: }
6823:
6824: # --------------------------------------------------------------- currentdump
6825: sub currentdump {
6826: my ($courseid,$sdom,$sname)=@_;
6827: $courseid = $env{'request.course.id'} if (! defined($courseid));
6828: $sdom = $env{'user.domain'} if (! defined($sdom));
6829: $sname = $env{'user.name'} if (! defined($sname));
6830: my $uhome = &homeserver($sname,$sdom);
6831: my $rep;
6832:
6833: if (grep { $_ eq $uhome } current_machine_ids()) {
6834: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
6835: $courseid)));
6836: } else {
6837: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
6838: }
6839:
6840: return if ($rep =~ /^(error:|no_such_host)/);
6841: #
6842: my %returnhash=();
6843: #
6844: if ($rep eq "unknown_cmd") {
6845: # an old lond will not know currentdump
6846: # Do a dump and make it look like a currentdump
6847: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
6848: return if ($tmp[0] =~ /^(error:|no_such_host)/);
6849: my %hash = @tmp;
6850: @tmp=();
6851: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
6852: } else {
6853: my @pairs=split(/\&/,$rep);
6854: foreach my $pair (@pairs) {
6855: my ($key,$value)=split(/=/,$pair,2);
6856: my ($symb,$param) = split(/:/,$key);
6857: $returnhash{&unescape($symb)}->{&unescape($param)} =
6858: &thaw_unescape($value);
6859: }
6860: }
6861: return %returnhash;
6862: }
6863:
6864: sub convert_dump_to_currentdump{
6865: my %hash = %{shift()};
6866: my %returnhash;
6867: # Code ripped from lond, essentially. The only difference
6868: # here is the unescaping done by lonnet::dump(). Conceivably
6869: # we might run in to problems with parameter names =~ /^v\./
6870: while (my ($key,$value) = each(%hash)) {
6871: my ($v,$symb,$param) = split(/:/,$key);
6872: $symb = &unescape($symb);
6873: $param = &unescape($param);
6874: next if ($v eq 'version' || $symb eq 'keys');
6875: next if (exists($returnhash{$symb}) &&
6876: exists($returnhash{$symb}->{$param}) &&
6877: $returnhash{$symb}->{'v.'.$param} > $v);
6878: $returnhash{$symb}->{$param}=$value;
6879: $returnhash{$symb}->{'v.'.$param}=$v;
6880: }
6881: #
6882: # Remove all of the keys in the hashes which keep track of
6883: # the version of the parameter.
6884: while (my ($symb,$param_hash) = each(%returnhash)) {
6885: # use a foreach because we are going to delete from the hash.
6886: foreach my $key (keys(%$param_hash)) {
6887: delete($param_hash->{$key}) if ($key =~ /^v\./);
6888: }
6889: }
6890: return \%returnhash;
6891: }
6892:
6893: # ------------------------------------------------------ critical inc interface
6894:
6895: sub cinc {
6896: return &inc(@_,'critical');
6897: }
6898:
6899: # --------------------------------------------------------------- inc interface
6900:
6901: sub inc {
6902: my ($namespace,$store,$udomain,$uname,$critical) = @_;
6903: if (!$udomain) { $udomain=$env{'user.domain'}; }
6904: if (!$uname) { $uname=$env{'user.name'}; }
6905: my $uhome=&homeserver($uname,$udomain);
6906: my $items='';
6907: if (! ref($store)) {
6908: # got a single value, so use that instead
6909: $items = &escape($store).'=&';
6910: } elsif (ref($store) eq 'SCALAR') {
6911: $items = &escape($$store).'=&';
6912: } elsif (ref($store) eq 'ARRAY') {
6913: $items = join('=&',map {&escape($_);} @{$store});
6914: } elsif (ref($store) eq 'HASH') {
6915: while (my($key,$value) = each(%{$store})) {
6916: $items.= &escape($key).'='.&escape($value).'&';
6917: }
6918: }
6919: $items=~s/\&$//;
6920: if ($critical) {
6921: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
6922: } else {
6923: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
6924: }
6925: }
6926:
6927: # --------------------------------------------------------------- put interface
6928:
6929: sub put {
6930: my ($namespace,$storehash,$udomain,$uname)=@_;
6931: if (!$udomain) { $udomain=$env{'user.domain'}; }
6932: if (!$uname) { $uname=$env{'user.name'}; }
6933: my $uhome=&homeserver($uname,$udomain);
6934: my $items='';
6935: foreach my $item (keys(%$storehash)) {
6936: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
6937: }
6938: $items=~s/\&$//;
6939: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
6940: }
6941:
6942: # ------------------------------------------------------------ newput interface
6943:
6944: sub newput {
6945: my ($namespace,$storehash,$udomain,$uname)=@_;
6946: if (!$udomain) { $udomain=$env{'user.domain'}; }
6947: if (!$uname) { $uname=$env{'user.name'}; }
6948: my $uhome=&homeserver($uname,$udomain);
6949: my $items='';
6950: foreach my $key (keys(%$storehash)) {
6951: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6952: }
6953: $items=~s/\&$//;
6954: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
6955: }
6956:
6957: # --------------------------------------------------------- putstore interface
6958:
6959: sub putstore {
6960: my ($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog)=@_;
6961: if (!$udomain) { $udomain=$env{'user.domain'}; }
6962: if (!$uname) { $uname=$env{'user.name'}; }
6963: my $uhome=&homeserver($uname,$udomain);
6964: my $items='';
6965: foreach my $key (keys(%$storehash)) {
6966: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6967: }
6968: $items=~s/\&$//;
6969: my $esc_symb=&escape($symb);
6970: my $esc_v=&escape($version);
6971: my $reply =
6972: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
6973: $uhome);
6974: if (($tolog) && ($reply eq 'ok')) {
6975: my $namevalue='';
6976: foreach my $key (keys(%{$storehash})) {
6977: $namevalue.=&escape($key).'='.&freeze_escape($storehash->{$key}).'&';
6978: }
6979: $namevalue .= 'ip='.&escape($ENV{'REMOTE_ADDR'}).
6980: '&host='.&escape($perlvar{'lonHostID'}).
6981: '&version='.$esc_v.
6982: '&by='.&escape($env{'user.name'}.':'.$env{'user.domain'});
6983: &Apache::lonnet::courselog($symb.':'.$uname.':'.$udomain.':PUTSTORE:'.$namevalue);
6984: }
6985: if ($reply eq 'unknown_cmd') {
6986: # gfall back to way things use to be done
6987: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
6988: $uname);
6989: }
6990: return $reply;
6991: }
6992:
6993: sub old_putstore {
6994: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
6995: if (!$udomain) { $udomain=$env{'user.domain'}; }
6996: if (!$uname) { $uname=$env{'user.name'}; }
6997: my $uhome=&homeserver($uname,$udomain);
6998: my %newstorehash;
6999: foreach my $item (keys(%$storehash)) {
7000: my $key = $version.':'.&escape($symb).':'.$item;
7001: $newstorehash{$key} = $storehash->{$item};
7002: }
7003: my $items='';
7004: my %allitems = ();
7005: foreach my $item (keys(%newstorehash)) {
7006: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
7007: my $key = $1.':keys:'.$2;
7008: $allitems{$key} .= $3.':';
7009: }
7010: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
7011: }
7012: foreach my $item (keys(%allitems)) {
7013: $allitems{$item} =~ s/\:$//;
7014: $items.= $item.'='.$allitems{$item}.'&';
7015: }
7016: $items=~s/\&$//;
7017: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
7018: }
7019:
7020: # ------------------------------------------------------ critical put interface
7021:
7022: sub cput {
7023: my ($namespace,$storehash,$udomain,$uname)=@_;
7024: if (!$udomain) { $udomain=$env{'user.domain'}; }
7025: if (!$uname) { $uname=$env{'user.name'}; }
7026: my $uhome=&homeserver($uname,$udomain);
7027: my $items='';
7028: foreach my $item (keys(%$storehash)) {
7029: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7030: }
7031: $items=~s/\&$//;
7032: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
7033: }
7034:
7035: # -------------------------------------------------------------- eget interface
7036:
7037: sub eget {
7038: my ($namespace,$storearr,$udomain,$uname)=@_;
7039: my $items='';
7040: foreach my $item (@$storearr) {
7041: $items.=&escape($item).'&';
7042: }
7043: $items=~s/\&$//;
7044: if (!$udomain) { $udomain=$env{'user.domain'}; }
7045: if (!$uname) { $uname=$env{'user.name'}; }
7046: my $uhome=&homeserver($uname,$udomain);
7047: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
7048: my @pairs=split(/\&/,$rep);
7049: my %returnhash=();
7050: my $i=0;
7051: foreach my $item (@$storearr) {
7052: $returnhash{$item}=&thaw_unescape($pairs[$i]);
7053: $i++;
7054: }
7055: return %returnhash;
7056: }
7057:
7058: # ------------------------------------------------------------ tmpput interface
7059: sub tmpput {
7060: my ($storehash,$server,$context)=@_;
7061: my $items='';
7062: foreach my $item (keys(%$storehash)) {
7063: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
7064: }
7065: $items=~s/\&$//;
7066: if (defined($context)) {
7067: $items .= ':'.&escape($context);
7068: }
7069: return &reply("tmpput:$items",$server);
7070: }
7071:
7072: # ------------------------------------------------------------ tmpget interface
7073: sub tmpget {
7074: my ($token,$server)=@_;
7075: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7076: my $rep=&reply("tmpget:$token",$server);
7077: my %returnhash;
7078: if ($rep =~ /^(con_lost|error|no_such_host)/i) {
7079: return %returnhash;
7080: }
7081: foreach my $item (split(/\&/,$rep)) {
7082: my ($key,$value)=split(/=/,$item);
7083: $returnhash{&unescape($key)}=&thaw_unescape($value);
7084: }
7085: return %returnhash;
7086: }
7087:
7088: # ------------------------------------------------------------ tmpdel interface
7089: sub tmpdel {
7090: my ($token,$server)=@_;
7091: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
7092: return &reply("tmpdel:$token",$server);
7093: }
7094:
7095: # ------------------------------------------------------------ get_timebased_id
7096:
7097: sub get_timebased_id {
7098: my ($prefix,$keyid,$namespace,$cdom,$cnum,$idtype,$who,$locktries,
7099: $maxtries) = @_;
7100: my ($newid,$error,$dellock);
7101: unless (($prefix =~ /^\w+$/) && ($keyid =~ /^\w+$/) && ($namespace ne '')) {
7102: return ('','ok','invalid call to get suffix');
7103: }
7104:
7105: # set defaults for any optional args for which values were not supplied
7106: if ($who eq '') {
7107: $who = $env{'user.name'}.':'.$env{'user.domain'};
7108: }
7109: if (!$locktries) {
7110: $locktries = 3;
7111: }
7112: if (!$maxtries) {
7113: $maxtries = 10;
7114: }
7115:
7116: if (($cdom eq '') || ($cnum eq '')) {
7117: if ($env{'request.course.id'}) {
7118: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7119: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7120: }
7121: if (($cdom eq '') || ($cnum eq '')) {
7122: return ('','ok','call to get suffix not in course context');
7123: }
7124: }
7125:
7126: # construct locking item
7127: my $lockhash = {
7128: $prefix."\0".'locked_'.$keyid => $who,
7129: };
7130: my $tries = 0;
7131:
7132: # attempt to get lock on nohist_$namespace file
7133: my $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7134: while (($gotlock ne 'ok') && $tries <$locktries) {
7135: $tries ++;
7136: sleep 1;
7137: $gotlock = &Apache::lonnet::newput('nohist_'.$namespace,$lockhash,$cdom,$cnum);
7138: }
7139:
7140: # attempt to get unique identifier, based on current timestamp
7141: if ($gotlock eq 'ok') {
7142: my %inuse = &Apache::lonnet::dump('nohist_'.$namespace,$cdom,$cnum,$prefix);
7143: my $id = time;
7144: $newid = $id;
7145: if ($idtype eq 'addcode') {
7146: $newid .= &sixnum_code();
7147: }
7148: my $idtries = 0;
7149: while (exists($inuse{$prefix."\0".$newid}) && $idtries < $maxtries) {
7150: if ($idtype eq 'concat') {
7151: $newid = $id.$idtries;
7152: } elsif ($idtype eq 'addcode') {
7153: $newid = $newid.&sixnum_code();
7154: } else {
7155: $newid ++;
7156: }
7157: $idtries ++;
7158: }
7159: if (!exists($inuse{$prefix."\0".$newid})) {
7160: my %new_item = (
7161: $prefix."\0".$newid => $who,
7162: );
7163: my $putresult = &Apache::lonnet::put('nohist_'.$namespace,\%new_item,
7164: $cdom,$cnum);
7165: if ($putresult ne 'ok') {
7166: undef($newid);
7167: $error = 'error saving new item: '.$putresult;
7168: }
7169: } else {
7170: undef($newid);
7171: $error = ('error: no unique suffix available for the new item ');
7172: }
7173: # remove lock
7174: my @del_lock = ($prefix."\0".'locked_'.$keyid);
7175: $dellock = &Apache::lonnet::del('nohist_'.$namespace,\@del_lock,$cdom,$cnum);
7176: } else {
7177: $error = "error: could not obtain lockfile\n";
7178: $dellock = 'ok';
7179: if (($prefix eq 'paste') && ($namespace eq 'courseeditor') && ($keyid eq 'num')) {
7180: $dellock = 'nolock';
7181: }
7182: }
7183: return ($newid,$dellock,$error);
7184: }
7185:
7186: sub sixnum_code {
7187: my $code;
7188: for (0..6) {
7189: $code .= int( rand(9) );
7190: }
7191: return $code;
7192: }
7193:
7194: # -------------------------------------------------- portfolio access checking
7195:
7196: sub portfolio_access {
7197: my ($requrl,$clientip) = @_;
7198: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
7199: my $result = &get_portfolio_access($udom,$unum,$file_name,$group,$clientip);
7200: if ($result) {
7201: my %setters;
7202: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7203: my ($startblock,$endblock) =
7204: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
7205: if ($startblock && $endblock) {
7206: return 'B';
7207: }
7208: } else {
7209: my ($startblock,$endblock) =
7210: &Apache::loncommon::blockcheck(\%setters,'port');
7211: if ($startblock && $endblock) {
7212: return 'B';
7213: }
7214: }
7215: }
7216: if ($result eq 'ok') {
7217: return 'F';
7218: } elsif ($result =~ /^[^:]+:guest_/) {
7219: return 'A';
7220: }
7221: return '';
7222: }
7223:
7224: sub get_portfolio_access {
7225: my ($udom,$unum,$file_name,$group,$clientip,$access_hash) = @_;
7226:
7227: if (!ref($access_hash)) {
7228: my $current_perms = &get_portfile_permissions($udom,$unum);
7229: my %access_controls = &get_access_controls($current_perms,$group,
7230: $file_name);
7231: $access_hash = $access_controls{$file_name};
7232: }
7233:
7234: my ($public,$guest,@domains,@users,@courses,@groups,@ips);
7235: my $now = time;
7236: if (ref($access_hash) eq 'HASH') {
7237: foreach my $key (keys(%{$access_hash})) {
7238: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
7239: if ($start > $now) {
7240: next;
7241: }
7242: if ($end && $end<$now) {
7243: next;
7244: }
7245: if ($scope eq 'public') {
7246: $public = $key;
7247: last;
7248: } elsif ($scope eq 'guest') {
7249: $guest = $key;
7250: } elsif ($scope eq 'domains') {
7251: push(@domains,$key);
7252: } elsif ($scope eq 'users') {
7253: push(@users,$key);
7254: } elsif ($scope eq 'course') {
7255: push(@courses,$key);
7256: } elsif ($scope eq 'group') {
7257: push(@groups,$key);
7258: } elsif ($scope eq 'ip') {
7259: push(@ips,$key);
7260: }
7261: }
7262: if ($public) {
7263: return 'ok';
7264: } elsif (@ips > 0) {
7265: my $allowed;
7266: foreach my $ipkey (@ips) {
7267: if (ref($access_hash->{$ipkey}{'ip'}) eq 'ARRAY') {
7268: if (&Apache::loncommon::check_ip_acc(join(',',@{$access_hash->{$ipkey}{'ip'}}),$clientip)) {
7269: $allowed = 1;
7270: last;
7271: }
7272: }
7273: }
7274: if ($allowed) {
7275: return 'ok';
7276: }
7277: }
7278: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
7279: if ($guest) {
7280: return $guest;
7281: }
7282: } else {
7283: if (@domains > 0) {
7284: foreach my $domkey (@domains) {
7285: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
7286: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
7287: return 'ok';
7288: }
7289: }
7290: }
7291: }
7292: if (@users > 0) {
7293: foreach my $userkey (@users) {
7294: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
7295: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
7296: if (ref($item) eq 'HASH') {
7297: if (($item->{'uname'} eq $env{'user.name'}) &&
7298: ($item->{'udom'} eq $env{'user.domain'})) {
7299: return 'ok';
7300: }
7301: }
7302: }
7303: }
7304: }
7305: }
7306: my %roleshash;
7307: my @courses_and_groups = @courses;
7308: push(@courses_and_groups,@groups);
7309: if (@courses_and_groups > 0) {
7310: my (%allgroups,%allroles);
7311: my ($start,$end,$role,$sec,$group);
7312: foreach my $envkey (%env) {
7313: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
7314: my $cid = $2.'_'.$3;
7315: if ($1 eq 'gr') {
7316: $group = $4;
7317: $allgroups{$cid}{$group} = $env{$envkey};
7318: } else {
7319: if ($4 eq '') {
7320: $sec = 'none';
7321: } else {
7322: $sec = $4;
7323: }
7324: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7325: }
7326: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
7327: my $cid = $2.'_'.$3;
7328: if ($4 eq '') {
7329: $sec = 'none';
7330: } else {
7331: $sec = $4;
7332: }
7333: $allroles{$cid}{$1}{$sec} = $env{$envkey};
7334: }
7335: }
7336: if (keys(%allroles) == 0) {
7337: return;
7338: }
7339: foreach my $key (@courses_and_groups) {
7340: my %content = %{$$access_hash{$key}};
7341: my $cnum = $content{'number'};
7342: my $cdom = $content{'domain'};
7343: my $cid = $cdom.'_'.$cnum;
7344: if (!exists($allroles{$cid})) {
7345: next;
7346: }
7347: foreach my $role_id (keys(%{$content{'roles'}})) {
7348: my @sections = @{$content{'roles'}{$role_id}{'section'}};
7349: my @groups = @{$content{'roles'}{$role_id}{'group'}};
7350: my @status = @{$content{'roles'}{$role_id}{'access'}};
7351: my @roles = @{$content{'roles'}{$role_id}{'role'}};
7352: foreach my $role (keys(%{$allroles{$cid}})) {
7353: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
7354: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
7355: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
7356: if (grep/^all$/,@sections) {
7357: return 'ok';
7358: } else {
7359: if (grep/^$sec$/,@sections) {
7360: return 'ok';
7361: }
7362: }
7363: }
7364: }
7365: if (keys(%{$allgroups{$cid}}) == 0) {
7366: if (grep/^none$/,@groups) {
7367: return 'ok';
7368: }
7369: } else {
7370: if (grep/^all$/,@groups) {
7371: return 'ok';
7372: }
7373: foreach my $group (keys(%{$allgroups{$cid}})) {
7374: if (grep/^$group$/,@groups) {
7375: return 'ok';
7376: }
7377: }
7378: }
7379: }
7380: }
7381: }
7382: }
7383: }
7384: if ($guest) {
7385: return $guest;
7386: }
7387: }
7388: }
7389: return;
7390: }
7391:
7392: sub course_group_datechecker {
7393: my ($dates,$now,$status) = @_;
7394: my ($start,$end) = split(/\./,$dates);
7395: if (!$start && !$end) {
7396: return 'ok';
7397: }
7398: if (grep/^active$/,@{$status}) {
7399: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
7400: return 'ok';
7401: }
7402: }
7403: if (grep/^previous$/,@{$status}) {
7404: if ($end > $now ) {
7405: return 'ok';
7406: }
7407: }
7408: if (grep/^future$/,@{$status}) {
7409: if ($start > $now) {
7410: return 'ok';
7411: }
7412: }
7413: return;
7414: }
7415:
7416: sub parse_portfolio_url {
7417: my ($url) = @_;
7418:
7419: my ($type,$udom,$unum,$group,$file_name);
7420:
7421: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
7422: $type = 1;
7423: $udom = $1;
7424: $unum = $2;
7425: $file_name = $3;
7426: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
7427: $type = 2;
7428: $udom = $1;
7429: $unum = $2;
7430: $group = $3;
7431: $file_name = $3.'/'.$4;
7432: }
7433: if (wantarray) {
7434: return ($type,$udom,$unum,$file_name,$group);
7435: }
7436: return $type;
7437: }
7438:
7439: sub is_portfolio_url {
7440: my ($url) = @_;
7441: return scalar(&parse_portfolio_url($url));
7442: }
7443:
7444: sub is_portfolio_file {
7445: my ($file) = @_;
7446: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
7447: return 1;
7448: }
7449: return;
7450: }
7451:
7452: sub usertools_access {
7453: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
7454: my ($access,%tools);
7455: if ($context eq '') {
7456: $context = 'tools';
7457: }
7458: if ($context eq 'requestcourses') {
7459: %tools = (
7460: official => 1,
7461: unofficial => 1,
7462: community => 1,
7463: textbook => 1,
7464: );
7465: } elsif ($context eq 'requestauthor') {
7466: %tools = (
7467: requestauthor => 1,
7468: );
7469: } else {
7470: %tools = (
7471: aboutme => 1,
7472: blog => 1,
7473: webdav => 1,
7474: portfolio => 1,
7475: );
7476: }
7477: return if (!defined($tools{$tool}));
7478:
7479: if (($udom eq '') || ($uname eq '')) {
7480: $udom = $env{'user.domain'};
7481: $uname = $env{'user.name'};
7482: }
7483:
7484: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7485: if ($action ne 'reload') {
7486: if ($context eq 'requestcourses') {
7487: return $env{'environment.canrequest.'.$tool};
7488: } elsif ($context eq 'requestauthor') {
7489: return $env{'environment.canrequest.author'};
7490: } else {
7491: return $env{'environment.availabletools.'.$tool};
7492: }
7493: }
7494: }
7495:
7496: my ($toolstatus,$inststatus,$envkey);
7497: if ($context eq 'requestauthor') {
7498: $envkey = $context;
7499: } else {
7500: $envkey = $context.'.'.$tool;
7501: }
7502:
7503: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
7504: ($action ne 'reload')) {
7505: $toolstatus = $env{'environment.'.$envkey};
7506: $inststatus = $env{'environment.inststatus'};
7507: } else {
7508: if (ref($userenvref) eq 'HASH') {
7509: $toolstatus = $userenvref->{$envkey};
7510: $inststatus = $userenvref->{'inststatus'};
7511: } else {
7512: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
7513: $toolstatus = $userenv{$envkey};
7514: $inststatus = $userenv{'inststatus'};
7515: }
7516: }
7517:
7518: if ($toolstatus ne '') {
7519: if ($toolstatus) {
7520: $access = 1;
7521: } else {
7522: $access = 0;
7523: }
7524: return $access;
7525: }
7526:
7527: my ($is_adv,%domdef);
7528: if (ref($is_advref) eq 'HASH') {
7529: $is_adv = $is_advref->{'is_adv'};
7530: } else {
7531: $is_adv = &is_advanced_user($udom,$uname);
7532: }
7533: if (ref($domdefref) eq 'HASH') {
7534: %domdef = %{$domdefref};
7535: } else {
7536: %domdef = &get_domain_defaults($udom);
7537: }
7538: if (ref($domdef{$tool}) eq 'HASH') {
7539: if ($is_adv) {
7540: if ($domdef{$tool}{'_LC_adv'} ne '') {
7541: if ($domdef{$tool}{'_LC_adv'}) {
7542: $access = 1;
7543: } else {
7544: $access = 0;
7545: }
7546: return $access;
7547: }
7548: }
7549: if ($inststatus ne '') {
7550: my ($hasaccess,$hasnoaccess);
7551: foreach my $affiliation (split(/:/,$inststatus)) {
7552: if ($domdef{$tool}{$affiliation} ne '') {
7553: if ($domdef{$tool}{$affiliation}) {
7554: $hasaccess = 1;
7555: } else {
7556: $hasnoaccess = 1;
7557: }
7558: }
7559: }
7560: if ($hasaccess || $hasnoaccess) {
7561: if ($hasaccess) {
7562: $access = 1;
7563: } elsif ($hasnoaccess) {
7564: $access = 0;
7565: }
7566: return $access;
7567: }
7568: } else {
7569: if ($domdef{$tool}{'default'} ne '') {
7570: if ($domdef{$tool}{'default'}) {
7571: $access = 1;
7572: } elsif ($domdef{$tool}{'default'} == 0) {
7573: $access = 0;
7574: }
7575: return $access;
7576: }
7577: }
7578: } else {
7579: if (($context eq 'tools') && ($tool ne 'webdav')) {
7580: $access = 1;
7581: } else {
7582: $access = 0;
7583: }
7584: return $access;
7585: }
7586: }
7587:
7588: sub is_course_owner {
7589: my ($cdom,$cnum,$udom,$uname) = @_;
7590: if (($udom eq '') || ($uname eq '')) {
7591: $udom = $env{'user.domain'};
7592: $uname = $env{'user.name'};
7593: }
7594: unless (($udom eq '') || ($uname eq '')) {
7595: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
7596: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
7597: return 1;
7598: } else {
7599: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
7600: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
7601: return 1;
7602: }
7603: }
7604: }
7605: }
7606: return;
7607: }
7608:
7609: sub is_advanced_user {
7610: my ($udom,$uname) = @_;
7611: if ($udom ne '' && $uname ne '') {
7612: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
7613: if (wantarray) {
7614: return ($env{'user.adv'},$env{'user.author'});
7615: } else {
7616: return $env{'user.adv'};
7617: }
7618: }
7619: }
7620: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
7621: my %allroles;
7622: my ($is_adv,$is_author);
7623: foreach my $role (keys(%roleshash)) {
7624: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
7625: my $area = '/'.$tdomain.'/'.$trest;
7626: if ($sec ne '') {
7627: $area .= '/'.$sec;
7628: }
7629: if (($area ne '') && ($trole ne '')) {
7630: my $spec=$trole.'.'.$area;
7631: if ($trole =~ /^cr\//) {
7632: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
7633: } elsif ($trole ne 'gr') {
7634: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
7635: }
7636: if ($trole eq 'au') {
7637: $is_author = 1;
7638: }
7639: }
7640: }
7641: foreach my $role (keys(%allroles)) {
7642: last if ($is_adv);
7643: foreach my $item (split(/:/,$allroles{$role})) {
7644: if ($item ne '') {
7645: my ($privilege,$restrictions)=split(/&/,$item);
7646: if ($privilege eq 'adv') {
7647: $is_adv = 1;
7648: last;
7649: }
7650: }
7651: }
7652: }
7653: if (wantarray) {
7654: return ($is_adv,$is_author);
7655: }
7656: return $is_adv;
7657: }
7658:
7659: sub check_can_request {
7660: my ($dom,$can_request,$request_domains) = @_;
7661: my $canreq = 0;
7662: my ($types,$typename) = &Apache::loncommon::course_types();
7663: my @options = ('approval','validate','autolimit');
7664: my $optregex = join('|',@options);
7665: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
7666: foreach my $type (@{$types}) {
7667: if (&usertools_access($env{'user.name'},
7668: $env{'user.domain'},
7669: $type,undef,'requestcourses')) {
7670: $canreq ++;
7671: if (ref($request_domains) eq 'HASH') {
7672: push(@{$request_domains->{$type}},$env{'user.domain'});
7673: }
7674: if ($dom eq $env{'user.domain'}) {
7675: $can_request->{$type} = 1;
7676: }
7677: }
7678: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
7679: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
7680: if (@curr > 0) {
7681: foreach my $item (@curr) {
7682: if (ref($request_domains) eq 'HASH') {
7683: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
7684: if ($otherdom ne '') {
7685: if (ref($request_domains->{$type}) eq 'ARRAY') {
7686: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
7687: push(@{$request_domains->{$type}},$otherdom);
7688: }
7689: } else {
7690: push(@{$request_domains->{$type}},$otherdom);
7691: }
7692: }
7693: }
7694: }
7695: unless($dom eq $env{'user.domain'}) {
7696: $canreq ++;
7697: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
7698: $can_request->{$type} = 1;
7699: }
7700: }
7701: }
7702: }
7703: }
7704: }
7705: return $canreq;
7706: }
7707:
7708: # ---------------------------------------------- Custom access rule evaluation
7709:
7710: sub customaccess {
7711: my ($priv,$uri)=@_;
7712: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
7713: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
7714: $udom = &LONCAPA::clean_domain($udom);
7715: $ucrs = &LONCAPA::clean_username($ucrs);
7716: my $access=0;
7717: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
7718: my ($effect,$realm,$role,$type)=split(/\:/,$right);
7719: if ($type eq 'user') {
7720: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7721: my ($tdom,$tuname)=split(m{/},$scope);
7722: if ($tdom) {
7723: if ($tdom ne $env{'user.domain'}) { next; }
7724: }
7725: if ($tuname) {
7726: if ($tuname ne $env{'user.name'}) { next; }
7727: }
7728: $access=($effect eq 'allow');
7729: last;
7730: }
7731: } else {
7732: if ($role) {
7733: if ($role ne $urole) { next; }
7734: }
7735: foreach my $scope (split(/\s*\,\s*/,$realm)) {
7736: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
7737: if ($tdom) {
7738: if ($tdom ne $udom) { next; }
7739: }
7740: if ($tcrs) {
7741: if ($tcrs ne $ucrs) { next; }
7742: }
7743: if ($tsec) {
7744: if ($tsec ne $usec) { next; }
7745: }
7746: $access=($effect eq 'allow');
7747: last;
7748: }
7749: if ($realm eq '' && $role eq '') {
7750: $access=($effect eq 'allow');
7751: }
7752: }
7753: }
7754: return $access;
7755: }
7756:
7757: # ------------------------------------------------- Check for a user privilege
7758:
7759: sub allowed {
7760: my ($priv,$uri,$symb,$role,$clientip,$noblockcheck)=@_;
7761: my $ver_orguri=$uri;
7762: $uri=&deversion($uri);
7763: my $orguri=$uri;
7764: $uri=&declutter($uri);
7765:
7766: if ($priv eq 'evb') {
7767: # Evade communication block restrictions for specified role in a course
7768: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
7769: return $1;
7770: } else {
7771: return;
7772: }
7773: }
7774:
7775: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
7776: # Free bre access to adm and meta resources
7777: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
7778: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
7779: && ($priv eq 'bre')) {
7780: return 'F';
7781: }
7782:
7783: # Free bre access to user's own portfolio contents
7784: my ($space,$domain,$name,@dir)=split('/',$uri);
7785: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
7786: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
7787: my %setters;
7788: my ($startblock,$endblock) =
7789: &Apache::loncommon::blockcheck(\%setters,'port');
7790: if ($startblock && $endblock) {
7791: return 'B';
7792: } else {
7793: return 'F';
7794: }
7795: }
7796:
7797: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
7798: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
7799: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
7800: if (exists($env{'request.course.id'})) {
7801: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7802: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
7803: if (($domain eq $cdom) && ($name eq $cnum)) {
7804: my $courseprivid=$env{'request.course.id'};
7805: $courseprivid=~s/\_/\//;
7806: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
7807: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
7808: return $1;
7809: } else {
7810: if ($env{'request.course.sec'}) {
7811: $courseprivid.='/'.$env{'request.course.sec'};
7812: }
7813: if ($env{'user.priv.'.$env{'request.role'}.'./'.
7814: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
7815: return $2;
7816: }
7817: }
7818: }
7819: }
7820: }
7821:
7822: # Free bre to public access
7823:
7824: if ($priv eq 'bre') {
7825: my $copyright=&metadata($uri,'copyright');
7826: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
7827: return 'F';
7828: }
7829: if ($copyright eq 'priv') {
7830: $uri=~/([^\/]+)\/([^\/]+)\//;
7831: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
7832: return '';
7833: }
7834: }
7835: if ($copyright eq 'domain') {
7836: $uri=~/([^\/]+)\/([^\/]+)\//;
7837: unless (($env{'user.domain'} eq $1) ||
7838: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
7839: return '';
7840: }
7841: }
7842: if ($env{'request.role'}=~ /li\.\//) {
7843: # Library role, so allow browsing of resources in this domain.
7844: return 'F';
7845: }
7846: if ($copyright eq 'custom') {
7847: unless (&customaccess($priv,$uri)) { return ''; }
7848: }
7849: }
7850: # Domain coordinator is trying to create a course
7851: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
7852: # uri is the requested domain in this case.
7853: # comparison to 'request.role.domain' shows if the user has selected
7854: # a role of dc for the domain in question.
7855: return 'F' if ($uri eq $env{'request.role.domain'});
7856: }
7857:
7858: my $thisallowed='';
7859: my $statecond=0;
7860: my $courseprivid='';
7861:
7862: my $ownaccess;
7863: # Community Coordinator or Assistant Co-author browsing resource space.
7864: if (($priv eq 'bro') && ($env{'user.author'})) {
7865: if ($uri eq '') {
7866: $ownaccess = 1;
7867: } else {
7868: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
7869: my $udom = $env{'user.domain'};
7870: my $uname = $env{'user.name'};
7871: if ($uri =~ m{^\Q$udom\E/?$}) {
7872: $ownaccess = 1;
7873: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
7874: unless ($uri =~ m{\.\./}) {
7875: $ownaccess = 1;
7876: }
7877: } elsif (($udom ne 'public') && ($uname ne 'public')) {
7878: my $now = time;
7879: if ($uri =~ m{^([^/]+)/?$}) {
7880: my $adom = $1;
7881: foreach my $key (keys(%env)) {
7882: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
7883: my ($start,$end) = split('.',$env{$key});
7884: if (($now >= $start) && (!$end || $end < $now)) {
7885: $ownaccess = 1;
7886: last;
7887: }
7888: }
7889: }
7890: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
7891: my $adom = $1;
7892: my $aname = $2;
7893: foreach my $role ('ca','aa') {
7894: if ($env{"user.role.$role./$adom/$aname"}) {
7895: my ($start,$end) =
7896: split('.',$env{"user.role.$role./$adom/$aname"});
7897: if (($now >= $start) && (!$end || $end < $now)) {
7898: $ownaccess = 1;
7899: last;
7900: }
7901: }
7902: }
7903: }
7904: }
7905: }
7906: }
7907: }
7908:
7909: # Course
7910:
7911: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
7912: unless (($priv eq 'bro') && (!$ownaccess)) {
7913: $thisallowed.=$1;
7914: }
7915: }
7916:
7917: # Domain
7918:
7919: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
7920: =~/\Q$priv\E\&([^\:]*)/) {
7921: unless (($priv eq 'bro') && (!$ownaccess)) {
7922: $thisallowed.=$1;
7923: }
7924: }
7925:
7926: # User who is not author or co-author might still be able to edit
7927: # resource of an author in the domain (e.g., if Domain Coordinator).
7928: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
7929: (&allowed('mdc',$env{'request.course.id'}))) {
7930: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
7931: $thisallowed.=$1;
7932: }
7933: }
7934:
7935: # Course: uri itself is a course
7936: my $courseuri=$uri;
7937: $courseuri=~s/\_(\d)/\/$1/;
7938: $courseuri=~s/^([^\/])/\/$1/;
7939:
7940: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
7941: =~/\Q$priv\E\&([^\:]*)/) {
7942: if ($priv eq 'mip') {
7943: my $rem = $1;
7944: if (($uri ne '') && ($env{'request.course.id'} eq $uri) &&
7945: ($env{'course.'.$env{'request.course.id'}.'.internal.courseowner'} eq $env{'user.name'}.':'.$env{'user.domain'})) {
7946: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
7947: if ($cdom ne '') {
7948: my %passwdconf = &get_passwdconf($cdom);
7949: if (ref($passwdconf{'crsownerchg'}) eq 'HASH') {
7950: if (ref($passwdconf{'crsownerchg'}{'by'}) eq 'ARRAY') {
7951: if (@{$passwdconf{'crsownerchg'}{'by'}}) {
7952: my @inststatuses = split(':',$env{'environment.inststatus'});
7953: unless (@inststatuses) {
7954: @inststatuses = ('default');
7955: }
7956: foreach my $status (@inststatuses) {
7957: if (grep(/^\Q$status\E$/,@{$passwdconf{'crsownerchg'}{'by'}})) {
7958: $thisallowed.=$rem;
7959: }
7960: }
7961: }
7962: }
7963: }
7964: }
7965: }
7966: } else {
7967: unless (($priv eq 'bro') && (!$ownaccess)) {
7968: $thisallowed.=$1;
7969: }
7970: }
7971: }
7972:
7973: # URI is an uploaded document for this course, default permissions don't matter
7974: # not allowing 'edit' access (editupload) to uploaded course docs
7975: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
7976: $thisallowed='';
7977: my ($match)=&is_on_map($uri);
7978: if ($match) {
7979: if ($env{'user.priv.'.$env{'request.role'}.'./'}
7980: =~/\Q$priv\E\&([^\:]*)/) {
7981: my $value = $1;
7982: if ($noblockcheck) {
7983: $thisallowed.=$value;
7984: } else {
7985: my @blockers = &has_comm_blocking($priv,$symb,$uri);
7986: if (@blockers > 0) {
7987: $thisallowed = 'B';
7988: } else {
7989: $thisallowed.=$value;
7990: }
7991: }
7992: }
7993: } else {
7994: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
7995: if ($refuri) {
7996: if ($refuri =~ m|^/adm/|) {
7997: $thisallowed='F';
7998: } else {
7999: $refuri=&declutter($refuri);
8000: my ($match) = &is_on_map($refuri);
8001: if ($match) {
8002: if ($noblockcheck) {
8003: $thisallowed='F';
8004: } else {
8005: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8006: if (@blockers > 0) {
8007: $thisallowed = 'B';
8008: } else {
8009: $thisallowed='F';
8010: }
8011: }
8012: }
8013: }
8014: }
8015: }
8016: }
8017:
8018: if ($priv eq 'bre'
8019: && $thisallowed ne 'F'
8020: && $thisallowed ne '2'
8021: && &is_portfolio_url($uri)) {
8022: $thisallowed = &portfolio_access($uri,$clientip);
8023: }
8024:
8025: # Full access at system, domain or course-wide level? Exit.
8026: if ($thisallowed=~/F/) {
8027: return 'F';
8028: }
8029:
8030: # If this is generating or modifying users, exit with special codes
8031:
8032: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
8033: if (($priv eq 'cca') || ($priv eq 'caa')) {
8034: my ($audom,$auname)=split('/',$uri);
8035: # no author name given, so this just checks on the general right to make a co-author in this domain
8036: unless ($auname) { return $thisallowed; }
8037: # an author name is given, so we are about to actually make a co-author for a certain account
8038: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
8039: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
8040: ($audom ne $env{'request.role.domain'}))) { return ''; }
8041: }
8042: return $thisallowed;
8043: }
8044: #
8045: # Gathered so far: system, domain and course wide privileges
8046: #
8047: # Course: See if uri or referer is an individual resource that is part of
8048: # the course
8049:
8050: if ($env{'request.course.id'}) {
8051:
8052: # If this is modifying password (internal auth) domains must match for user and user's role.
8053:
8054: if ($priv eq 'mip') {
8055: if ($env{'user.domain'} eq $env{'request.role.domain'}) {
8056: return $thisallowed;
8057: } else {
8058: return '';
8059: }
8060: }
8061:
8062: $courseprivid=$env{'request.course.id'};
8063: if ($env{'request.course.sec'}) {
8064: $courseprivid.='/'.$env{'request.course.sec'};
8065: }
8066: $courseprivid=~s/\_/\//;
8067: my $checkreferer=1;
8068: my ($match,$cond)=&is_on_map($uri);
8069: if ($match) {
8070: $statecond=$cond;
8071: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8072: =~/\Q$priv\E\&([^\:]*)/) {
8073: my $value = $1;
8074: if ($priv eq 'bre') {
8075: if ($noblockcheck) {
8076: $thisallowed.=$value;
8077: } else {
8078: my @blockers = &has_comm_blocking($priv,$symb,$uri);
8079: if (@blockers > 0) {
8080: $thisallowed = 'B';
8081: } else {
8082: $thisallowed.=$value;
8083: }
8084: }
8085: } else {
8086: $thisallowed.=$value;
8087: }
8088: $checkreferer=0;
8089: }
8090: }
8091:
8092: if ($checkreferer) {
8093: my $refuri=$env{'httpref.'.$orguri};
8094: unless ($refuri) {
8095: foreach my $key (keys(%env)) {
8096: if ($key=~/^httpref\..*\*/) {
8097: my $pattern=$key;
8098: $pattern=~s/^httpref\.\/res\///;
8099: $pattern=~s/\*/\[\^\/\]\+/g;
8100: $pattern=~s/\//\\\//g;
8101: if ($orguri=~/$pattern/) {
8102: $refuri=$env{$key};
8103: }
8104: }
8105: }
8106: }
8107:
8108: if ($refuri) {
8109: $refuri=&declutter($refuri);
8110: my ($match,$cond)=&is_on_map($refuri);
8111: if ($match) {
8112: my $refstatecond=$cond;
8113: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
8114: =~/\Q$priv\E\&([^\:]*)/) {
8115: my $value = $1;
8116: if ($priv eq 'bre') {
8117: if ($noblockcheck) {
8118: $thisallowed.=$value;
8119: } else {
8120: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
8121: if (@blockers > 0) {
8122: $thisallowed = 'B';
8123: } else {
8124: $thisallowed.=$value;
8125: }
8126: }
8127: } else {
8128: $thisallowed.=$value;
8129: }
8130: $uri=$refuri;
8131: $statecond=$refstatecond;
8132: }
8133: }
8134: }
8135: }
8136: }
8137:
8138: #
8139: # Gathered now: all privileges that could apply, and condition number
8140: #
8141: #
8142: # Full or no access?
8143: #
8144:
8145: if ($thisallowed=~/F/) {
8146: return 'F';
8147: }
8148:
8149: unless ($thisallowed) {
8150: return '';
8151: }
8152:
8153: # Restrictions exist, deal with them
8154: #
8155: # C:according to course preferences
8156: # R:according to resource settings
8157: # L:unless locked
8158: # X:according to user session state
8159: #
8160:
8161: # Possibly locked functionality, check all courses
8162: # Locks might take effect only after 10 minutes cache expiration for other
8163: # courses, and 2 minutes for current course
8164:
8165: my $envkey;
8166: if ($thisallowed=~/L/) {
8167: foreach $envkey (keys(%env)) {
8168: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
8169: my $courseid=$2;
8170: my $roleid=$1.'.'.$2;
8171: $courseid=~s/^\///;
8172: my $expiretime=600;
8173: if ($env{'request.role'} eq $roleid) {
8174: $expiretime=120;
8175: }
8176: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
8177: my $prefix='course.'.$cdom.'_'.$cnum.'.';
8178: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
8179: &coursedescription($courseid,{'freshen_cache' => 1});
8180: }
8181: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
8182: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
8183: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
8184: &log($env{'user.domain'},$env{'user.name'},
8185: $env{'user.home'},
8186: 'Locked by res: '.$priv.' for '.$uri.' due to '.
8187: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8188: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8189: return '';
8190: }
8191: }
8192: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
8193: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
8194: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
8195: &log($env{'user.domain'},$env{'user.name'},
8196: $env{'user.home'},
8197: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
8198: $cdom.'/'.$cnum.'/'.$csec.' expire '.
8199: $env{$prefix.'priv.'.$priv.'.lock.expire'});
8200: return '';
8201: }
8202: }
8203: }
8204: }
8205: }
8206:
8207: #
8208: # Rest of the restrictions depend on selected course
8209: #
8210:
8211: unless ($env{'request.course.id'}) {
8212: if ($thisallowed eq 'A') {
8213: return 'A';
8214: } elsif ($thisallowed eq 'B') {
8215: return 'B';
8216: } else {
8217: return '1';
8218: }
8219: }
8220:
8221: #
8222: # Now user is definitely in a course
8223: #
8224:
8225:
8226: # Course preferences
8227:
8228: if ($thisallowed=~/C/) {
8229: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8230: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
8231: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
8232: =~/\Q$rolecode\E/) {
8233: if (($priv ne 'pch') && ($priv ne 'plc')) {
8234: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8235: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
8236: $env{'request.course.id'});
8237: }
8238: return '';
8239: }
8240:
8241: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
8242: =~/\Q$unamedom\E/) {
8243: if (($priv ne 'pch') && ($priv ne 'plc')) {
8244: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
8245: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
8246: $env{'request.course.id'});
8247: }
8248: return '';
8249: }
8250: }
8251:
8252: # Resource preferences
8253:
8254: if ($thisallowed=~/R/) {
8255: my $rolecode=(split(/\./,$env{'request.role'}))[0];
8256: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
8257: if (($priv ne 'pch') && ($priv ne 'plc')) {
8258: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
8259: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
8260: }
8261: return '';
8262: }
8263: }
8264:
8265: # Restricted by state or randomout?
8266:
8267: if ($thisallowed=~/X/) {
8268: if ($env{'acc.randomout'}) {
8269: if (!$symb) { $symb=&symbread($uri,1); }
8270: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
8271: return '';
8272: }
8273: }
8274: if (&condval($statecond)) {
8275: return '2';
8276: } else {
8277: return '';
8278: }
8279: }
8280:
8281: if ($thisallowed eq 'A') {
8282: return 'A';
8283: } elsif ($thisallowed eq 'B') {
8284: return 'B';
8285: }
8286: return 'F';
8287: }
8288:
8289: # ------------------------------------------- Check construction space access
8290:
8291: sub constructaccess {
8292: my ($url,$setpriv)=@_;
8293:
8294: # We do not allow editing of previous versions of files
8295: if ($url=~/\.(\d+)\.(\w+)$/) { return ''; }
8296:
8297: # Get username and domain from URL
8298: my ($ownername,$ownerdomain,$ownerhome);
8299:
8300: ($ownerdomain,$ownername) =
8301: ($url=~ m{^(?:\Q$perlvar{'lonDocRoot'}\E|)/priv/($match_domain)/($match_username)(?:/|$)});
8302:
8303: # The URL does not really point to any authorspace, forget it
8304: unless (($ownername) && ($ownerdomain)) { return ''; }
8305:
8306: # Now we need to see if the user has access to the authorspace of
8307: # $ownername at $ownerdomain
8308:
8309: if (($ownername eq $env{'user.name'}) && ($ownerdomain eq $env{'user.domain'})) {
8310: # Real author for this?
8311: $ownerhome = $env{'user.home'};
8312: if (exists($env{'user.priv.au./'.$ownerdomain.'/./'})) {
8313: return ($ownername,$ownerdomain,$ownerhome);
8314: }
8315: } else {
8316: # Co-author for this?
8317: if (exists($env{'user.priv.ca./'.$ownerdomain.'/'.$ownername.'./'}) ||
8318: exists($env{'user.priv.aa./'.$ownerdomain.'/'.$ownername.'./'}) ) {
8319: $ownerhome = &homeserver($ownername,$ownerdomain);
8320: return ($ownername,$ownerdomain,$ownerhome);
8321: }
8322: }
8323:
8324: # We don't have any access right now. If we are not possibly going to do anything about this,
8325: # we might as well leave
8326: unless ($setpriv) { return ''; }
8327:
8328: # Backdoor access?
8329: my $allowed=&allowed('eco',$ownerdomain);
8330: # Nope
8331: unless ($allowed) { return ''; }
8332: # Looks like we may have access, but could be locked by the owner of the construction space
8333: if ($allowed eq 'U') {
8334: my %blocked=&get('environment',['domcoord.author'],
8335: $ownerdomain,$ownername);
8336: # Is blocked by owner
8337: if ($blocked{'domcoord.author'} eq 'blocked') { return ''; }
8338: }
8339: if (($allowed eq 'F') || ($allowed eq 'U')) {
8340: # Grant temporary access
8341: my $then=$env{'user.login.time'};
8342: my $update=$env{'user.update.time'};
8343: if (!$update) { $update = $then; }
8344: my $refresh=$env{'user.refresh.time'};
8345: if (!$refresh) { $refresh = $update; }
8346: my $now = time;
8347: &check_adhoc_privs($ownerdomain,$ownername,$update,$refresh,
8348: $now,'ca','constructaccess');
8349: $ownerhome = &homeserver($ownername,$ownerdomain);
8350: return($ownername,$ownerdomain,$ownerhome);
8351: }
8352: # No business here
8353: return '';
8354: }
8355:
8356: # ----------------------------------------------------------- Content Blocking
8357:
8358: {
8359: # Caches for faster Course Contents display where content blocking
8360: # is in operation (i.e., interval param set) for timed quiz.
8361: #
8362: # User for whom data are being temporarily cached.
8363: my $cacheduser='';
8364: # Cached blockers for this user (a hash of blocking items).
8365: my %cachedblockers=();
8366: # When the data were last cached.
8367: my $cachedlast='';
8368:
8369: sub load_all_blockers {
8370: my ($uname,$udom,$blocks)=@_;
8371: if (($uname ne '') && ($udom ne '')) {
8372: if (($cacheduser eq $uname.':'.$udom) &&
8373: (abs($cachedlast-time)<5)) {
8374: return;
8375: }
8376: }
8377: $cachedlast=time;
8378: $cacheduser=$uname.':'.$udom;
8379: %cachedblockers = &get_commblock_resources($blocks);
8380: }
8381:
8382: sub get_comm_blocks {
8383: my ($cdom,$cnum) = @_;
8384: if ($cdom eq '' || $cnum eq '') {
8385: return unless ($env{'request.course.id'});
8386: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
8387: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
8388: }
8389: my %commblocks;
8390: my $hashid=$cdom.'_'.$cnum;
8391: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
8392: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
8393: %commblocks = %{$blocksref};
8394: } else {
8395: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
8396: my $cachetime = 600;
8397: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
8398: }
8399: return %commblocks;
8400: }
8401:
8402: sub get_commblock_resources {
8403: my ($blocks) = @_;
8404: my %blockers = ();
8405: return %blockers unless ($env{'request.course.id'});
8406: return %blockers if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8407: my %commblocks;
8408: if (ref($blocks) eq 'HASH') {
8409: %commblocks = %{$blocks};
8410: } else {
8411: %commblocks = &get_comm_blocks();
8412: }
8413: return %blockers unless (keys(%commblocks) > 0);
8414: my $navmap = Apache::lonnavmaps::navmap->new();
8415: return %blockers unless (ref($navmap));
8416: my $now = time;
8417: foreach my $block (keys(%commblocks)) {
8418: if ($block =~ /^(\d+)____(\d+)$/) {
8419: my ($start,$end) = ($1,$2);
8420: if ($start <= $now && $end >= $now) {
8421: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8422: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8423: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8424: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8425: $blockers{$block}{maps} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8426: }
8427: }
8428: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8429: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8430: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8431: }
8432: }
8433: }
8434: }
8435: }
8436: } elsif ($block =~ /^firstaccess____(.+)$/) {
8437: my $item = $1;
8438: my @to_test;
8439: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
8440: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
8441: my @interval;
8442: my $type = 'map';
8443: if ($item eq 'course') {
8444: $type = 'course';
8445: @interval=&EXT("resource.0.interval");
8446: } else {
8447: if ($item =~ /___\d+___/) {
8448: $type = 'resource';
8449: @interval=&EXT("resource.0.interval",$item);
8450: if (ref($navmap)) {
8451: my $res = $navmap->getBySymb($item);
8452: push(@to_test,$res);
8453: }
8454: } else {
8455: my $mapsymb = &symbread($item,1);
8456: if ($mapsymb) {
8457: if (ref($navmap)) {
8458: my $mapres = $navmap->getBySymb($mapsymb);
8459: @to_test = $mapres->retrieveResources($mapres,undef,0,0,0,1);
8460: foreach my $res (@to_test) {
8461: my $symb = $res->symb();
8462: next if ($symb eq $mapsymb);
8463: if ($symb ne '') {
8464: @interval=&EXT("resource.0.interval",$symb);
8465: if ($interval[1] eq 'map') {
8466: last;
8467: }
8468: }
8469: }
8470: }
8471: }
8472: }
8473: }
8474: if ($interval[0] =~ /^\d+$/) {
8475: my $first_access;
8476: if ($type eq 'resource') {
8477: $first_access=&get_first_access($interval[1],$item);
8478: } elsif ($type eq 'map') {
8479: $first_access=&get_first_access($interval[1],undef,$item);
8480: } else {
8481: $first_access=&get_first_access($interval[1]);
8482: }
8483: if ($first_access) {
8484: my $timesup = $first_access+$interval[0];
8485: if ($timesup > $now) {
8486: my $activeblock;
8487: foreach my $res (@to_test) {
8488: if ($res->answerable()) {
8489: $activeblock = 1;
8490: last;
8491: }
8492: }
8493: if ($activeblock) {
8494: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
8495: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'maps'}})) {
8496: $blockers{$block}{'maps'} = $commblocks{$block}{'blocks'}{'docs'}{'maps'};
8497: }
8498: }
8499: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
8500: if (keys(%{$commblocks{$block}{'blocks'}{'docs'}{'resources'}})) {
8501: $blockers{$block}{'resources'} = $commblocks{$block}{'blocks'}{'docs'}{'resources'};
8502: }
8503: }
8504: }
8505: }
8506: }
8507: }
8508: }
8509: }
8510: }
8511: }
8512: return %blockers;
8513: }
8514:
8515: sub has_comm_blocking {
8516: my ($priv,$symb,$uri,$blocks) = @_;
8517: my @blockers;
8518: return unless ($env{'request.course.id'});
8519: return unless ($priv eq 'bre');
8520: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
8521: return if ($env{'request.state'} eq 'construct');
8522: &load_all_blockers($env{'user.name'},$env{'user.domain'},$blocks);
8523: return unless (keys(%cachedblockers) > 0);
8524: my (%possibles,@symbs);
8525: if (!$symb) {
8526: $symb = &symbread($uri,1,1,1,\%possibles);
8527: }
8528: if ($symb) {
8529: @symbs = ($symb);
8530: } elsif (keys(%possibles)) {
8531: @symbs = keys(%possibles);
8532: }
8533: my $noblock;
8534: foreach my $symb (@symbs) {
8535: last if ($noblock);
8536: my ($map,$resid,$resurl)=&decode_symb($symb);
8537: foreach my $block (keys(%cachedblockers)) {
8538: if ($block =~ /^firstaccess____(.+)$/) {
8539: my $item = $1;
8540: if (($item eq $map) || ($item eq $symb)) {
8541: $noblock = 1;
8542: last;
8543: }
8544: }
8545: if (ref($cachedblockers{$block}) eq 'HASH') {
8546: if (ref($cachedblockers{$block}{'resources'}) eq 'HASH') {
8547: if ($cachedblockers{$block}{'resources'}{$symb}) {
8548: unless (grep(/^\Q$block\E$/,@blockers)) {
8549: push(@blockers,$block);
8550: }
8551: }
8552: }
8553: }
8554: if (ref($cachedblockers{$block}{'maps'}) eq 'HASH') {
8555: if ($cachedblockers{$block}{'maps'}{$map}) {
8556: unless (grep(/^\Q$block\E$/,@blockers)) {
8557: push(@blockers,$block);
8558: }
8559: }
8560: }
8561: }
8562: }
8563: return if ($noblock);
8564: return @blockers;
8565: }
8566: }
8567:
8568: # -------------------------------- Deversion and split uri into path an filename
8569:
8570: #
8571: # Removes the version from a URI and
8572: # splits it in to its filename and path to the filename.
8573: # Seems like File::Basename could have done this more clearly.
8574: # Parameters:
8575: # $uri - input URI
8576: # Returns:
8577: # Two element list consisting of
8578: # $pathname - the URI up to and excluding the trailing /
8579: # $filename - The part of the URI following the last /
8580: # NOTE:
8581: # Another realization of this is simply:
8582: # use File::Basename;
8583: # ...
8584: # $uri = shift;
8585: # $filename = basename($uri);
8586: # $path = dirname($uri);
8587: # return ($filename, $path);
8588: #
8589: # The implementation below is probably faster however.
8590: #
8591: sub split_uri_for_cond {
8592: my $uri=&deversion(&declutter(shift));
8593: my @uriparts=split(/\//,$uri);
8594: my $filename=pop(@uriparts);
8595: my $pathname=join('/',@uriparts);
8596: return ($pathname,$filename);
8597: }
8598: # --------------------------------------------------- Is a resource on the map?
8599:
8600: sub is_on_map {
8601: my ($pathname,$filename) = &split_uri_for_cond(shift);
8602: #Trying to find the conditional for the file
8603: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
8604: /\&\Q$filename\E\:([\d\|]+)\&/);
8605: if ($match) {
8606: return (1,$1);
8607: } else {
8608: return (0,0);
8609: }
8610: }
8611:
8612: # --------------------------------------------------------- Get symb from alias
8613:
8614: sub get_symb_from_alias {
8615: my $symb=shift;
8616: my ($map,$resid,$url)=&decode_symb($symb);
8617: # Already is a symb
8618: if ($url) { return $symb; }
8619: # Must be an alias
8620: my $aliassymb='';
8621: my %bighash;
8622: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8623: &GDBM_READER(),0640)) {
8624: my $rid=$bighash{'mapalias_'.$symb};
8625: if ($rid) {
8626: my ($mapid,$resid)=split(/\./,$rid);
8627: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
8628: $resid,$bighash{'src_'.$rid});
8629: }
8630: untie %bighash;
8631: }
8632: return $aliassymb;
8633: }
8634:
8635: # ----------------------------------------------------------------- Define Role
8636:
8637: sub definerole {
8638: if (allowed('mcr','/')) {
8639: my ($rolename,$sysrole,$domrole,$courole,$uname,$udom)=@_;
8640: foreach my $role (split(':',$sysrole)) {
8641: my ($crole,$cqual)=split(/\&/,$role);
8642: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
8643: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
8644: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8645: return "refused:s:$crole&$cqual";
8646: }
8647: }
8648: }
8649: foreach my $role (split(':',$domrole)) {
8650: my ($crole,$cqual)=split(/\&/,$role);
8651: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
8652: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
8653: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
8654: return "refused:d:$crole&$cqual";
8655: }
8656: }
8657: }
8658: foreach my $role (split(':',$courole)) {
8659: my ($crole,$cqual)=split(/\&/,$role);
8660: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
8661: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
8662: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
8663: return "refused:c:$crole&$cqual";
8664: }
8665: }
8666: }
8667: my $uhome;
8668: if (($uname ne '') && ($udom ne '')) {
8669: $uhome = &homeserver($uname,$udom);
8670: return $uhome if ($uhome eq 'no_host');
8671: } else {
8672: $uname = $env{'user.name'};
8673: $udom = $env{'user.domain'};
8674: $uhome = $env{'user.home'};
8675: }
8676: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
8677: "$udom:$uname:rolesdef_$rolename=".
8678: escape($sysrole.'_'.$domrole.'_'.$courole);
8679: return reply($command,$uhome);
8680: } else {
8681: return 'refused';
8682: }
8683: }
8684:
8685: # ---------------- Make a metadata query against the network of library servers
8686:
8687: sub metadata_query {
8688: my ($query,$custom,$customshow,$server_array,$domains_hash)=@_;
8689: my %rhash;
8690: my %libserv = &all_library();
8691: my @server_list = (defined($server_array) ? @$server_array
8692: : keys(%libserv) );
8693: for my $server (@server_list) {
8694: my $domains = '';
8695: if (ref($domains_hash) eq 'HASH') {
8696: $domains = $domains_hash->{$server};
8697: }
8698: unless ($custom or $customshow) {
8699: my $reply=&reply("querysend:".&escape($query).':::'.&escape($domains),$server);
8700: $rhash{$server}=$reply;
8701: }
8702: else {
8703: my $reply=&reply("querysend:".&escape($query).':'.
8704: &escape($custom).':'.&escape($customshow).':'.&escape($domains),
8705: $server);
8706: $rhash{$server}=$reply;
8707: }
8708: }
8709: return \%rhash;
8710: }
8711:
8712: # ----------------------------------------- Send log queries and wait for reply
8713:
8714: sub log_query {
8715: my ($uname,$udom,$query,%filters)=@_;
8716: my $uhome=&homeserver($uname,$udom);
8717: if ($uhome eq 'no_host') { return 'error: no_host'; }
8718: my $uhost=&hostname($uhome);
8719: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
8720: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
8721: $uhome);
8722: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
8723: return get_query_reply($queryid);
8724: }
8725:
8726: # -------------------------- Update MySQL table for portfolio file
8727:
8728: sub update_portfolio_table {
8729: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
8730: if ($group ne '') {
8731: $file_name =~s /^\Q$group\E//;
8732: }
8733: my $homeserver = &homeserver($uname,$udom);
8734: my $queryid=
8735: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
8736: ':'.&escape($file_name).':'.$action,$homeserver);
8737: my $reply = &get_query_reply($queryid);
8738: return $reply;
8739: }
8740:
8741: # -------------------------- Update MySQL allusers table
8742:
8743: sub update_allusers_table {
8744: my ($uname,$udom,$names) = @_;
8745: my $homeserver = &homeserver($uname,$udom);
8746: my $queryid=
8747: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
8748: 'lastname='.&escape($names->{'lastname'}).'%%'.
8749: 'firstname='.&escape($names->{'firstname'}).'%%'.
8750: 'middlename='.&escape($names->{'middlename'}).'%%'.
8751: 'generation='.&escape($names->{'generation'}).'%%'.
8752: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
8753: 'id='.&escape($names->{'id'}),$homeserver);
8754: return;
8755: }
8756:
8757: # ------- Request retrieval of institutional classlists for course(s)
8758:
8759: sub fetch_enrollment_query {
8760: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
8761: my ($homeserver,$sleep,$loopmax);
8762: my $maxtries = 1;
8763: if ($context eq 'automated') {
8764: $homeserver = $perlvar{'lonHostID'};
8765: $sleep = 2;
8766: $loopmax = 100;
8767: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
8768: } else {
8769: $homeserver = &homeserver($cnum,$dom);
8770: }
8771: my $host=&hostname($homeserver);
8772: my $cmd = '';
8773: foreach my $affiliate (keys(%{$affiliatesref})) {
8774: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
8775: }
8776: $cmd =~ s/%%$//;
8777: $cmd = &escape($cmd);
8778: my $query = 'fetchenrollment';
8779: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
8780: unless ($queryid=~/^\Q$host\E\_/) {
8781: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
8782: return 'error: '.$queryid;
8783: }
8784: my $reply = &get_query_reply($queryid,$sleep,$loopmax);
8785: my $tries = 1;
8786: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
8787: $reply = &get_query_reply($queryid,$sleep,$loopmax);
8788: $tries ++;
8789: }
8790: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
8791: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
8792: } else {
8793: my @responses = split(/:/,$reply);
8794: if (grep { $_ eq $homeserver } ¤t_machine_ids()) {
8795: foreach my $line (@responses) {
8796: my ($key,$value) = split(/=/,$line,2);
8797: $$replyref{$key} = $value;
8798: }
8799: } else {
8800: my $pathname = LONCAPA::tempdir();
8801: foreach my $line (@responses) {
8802: my ($key,$value) = split(/=/,$line);
8803: $$replyref{$key} = $value;
8804: if ($value > 0) {
8805: foreach my $item (@{$$affiliatesref{$key}}) {
8806: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
8807: my $destname = $pathname.'/'.$filename;
8808: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
8809: if ($xml_classlist =~ /^error/) {
8810: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
8811: } else {
8812: if ( open(FILE,">",$destname) ) {
8813: print FILE &unescape($xml_classlist);
8814: close(FILE);
8815: } else {
8816: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
8817: }
8818: }
8819: }
8820: }
8821: }
8822: }
8823: return 'ok';
8824: }
8825: return 'error';
8826: }
8827:
8828: sub get_query_reply {
8829: my ($queryid,$sleep,$loopmax) = @_;
8830: if (($sleep eq '') || ($sleep !~ /^\d+\.?\d*$/)) {
8831: $sleep = 0.2;
8832: }
8833: if (($loopmax eq '') || ($loopmax =~ /\D/)) {
8834: $loopmax = 100;
8835: }
8836: my $replyfile=LONCAPA::tempdir().$queryid;
8837: my $reply='';
8838: for (1..$loopmax) {
8839: sleep($sleep);
8840: if (-e $replyfile.'.end') {
8841: if (open(my $fh,"<",$replyfile)) {
8842: $reply = join('',<$fh>);
8843: close($fh);
8844: } else { return 'error: reply_file_error'; }
8845: return &unescape($reply);
8846: }
8847: }
8848: return 'timeout:'.$queryid;
8849: }
8850:
8851: sub courselog_query {
8852: #
8853: # possible filters:
8854: # url: url or symb
8855: # username
8856: # domain
8857: # action: view, submit, grade
8858: # start: timestamp
8859: # end: timestamp
8860: #
8861: my (%filters)=@_;
8862: unless ($env{'request.course.id'}) { return 'no_course'; }
8863: if ($filters{'url'}) {
8864: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
8865: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
8866: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
8867: }
8868: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
8869: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
8870: return &log_query($cname,$cdom,'courselog',%filters);
8871: }
8872:
8873: sub userlog_query {
8874: #
8875: # possible filters:
8876: # action: log check role
8877: # start: timestamp
8878: # end: timestamp
8879: #
8880: my ($uname,$udom,%filters)=@_;
8881: return &log_query($uname,$udom,'userlog',%filters);
8882: }
8883:
8884: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
8885:
8886: sub auto_run {
8887: my ($cnum,$cdom) = @_;
8888: my $response = 0;
8889: my $settings;
8890: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
8891: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
8892: $settings = $domconfig{'autoenroll'};
8893: if ($settings->{'run'} eq '1') {
8894: $response = 1;
8895: }
8896: } else {
8897: my $homeserver;
8898: if (&is_course($cdom,$cnum)) {
8899: $homeserver = &homeserver($cnum,$cdom);
8900: } else {
8901: $homeserver = &domain($cdom,'primary');
8902: }
8903: if ($homeserver ne 'no_host') {
8904: $response = &reply('autorun:'.$cdom,$homeserver);
8905: }
8906: }
8907: return $response;
8908: }
8909:
8910: sub auto_get_sections {
8911: my ($cnum,$cdom,$inst_coursecode) = @_;
8912: my $homeserver;
8913: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8914: $homeserver = &homeserver($cnum,$cdom);
8915: }
8916: if (!defined($homeserver)) {
8917: if ($cdom =~ /^$match_domain$/) {
8918: $homeserver = &domain($cdom,'primary');
8919: }
8920: }
8921: my @secs;
8922: if (defined($homeserver)) {
8923: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
8924: unless ($response eq 'refused') {
8925: @secs = split(/:/,$response);
8926: }
8927: }
8928: return @secs;
8929: }
8930:
8931: sub auto_new_course {
8932: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
8933: my $homeserver = &homeserver($cnum,$cdom);
8934: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
8935: return $response;
8936: }
8937:
8938: sub auto_validate_courseID {
8939: my ($cnum,$cdom,$inst_course_id) = @_;
8940: my $homeserver = &homeserver($cnum,$cdom);
8941: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
8942: return $response;
8943: }
8944:
8945: sub auto_validate_instcode {
8946: my ($cnum,$cdom,$instcode,$owner) = @_;
8947: my ($homeserver,$response);
8948: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8949: $homeserver = &homeserver($cnum,$cdom);
8950: }
8951: if (!defined($homeserver)) {
8952: if ($cdom =~ /^$match_domain$/) {
8953: $homeserver = &domain($cdom,'primary');
8954: }
8955: }
8956: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
8957: &escape($instcode).':'.&escape($owner),$homeserver));
8958: my ($outcome,$description,$defaultcredits) = map { &unescape($_); } split('&',$response,3);
8959: return ($outcome,$description,$defaultcredits);
8960: }
8961:
8962: sub auto_create_password {
8963: my ($cnum,$cdom,$authparam,$udom) = @_;
8964: my ($homeserver,$response);
8965: my $create_passwd = 0;
8966: my $authchk = '';
8967: if ($udom =~ /^$match_domain$/) {
8968: $homeserver = &domain($udom,'primary');
8969: }
8970: if ($homeserver eq '') {
8971: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
8972: $homeserver = &homeserver($cnum,$cdom);
8973: }
8974: }
8975: if ($homeserver eq '') {
8976: $authchk = 'nodomain';
8977: } else {
8978: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
8979: if ($response eq 'refused') {
8980: $authchk = 'refused';
8981: } else {
8982: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
8983: }
8984: }
8985: return ($authparam,$create_passwd,$authchk);
8986: }
8987:
8988: sub auto_photo_permission {
8989: my ($cnum,$cdom,$students) = @_;
8990: my $homeserver = &homeserver($cnum,$cdom);
8991: my ($outcome,$perm_reqd,$conditions) =
8992: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
8993: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
8994: return (undef,undef);
8995: }
8996: return ($outcome,$perm_reqd,$conditions);
8997: }
8998:
8999: sub auto_checkphotos {
9000: my ($uname,$udom,$pid) = @_;
9001: my $homeserver = &homeserver($uname,$udom);
9002: my ($result,$resulttype);
9003: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
9004: &escape($uname).':'.&escape($pid),
9005: $homeserver));
9006: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9007: return (undef,undef);
9008: }
9009: if ($outcome) {
9010: ($result,$resulttype) = split(/:/,$outcome);
9011: }
9012: return ($result,$resulttype);
9013: }
9014:
9015: sub auto_photochoice {
9016: my ($cnum,$cdom) = @_;
9017: my $homeserver = &homeserver($cnum,$cdom);
9018: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
9019: &escape($cdom),
9020: $homeserver)));
9021: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
9022: return (undef,undef);
9023: }
9024: return ($update,$comment);
9025: }
9026:
9027: sub auto_photoupdate {
9028: my ($affiliatesref,$dom,$cnum,$photo) = @_;
9029: my $homeserver = &homeserver($cnum,$dom);
9030: my $host=&hostname($homeserver);
9031: my $cmd = '';
9032: my $maxtries = 1;
9033: foreach my $affiliate (keys(%{$affiliatesref})) {
9034: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
9035: }
9036: $cmd =~ s/%%$//;
9037: $cmd = &escape($cmd);
9038: my $query = 'institutionalphotos';
9039: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
9040: unless ($queryid=~/^\Q$host\E\_/) {
9041: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
9042: return 'error: '.$queryid;
9043: }
9044: my $reply = &get_query_reply($queryid);
9045: my $tries = 1;
9046: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
9047: $reply = &get_query_reply($queryid);
9048: $tries ++;
9049: }
9050: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
9051: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
9052: } else {
9053: my @responses = split(/:/,$reply);
9054: my $outcome = shift(@responses);
9055: foreach my $item (@responses) {
9056: my ($key,$value) = split(/=/,$item);
9057: $$photo{$key} = $value;
9058: }
9059: return $outcome;
9060: }
9061: return 'error';
9062: }
9063:
9064: sub auto_instcode_format {
9065: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
9066: $cat_order) = @_;
9067: my $courses = '';
9068: my @homeservers;
9069: if ($caller eq 'global') {
9070: my %servers = &get_servers($codedom,'library');
9071: foreach my $tryserver (keys(%servers)) {
9072: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9073: push(@homeservers,$tryserver);
9074: }
9075: }
9076: } elsif ($caller eq 'requests') {
9077: if ($codedom =~ /^$match_domain$/) {
9078: my $chome = &domain($codedom,'primary');
9079: unless ($chome eq 'no_host') {
9080: push(@homeservers,$chome);
9081: }
9082: }
9083: } else {
9084: push(@homeservers,&homeserver($caller,$codedom));
9085: }
9086: foreach my $code (keys(%{$instcodes})) {
9087: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
9088: }
9089: chop($courses);
9090: my $ok_response = 0;
9091: my $response;
9092: while (@homeservers > 0 && $ok_response == 0) {
9093: my $server = shift(@homeservers);
9094: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
9095: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
9096: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
9097: split(/:/,$response);
9098: %{$codes} = (%{$codes},&str2hash($codes_str));
9099: push(@{$codetitles},&str2array($codetitles_str));
9100: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
9101: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
9102: $ok_response = 1;
9103: }
9104: }
9105: if ($ok_response) {
9106: return 'ok';
9107: } else {
9108: return $response;
9109: }
9110: }
9111:
9112: sub auto_instcode_defaults {
9113: my ($domain,$returnhash,$code_order) = @_;
9114: my @homeservers;
9115:
9116: my %servers = &get_servers($domain,'library');
9117: foreach my $tryserver (keys(%servers)) {
9118: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9119: push(@homeservers,$tryserver);
9120: }
9121: }
9122:
9123: my $response;
9124: foreach my $server (@homeservers) {
9125: $response=&reply('autoinstcodedefaults:'.$domain,$server);
9126: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9127:
9128: foreach my $pair (split(/\&/,$response)) {
9129: my ($name,$value)=split(/\=/,$pair);
9130: if ($name eq 'code_order') {
9131: @{$code_order} = split(/\&/,&unescape($value));
9132: } else {
9133: $returnhash->{&unescape($name)}=&unescape($value);
9134: }
9135: }
9136: return 'ok';
9137: }
9138:
9139: return $response;
9140: }
9141:
9142: sub auto_possible_instcodes {
9143: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
9144: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
9145: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9146: return;
9147: }
9148: my (@homeservers,$uhome);
9149: if (defined(&domain($domain,'primary'))) {
9150: $uhome=&domain($domain,'primary');
9151: push(@homeservers,&domain($domain,'primary'));
9152: } else {
9153: my %servers = &get_servers($domain,'library');
9154: foreach my $tryserver (keys(%servers)) {
9155: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
9156: push(@homeservers,$tryserver);
9157: }
9158: }
9159: }
9160: my $response;
9161: foreach my $server (@homeservers) {
9162: $response=&reply('autopossibleinstcodes:'.$domain,$server);
9163: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
9164: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
9165: split(':',$response);
9166: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
9167: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
9168: foreach my $item (split('&',$cat_title)) {
9169: my ($name,$value)=split('=',$item);
9170: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
9171: }
9172: foreach my $item (split('&',$cat_order)) {
9173: my ($name,$value)=split('=',$item);
9174: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
9175: }
9176: return 'ok';
9177: }
9178: return $response;
9179: }
9180:
9181: sub auto_courserequest_checks {
9182: my ($dom) = @_;
9183: my ($homeserver,%validations);
9184: if ($dom =~ /^$match_domain$/) {
9185: $homeserver = &domain($dom,'primary');
9186: }
9187: unless ($homeserver eq 'no_host') {
9188: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
9189: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9190: my @items = split(/&/,$response);
9191: foreach my $item (@items) {
9192: my ($key,$value) = split('=',$item);
9193: $validations{&unescape($key)} = &thaw_unescape($value);
9194: }
9195: }
9196: }
9197: return %validations;
9198: }
9199:
9200: sub auto_courserequest_validation {
9201: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist,$custominfo) = @_;
9202: my ($homeserver,$response);
9203: if ($dom =~ /^$match_domain$/) {
9204: $homeserver = &domain($dom,'primary');
9205: }
9206: unless ($homeserver eq 'no_host') {
9207: my $customdata;
9208: if (ref($custominfo) eq 'HASH') {
9209: $customdata = &freeze_escape($custominfo);
9210: }
9211: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
9212: ':'.&escape($crstype).':'.&escape($inststatuslist).
9213: ':'.&escape($instcode).':'.&escape($instseclist).':'.
9214: $customdata,$homeserver));
9215: }
9216: return $response;
9217: }
9218:
9219: sub auto_validate_class_sec {
9220: my ($cdom,$cnum,$owners,$inst_class) = @_;
9221: my $homeserver = &homeserver($cnum,$cdom);
9222: my $ownerlist;
9223: if (ref($owners) eq 'ARRAY') {
9224: $ownerlist = join(',',@{$owners});
9225: } else {
9226: $ownerlist = $owners;
9227: }
9228: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
9229: &escape($ownerlist).':'.$cdom,$homeserver);
9230: return $response;
9231: }
9232:
9233: sub auto_validate_instclasses {
9234: my ($cdom,$cnum,$owners,$classesref) = @_;
9235: my ($homeserver,%validations);
9236: $homeserver = &homeserver($cnum,$cdom);
9237: unless ($homeserver eq 'no_host') {
9238: my $ownerlist;
9239: if (ref($owners) eq 'ARRAY') {
9240: $ownerlist = join(',',@{$owners});
9241: } else {
9242: $ownerlist = $owners;
9243: }
9244: if (ref($classesref) eq 'HASH') {
9245: my $classes = &freeze_escape($classesref);
9246: my $response=&reply('autovalidateinstclasses:'.&escape($ownerlist).
9247: ':'.$cdom.':'.$classes,$homeserver);
9248: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9249: my @items = split(/&/,$response);
9250: foreach my $item (@items) {
9251: my ($key,$value) = split('=',$item);
9252: $validations{&unescape($key)} = &thaw_unescape($value);
9253: }
9254: }
9255: }
9256: }
9257: return %validations;
9258: }
9259:
9260: sub auto_crsreq_update {
9261: my ($cdom,$cnum,$crstype,$action,$ownername,$ownerdomain,$fullname,$title,
9262: $code,$accessstart,$accessend,$inbound) = @_;
9263: my ($homeserver,%crsreqresponse);
9264: if ($cdom =~ /^$match_domain$/) {
9265: $homeserver = &domain($cdom,'primary');
9266: }
9267: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9268: my $info;
9269: if (ref($inbound) eq 'HASH') {
9270: $info = &freeze_escape($inbound);
9271: }
9272: my $response=&reply('autocrsrequpdate:'.$cdom.':'.$cnum.':'.&escape($crstype).
9273: ':'.&escape($action).':'.&escape($ownername).':'.
9274: &escape($ownerdomain).':'.&escape($fullname).':'.
9275: &escape($title).':'.&escape($code).':'.
9276: &escape($accessstart).':'.&escape($accessend).':'.$info,$homeserver);
9277: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
9278: my @items = split(/&/,$response);
9279: foreach my $item (@items) {
9280: my ($key,$value) = split('=',$item);
9281: $crsreqresponse{&unescape($key)} = &thaw_unescape($value);
9282: }
9283: }
9284: }
9285: return \%crsreqresponse;
9286: }
9287:
9288: sub auto_export_grades {
9289: my ($cdom,$cnum,$inforef,$gradesref) = @_;
9290: my ($homeserver,%exportresponse);
9291: if ($cdom =~ /^$match_domain$/) {
9292: $homeserver = &domain($cdom,'primary');
9293: }
9294: unless (($homeserver eq 'no_host') || ($homeserver eq '')) {
9295: my $info;
9296: if (ref($inforef) eq 'HASH') {
9297: $info = &freeze_escape($inforef);
9298: }
9299: if (ref($gradesref) eq 'HASH') {
9300: my $grades = &freeze_escape($gradesref);
9301: my $response=&reply('encrypt:autoexportgrades:'.$cdom.':'.$cnum.':'.
9302: $info.':'.$grades,$homeserver);
9303: unless ($response =~ /(con_lost|error|no_such_host|refused|unknown_command)/) {
9304: my @items = split(/&/,$response);
9305: foreach my $item (@items) {
9306: my ($key,$value) = split('=',$item);
9307: $exportresponse{&unescape($key)} = &thaw_unescape($value);
9308: }
9309: }
9310: }
9311: }
9312: return \%exportresponse;
9313: }
9314:
9315: sub check_instcode_cloning {
9316: my ($codedefaults,$code_order,$cloner,$clonefromcode,$clonetocode) = @_;
9317: unless ((ref($codedefaults) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
9318: return;
9319: }
9320: my $canclone;
9321: if (@{$code_order} > 0) {
9322: my $instcoderegexp ='^';
9323: my @clonecodes = split(/\&/,$cloner);
9324: foreach my $item (@{$code_order}) {
9325: if (grep(/^\Q$item\E=/,@clonecodes)) {
9326: foreach my $pair (@clonecodes) {
9327: my ($key,$val) = split(/\=/,$pair,2);
9328: $val = &unescape($val);
9329: if ($key eq $item) {
9330: $instcoderegexp .= '('.$val.')';
9331: last;
9332: }
9333: }
9334: } else {
9335: $instcoderegexp .= $codedefaults->{$item};
9336: }
9337: }
9338: $instcoderegexp .= '$';
9339: my (@from,@to);
9340: eval {
9341: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9342: (@to) = ($clonetocode =~ /$instcoderegexp/);
9343: };
9344: if ((@from > 0) && (@to > 0)) {
9345: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9346: if (!@diffs) {
9347: $canclone = 1;
9348: }
9349: }
9350: }
9351: return $canclone;
9352: }
9353:
9354: sub default_instcode_cloning {
9355: my ($clonedom,$domdefclone,$clonefromcode,$clonetocode,$codedefaultsref,$codeorderref) = @_;
9356: my (%codedefaults,@code_order,$canclone);
9357: if ((ref($codedefaultsref) eq 'HASH') && (ref($codeorderref) eq 'ARRAY')) {
9358: %codedefaults = %{$codedefaultsref};
9359: @code_order = @{$codeorderref};
9360: } elsif ($clonedom) {
9361: &auto_instcode_defaults($clonedom,\%codedefaults,\@code_order);
9362: }
9363: if (($domdefclone) && (@code_order)) {
9364: my @clonecodes = split(/\+/,$domdefclone);
9365: my $instcoderegexp ='^';
9366: foreach my $item (@code_order) {
9367: if (grep(/^\Q$item\E$/,@clonecodes)) {
9368: $instcoderegexp .= '('.$codedefaults{$item}.')';
9369: } else {
9370: $instcoderegexp .= $codedefaults{$item};
9371: }
9372: }
9373: $instcoderegexp .= '$';
9374: my (@from,@to);
9375: eval {
9376: (@from) = ($clonefromcode =~ /$instcoderegexp/);
9377: (@to) = ($clonetocode =~ /$instcoderegexp/);
9378: };
9379: if ((@from > 0) && (@to > 0)) {
9380: my @diffs = &Apache::loncommon::compare_arrays(\@from,\@to);
9381: if (!@diffs) {
9382: $canclone = 1;
9383: }
9384: }
9385: }
9386: return $canclone;
9387: }
9388:
9389: # ------------------------------------------------------- Course Group routines
9390:
9391: sub get_coursegroups {
9392: my ($cdom,$cnum,$group,$namespace) = @_;
9393: return(&dump($namespace,$cdom,$cnum,$group));
9394: }
9395:
9396: sub modify_coursegroup {
9397: my ($cdom,$cnum,$groupsettings) = @_;
9398: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
9399: }
9400:
9401: sub toggle_coursegroup_status {
9402: my ($cdom,$cnum,$group,$action) = @_;
9403: my ($from_namespace,$to_namespace);
9404: if ($action eq 'delete') {
9405: $from_namespace = 'coursegroups';
9406: $to_namespace = 'deleted_groups';
9407: } else {
9408: $from_namespace = 'deleted_groups';
9409: $to_namespace = 'coursegroups';
9410: }
9411: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
9412: if (my $tmp = &error(%curr_group)) {
9413: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
9414: return ('read error',$tmp);
9415: } else {
9416: my %savedsettings = %curr_group;
9417: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
9418: my $deloutcome;
9419: if ($result eq 'ok') {
9420: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
9421: } else {
9422: return ('write error',$result);
9423: }
9424: if ($deloutcome eq 'ok') {
9425: return 'ok';
9426: } else {
9427: return ('delete error',$deloutcome);
9428: }
9429: }
9430: }
9431:
9432: sub modify_group_roles {
9433: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
9434: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
9435: my $role = 'gr/'.&escape($userprivs);
9436: my ($uname,$udom) = split(/:/,$user);
9437: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
9438: if ($result eq 'ok') {
9439: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
9440: }
9441: return $result;
9442: }
9443:
9444: sub modify_coursegroup_membership {
9445: my ($cdom,$cnum,$membership) = @_;
9446: my $result = &put('groupmembership',$membership,$cdom,$cnum);
9447: return $result;
9448: }
9449:
9450: sub get_active_groups {
9451: my ($udom,$uname,$cdom,$cnum) = @_;
9452: my $now = time;
9453: my %groups = ();
9454: foreach my $key (keys(%env)) {
9455: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
9456: my ($start,$end) = split(/\./,$env{$key});
9457: if (($end!=0) && ($end<$now)) { next; }
9458: if (($start!=0) && ($start>$now)) { next; }
9459: if ($1 eq $cdom && $2 eq $cnum) {
9460: $groups{$3} = $env{$key} ;
9461: }
9462: }
9463: }
9464: return %groups;
9465: }
9466:
9467: sub get_group_membership {
9468: my ($cdom,$cnum,$group) = @_;
9469: return(&dump('groupmembership',$cdom,$cnum,$group));
9470: }
9471:
9472: sub get_users_groups {
9473: my ($udom,$uname,$courseid) = @_;
9474: my @usersgroups;
9475: my $cachetime=1800;
9476:
9477: my $hashid="$udom:$uname:$courseid";
9478: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
9479: if (defined($cached)) {
9480: @usersgroups = split(/:/,$grouplist);
9481: } else {
9482: $grouplist = '';
9483: my $courseurl = &courseid_to_courseurl($courseid);
9484: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
9485: my $access_end = $env{'course.'.$courseid.
9486: '.default_enrollment_end_date'};
9487: my $now = time;
9488: foreach my $key (keys(%roleshash)) {
9489: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
9490: my $group = $1;
9491: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
9492: my $start = $2;
9493: my $end = $1;
9494: if ($start == -1) { next; } # deleted from group
9495: if (($start!=0) && ($start>$now)) { next; }
9496: if (($end!=0) && ($end<$now)) {
9497: if ($access_end && $access_end < $now) {
9498: if ($access_end - $end < 86400) {
9499: push(@usersgroups,$group);
9500: }
9501: }
9502: next;
9503: }
9504: push(@usersgroups,$group);
9505: }
9506: }
9507: }
9508: @usersgroups = &sort_course_groups($courseid,@usersgroups);
9509: $grouplist = join(':',@usersgroups);
9510: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
9511: }
9512: return @usersgroups;
9513: }
9514:
9515: sub devalidate_getgroups_cache {
9516: my ($udom,$uname,$cdom,$cnum)=@_;
9517: my $courseid = $cdom.'_'.$cnum;
9518:
9519: my $hashid="$udom:$uname:$courseid";
9520: &devalidate_cache_new('getgroups',$hashid);
9521: }
9522:
9523: # ------------------------------------------------------------------ Plain Text
9524:
9525: sub plaintext {
9526: my ($short,$type,$cid,$forcedefault) = @_;
9527: if ($short =~ m{^cr/}) {
9528: return (split('/',$short))[-1];
9529: }
9530: if (!defined($cid)) {
9531: $cid = $env{'request.course.id'};
9532: }
9533: my %rolenames = (
9534: Course => 'std',
9535: Community => 'alt1',
9536: );
9537: if ($cid ne '') {
9538: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
9539: unless ($forcedefault) {
9540: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
9541: &Apache::lonlocal::mt_escape(\$roletext);
9542: return &Apache::lonlocal::mt($roletext);
9543: }
9544: }
9545: }
9546: if ((defined($type)) && (defined($rolenames{$type})) &&
9547: (defined($rolenames{$type})) &&
9548: (defined($prp{$short}{$rolenames{$type}}))) {
9549: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
9550: } elsif ($cid ne '') {
9551: my $crstype = $env{'course.'.$cid.'.type'};
9552: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
9553: (defined($prp{$short}{$rolenames{$crstype}}))) {
9554: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
9555: }
9556: }
9557: return &Apache::lonlocal::mt($prp{$short}{'std'});
9558: }
9559:
9560: # ----------------------------------------------------------------- Assign Role
9561:
9562: sub assignrole {
9563: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
9564: $context)=@_;
9565: my $mrole;
9566: if ($role =~ /^cr\//) {
9567: my $cwosec=$url;
9568: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9569: unless (&allowed('ccr',$cwosec)) {
9570: my $refused = 1;
9571: if ($context eq 'requestcourses') {
9572: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
9573: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
9574: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
9575: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9576: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9577: if ($crsenv{'internal.courseowner'} eq
9578: $env{'user.name'}.':'.$env{'user.domain'}) {
9579: $refused = '';
9580: }
9581: }
9582: }
9583: }
9584: }
9585: if ($refused) {
9586: &logthis('Refused custom assignrole: '.
9587: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
9588: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
9589: return 'refused';
9590: }
9591: }
9592: $mrole='cr';
9593: } elsif ($role =~ /^gr\//) {
9594: my $cwogrp=$url;
9595: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
9596: unless (&allowed('mdg',$cwogrp)) {
9597: &logthis('Refused group assignrole: '.
9598: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
9599: $env{'user.name'}.' at '.$env{'user.domain'});
9600: return 'refused';
9601: }
9602: $mrole='gr';
9603: } else {
9604: my $cwosec=$url;
9605: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
9606: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
9607: my $refused;
9608: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
9609: if (!(&allowed('c'.$role,$url))) {
9610: $refused = 1;
9611: }
9612: } else {
9613: $refused = 1;
9614: }
9615: if ($refused) {
9616: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
9617: if (!$selfenroll && $context eq 'course') {
9618: my %crsenv;
9619: if ($role eq 'cc' || $role eq 'co') {
9620: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9621: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
9622: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
9623: if ($crsenv{'internal.courseowner'} eq
9624: $env{'user.name'}.':'.$env{'user.domain'}) {
9625: $refused = '';
9626: }
9627: }
9628: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
9629: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
9630: if ($crsenv{'internal.courseowner'} eq
9631: $env{'user.name'}.':'.$env{'user.domain'}) {
9632: $refused = '';
9633: }
9634: }
9635: }
9636: }
9637: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
9638: $refused = '';
9639: } elsif ($context eq 'requestcourses') {
9640: my @possroles = ('st','ta','ep','in','cc','co');
9641: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
9642: my $wrongcc;
9643: if ($cnum =~ /^$match_community$/) {
9644: $wrongcc = 1 if ($role eq 'cc');
9645: } else {
9646: $wrongcc = 1 if ($role eq 'co');
9647: }
9648: unless ($wrongcc) {
9649: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
9650: if ($crsenv{'internal.courseowner'} eq
9651: $env{'user.name'}.':'.$env{'user.domain'}) {
9652: $refused = '';
9653: }
9654: }
9655: }
9656: } elsif ($context eq 'requestauthor') {
9657: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
9658: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
9659: if ($env{'environment.requestauthor'} eq 'automatic') {
9660: $refused = '';
9661: } else {
9662: my %domdefaults = &get_domain_defaults($udom);
9663: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
9664: my $checkbystatus;
9665: if ($env{'user.adv'}) {
9666: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
9667: if ($disposition eq 'automatic') {
9668: $refused = '';
9669: } elsif ($disposition eq '') {
9670: $checkbystatus = 1;
9671: }
9672: } else {
9673: $checkbystatus = 1;
9674: }
9675: if ($checkbystatus) {
9676: if ($env{'environment.inststatus'}) {
9677: my @inststatuses = split(/,/,$env{'environment.inststatus'});
9678: foreach my $type (@inststatuses) {
9679: if (($type ne '') &&
9680: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
9681: $refused = '';
9682: }
9683: }
9684: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
9685: $refused = '';
9686: }
9687: }
9688: }
9689: }
9690: }
9691: }
9692: if ($refused) {
9693: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
9694: ' '.$role.' '.$end.' '.$start.' by '.
9695: $env{'user.name'}.' at '.$env{'user.domain'});
9696: return 'refused';
9697: }
9698: }
9699: } elsif ($role eq 'au') {
9700: if ($url ne '/'.$udom.'/') {
9701: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
9702: ' to assign author role for '.$uname.':'.$udom.
9703: ' in domain: '.$url.' refused (wrong domain).');
9704: return 'refused';
9705: }
9706: }
9707: $mrole=$role;
9708: }
9709: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
9710: "$udom:$uname:$url".'_'."$mrole=$role";
9711: if ($end) { $command.='_'.$end; }
9712: if ($start) {
9713: if ($end) {
9714: $command.='_'.$start;
9715: } else {
9716: $command.='_0_'.$start;
9717: }
9718: }
9719: my $origstart = $start;
9720: my $origend = $end;
9721: my $delflag;
9722: # actually delete
9723: if ($deleteflag) {
9724: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
9725: # modify command to delete the role
9726: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
9727: "$udom:$uname:$url".'_'."$mrole";
9728: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
9729: # set start and finish to negative values for userrolelog
9730: $start=-1;
9731: $end=-1;
9732: $delflag = 1;
9733: }
9734: }
9735: # send command
9736: my $answer=&reply($command,&homeserver($uname,$udom));
9737: # log new user role if status is ok
9738: if ($answer eq 'ok') {
9739: &userrolelog($role,$uname,$udom,$url,$start,$end);
9740: if (($role eq 'cc') || ($role eq 'in') ||
9741: ($role eq 'ep') || ($role eq 'ad') ||
9742: ($role eq 'ta') || ($role eq 'st') ||
9743: ($role=~/^cr/) || ($role eq 'gr') ||
9744: ($role eq 'co')) {
9745: # for course roles, perform group memberships changes triggered by role change.
9746: unless ($role =~ /^gr/) {
9747: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
9748: $origstart,$selfenroll,$context);
9749: }
9750: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9751: $selfenroll,$context);
9752: } elsif (($role eq 'li') || ($role eq 'dg') || ($role eq 'sc') ||
9753: ($role eq 'au') || ($role eq 'dc') || ($role eq 'dh') ||
9754: ($role eq 'da')) {
9755: &domainrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9756: $context);
9757: } elsif (($role eq 'ca') || ($role eq 'aa')) {
9758: &coauthorrolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,
9759: $context);
9760: }
9761: if ($role eq 'cc') {
9762: &autoupdate_coowners($url,$end,$start,$uname,$udom);
9763: }
9764: }
9765: return $answer;
9766: }
9767:
9768: sub autoupdate_coowners {
9769: my ($url,$end,$start,$uname,$udom) = @_;
9770: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
9771: if (($cdom ne '') && ($cnum ne '')) {
9772: my $now = time;
9773: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
9774: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
9775: my %coursehash = &coursedescription($cdom.'_'.$cnum);
9776: my $instcode = $coursehash{'internal.coursecode'};
9777: if ($instcode ne '') {
9778: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
9779: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
9780: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
9781: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
9782: if ($result eq 'valid') {
9783: if ($coursehash{'internal.co-owners'}) {
9784: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9785: push(@newcoowners,$coowner);
9786: }
9787: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
9788: push(@newcoowners,$uname.':'.$udom);
9789: }
9790: @newcoowners = sort(@newcoowners);
9791: } else {
9792: push(@newcoowners,$uname.':'.$udom);
9793: }
9794: } else {
9795: if ($coursehash{'internal.co-owners'}) {
9796: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
9797: unless ($coowner eq $uname.':'.$udom) {
9798: push(@newcoowners,$coowner);
9799: }
9800: }
9801: unless (@newcoowners > 0) {
9802: $delcoowners = 1;
9803: $coowners = '';
9804: }
9805: }
9806: }
9807: if (@newcoowners || $delcoowners) {
9808: &store_coowners($cdom,$cnum,$coursehash{'home'},
9809: $delcoowners,@newcoowners);
9810: }
9811: }
9812: }
9813: }
9814: }
9815: }
9816: }
9817:
9818: sub store_coowners {
9819: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
9820: my $cid = $cdom.'_'.$cnum;
9821: my ($coowners,$delresult,$putresult);
9822: if (@newcoowners) {
9823: $coowners = join(',',@newcoowners);
9824: my %coownershash = (
9825: 'internal.co-owners' => $coowners,
9826: );
9827: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
9828: if ($putresult eq 'ok') {
9829: if ($env{'course.'.$cid.'.num'} eq $cnum) {
9830: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
9831: }
9832: }
9833: }
9834: if ($delcoowners) {
9835: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
9836: if ($delresult eq 'ok') {
9837: if ($env{'course.'.$cid.'.internal.co-owners'}) {
9838: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
9839: }
9840: }
9841: }
9842: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
9843: my %crsinfo =
9844: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
9845: if (ref($crsinfo{$cid}) eq 'HASH') {
9846: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
9847: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
9848: }
9849: }
9850: }
9851:
9852: # -------------------------------------------------- Modify user authentication
9853: # Overrides without validation
9854:
9855: sub modifyuserauth {
9856: my ($udom,$uname,$umode,$upass)=@_;
9857: my $uhome=&homeserver($uname,$udom);
9858: my $allowed;
9859: if (&allowed('mau',$udom)) {
9860: $allowed = 1;
9861: } elsif (($umode eq 'internal') && ($udom eq $env{'user.domain'}) &&
9862: ($env{'request.course.id'}) && (&allowed('mip',$env{'request.course.id'})) &&
9863: (!$env{'course.'.$env{'request.course.id'}.'.internal.nopasswdchg'})) {
9864: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9865: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9866: if (($cdom ne '') && ($cnum ne '')) {
9867: my $is_owner = &is_course_owner($cdom,$cnum);
9868: if ($is_owner) {
9869: $allowed = 1;
9870: }
9871: }
9872: }
9873: unless ($allowed) { return 'refused'; }
9874: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
9875: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9876: ' in domain '.$env{'request.role.domain'});
9877: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
9878: &escape($upass),$uhome);
9879: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
9880: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
9881: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9882: &log($udom,,$uname,$uhome,
9883: 'Authentication changed by '.$env{'user.domain'}.', '.
9884: $env{'user.name'}.', '.$umode.
9885: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
9886: unless ($reply eq 'ok') {
9887: &logthis('Authentication mode error: '.$reply);
9888: return 'error: '.$reply;
9889: }
9890: return 'ok';
9891: }
9892:
9893: # --------------------------------------------------------------- Modify a user
9894:
9895: sub modifyuser {
9896: my ($udom, $uname, $uid,
9897: $umode, $upass, $first,
9898: $middle, $last, $gene,
9899: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
9900: $udom= &LONCAPA::clean_domain($udom);
9901: $uname=&LONCAPA::clean_username($uname);
9902: my $showcandelete = 'none';
9903: if (ref($candelete) eq 'ARRAY') {
9904: if (@{$candelete} > 0) {
9905: $showcandelete = join(', ',@{$candelete});
9906: }
9907: }
9908: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
9909: $umode.', '.$first.', '.$middle.', '.
9910: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
9911: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
9912: ' desiredhome not specified').
9913: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
9914: ' in domain '.$env{'request.role.domain'});
9915: my $uhome=&homeserver($uname,$udom,'true');
9916: my $newuser;
9917: if ($uhome eq 'no_host') {
9918: $newuser = 1;
9919: }
9920: # ----------------------------------------------------------------- Create User
9921: if (($uhome eq 'no_host') &&
9922: (($umode && $upass) || ($umode eq 'localauth'))) {
9923: my $unhome='';
9924: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
9925: $unhome = $desiredhome;
9926: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
9927: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
9928: } else { # load balancing routine for determining $unhome
9929: my $loadm=10000000;
9930: my %servers = &get_servers($udom,'library');
9931: foreach my $tryserver (keys(%servers)) {
9932: my $answer=reply('load',$tryserver);
9933: if (($answer=~/\d+/) && ($answer<$loadm)) {
9934: $loadm=$answer;
9935: $unhome=$tryserver;
9936: }
9937: }
9938: }
9939: if (($unhome eq '') || ($unhome eq 'no_host')) {
9940: return 'error: unable to find a home server for '.$uname.
9941: ' in domain '.$udom;
9942: }
9943: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
9944: &escape($upass),$unhome);
9945: unless ($reply eq 'ok') {
9946: return 'error: '.$reply;
9947: }
9948: $uhome=&homeserver($uname,$udom,'true');
9949: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
9950: return 'error: unable verify users home machine.';
9951: }
9952: } # End of creation of new user
9953: # ---------------------------------------------------------------------- Add ID
9954: if ($uid) {
9955: $uid=~tr/A-Z/a-z/;
9956: my %uidhash=&idrget($udom,$uname);
9957: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
9958: && (!$forceid)) {
9959: unless ($uid eq $uidhash{$uname}) {
9960: return 'error: user id "'.$uid.'" does not match '.
9961: 'current user id "'.$uidhash{$uname}.'".';
9962: }
9963: } else {
9964: &idput($udom,($uname => $uid));
9965: }
9966: }
9967: # -------------------------------------------------------------- Add names, etc
9968: my @tmp=&get('environment',
9969: ['firstname','middlename','lastname','generation','id',
9970: 'permanentemail','inststatus'],
9971: $udom,$uname);
9972: my (%names,%oldnames);
9973: if ($tmp[0] =~ m/^error:.*/) {
9974: %names=();
9975: } else {
9976: %names = @tmp;
9977: %oldnames = %names;
9978: }
9979: #
9980: # If name, email and/or uid are blank (e.g., because an uploaded file
9981: # of users did not contain them), do not overwrite existing values
9982: # unless field is in $candelete array ref.
9983: #
9984:
9985: my @fields = ('firstname','middlename','lastname','generation',
9986: 'permanentemail','id');
9987: my %newvalues;
9988: if (ref($candelete) eq 'ARRAY') {
9989: foreach my $field (@fields) {
9990: if (grep(/^\Q$field\E$/,@{$candelete})) {
9991: if ($field eq 'firstname') {
9992: $names{$field} = $first;
9993: } elsif ($field eq 'middlename') {
9994: $names{$field} = $middle;
9995: } elsif ($field eq 'lastname') {
9996: $names{$field} = $last;
9997: } elsif ($field eq 'generation') {
9998: $names{$field} = $gene;
9999: } elsif ($field eq 'permanentemail') {
10000: $names{$field} = $email;
10001: } elsif ($field eq 'id') {
10002: $names{$field} = $uid;
10003: }
10004: }
10005: }
10006: }
10007: if ($first) { $names{'firstname'} = $first; }
10008: if (defined($middle)) { $names{'middlename'} = $middle; }
10009: if ($last) { $names{'lastname'} = $last; }
10010: if (defined($gene)) { $names{'generation'} = $gene; }
10011: if ($email) {
10012: $email=~s/[^\w\@\.\-\,]//gs;
10013: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
10014: }
10015: if ($uid) { $names{'id'} = $uid; }
10016: if (defined($inststatus)) {
10017: $names{'inststatus'} = '';
10018: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
10019: if (ref($usertypes) eq 'HASH') {
10020: my @okstatuses;
10021: foreach my $item (split(/:/,$inststatus)) {
10022: if (defined($usertypes->{$item})) {
10023: push(@okstatuses,$item);
10024: }
10025: }
10026: if (@okstatuses) {
10027: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
10028: }
10029: }
10030: }
10031: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
10032: $umode.', '.$first.', '.$middle.', '.
10033: $last.', '.$gene.', '.$email.', '.$inststatus;
10034: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
10035: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
10036: } else {
10037: $logmsg .= ' during self creation';
10038: }
10039: my $changed;
10040: if ($newuser) {
10041: $changed = 1;
10042: } else {
10043: foreach my $field (@fields) {
10044: if ($names{$field} ne $oldnames{$field}) {
10045: $changed = 1;
10046: last;
10047: }
10048: }
10049: }
10050: unless ($changed) {
10051: $logmsg = 'No changes in user information needed for: '.$logmsg;
10052: &logthis($logmsg);
10053: return 'ok';
10054: }
10055: my $reply = &put('environment', \%names, $udom,$uname);
10056: if ($reply ne 'ok') {
10057: return 'error: '.$reply;
10058: }
10059: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
10060: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
10061: }
10062: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
10063: &devalidate_cache_new('namescache',$uname.':'.$udom);
10064: $logmsg = 'Success modifying user '.$logmsg;
10065: &logthis($logmsg);
10066: return 'ok';
10067: }
10068:
10069: # -------------------------------------------------------------- Modify student
10070:
10071: sub modifystudent {
10072: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
10073: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
10074: $selfenroll,$context,$inststatus,$credits,$instsec)=@_;
10075: if (!$cid) {
10076: unless ($cid=$env{'request.course.id'}) {
10077: return 'not_in_class';
10078: }
10079: }
10080: # --------------------------------------------------------------- Make the user
10081: my $reply=&modifyuser
10082: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
10083: $desiredhome,$email,$inststatus);
10084: unless ($reply eq 'ok') { return $reply; }
10085: # This will cause &modify_student_enrollment to get the uid from the
10086: # student's environment
10087: $uid = undef if (!$forceid);
10088: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
10089: $gene,$usec,$end,$start,$type,$locktype,
10090: $cid,$selfenroll,$context,$credits,$instsec);
10091: return $reply;
10092: }
10093:
10094: sub modify_student_enrollment {
10095: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,
10096: $locktype,$cid,$selfenroll,$context,$credits,$instsec) = @_;
10097: my ($cdom,$cnum,$chome);
10098: if (!$cid) {
10099: unless ($cid=$env{'request.course.id'}) {
10100: return 'not_in_class';
10101: }
10102: $cdom=$env{'course.'.$cid.'.domain'};
10103: $cnum=$env{'course.'.$cid.'.num'};
10104: } else {
10105: ($cdom,$cnum)=split(/_/,$cid);
10106: }
10107: $chome=$env{'course.'.$cid.'.home'};
10108: if (!$chome) {
10109: $chome=&homeserver($cnum,$cdom);
10110: }
10111: if (!$chome) { return 'unknown_course'; }
10112: # Make sure the user exists
10113: my $uhome=&homeserver($uname,$udom);
10114: if (($uhome eq '') || ($uhome eq 'no_host')) {
10115: return 'error: no such user';
10116: }
10117: # Get student data if we were not given enough information
10118: if (!defined($first) || $first eq '' ||
10119: !defined($last) || $last eq '' ||
10120: !defined($uid) || $uid eq '' ||
10121: !defined($middle) || $middle eq '' ||
10122: !defined($gene) || $gene eq '') {
10123: # They did not supply us with enough data to enroll the student, so
10124: # we need to pick up more information.
10125: my %tmp = &get('environment',
10126: ['firstname','middlename','lastname', 'generation','id']
10127: ,$udom,$uname);
10128:
10129: #foreach my $key (keys(%tmp)) {
10130: # &logthis("key $key = ".$tmp{$key});
10131: #}
10132: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
10133: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
10134: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
10135: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
10136: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
10137: }
10138: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
10139: my $user = "$uname:$udom";
10140: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
10141: my $reply=cput('classlist',
10142: {$user =>
10143: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype,$credits,$instsec) },
10144: $cdom,$cnum);
10145: if (($reply eq 'ok') || ($reply eq 'delayed')) {
10146: &devalidate_getsection_cache($udom,$uname,$cid);
10147: } else {
10148: return 'error: '.$reply;
10149: }
10150: # Add student role to user
10151: my $uurl='/'.$cid;
10152: $uurl=~s/\_/\//g;
10153: if ($usec) {
10154: $uurl.='/'.$usec;
10155: }
10156: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
10157: $selfenroll,$context);
10158: if ($result ne 'ok') {
10159: if ($old_entry{$user} ne '') {
10160: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
10161: } else {
10162: $reply = &del('classlist',[$user],$cdom,$cnum);
10163: }
10164: }
10165: return $result;
10166: }
10167:
10168: sub format_name {
10169: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
10170: my $name;
10171: if ($first ne 'lastname') {
10172: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
10173: } else {
10174: if ($lastname=~/\S/) {
10175: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
10176: $name=~s/\s+,/,/;
10177: } else {
10178: $name.= $firstname.' '.$middlename.' '.$generation;
10179: }
10180: }
10181: $name=~s/^\s+//;
10182: $name=~s/\s+$//;
10183: $name=~s/\s+/ /g;
10184: return $name;
10185: }
10186:
10187: # ------------------------------------------------- Write to course preferences
10188:
10189: sub writecoursepref {
10190: my ($courseid,%prefs)=@_;
10191: $courseid=~s/^\///;
10192: $courseid=~s/\_/\//g;
10193: my ($cdomain,$cnum)=split(/\//,$courseid);
10194: my $chome=homeserver($cnum,$cdomain);
10195: if (($chome eq '') || ($chome eq 'no_host')) {
10196: return 'error: no such course';
10197: }
10198: my $cstring='';
10199: foreach my $pref (keys(%prefs)) {
10200: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
10201: }
10202: $cstring=~s/\&$//;
10203: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
10204: }
10205:
10206: # ---------------------------------------------------------- Make/modify course
10207:
10208: sub createcourse {
10209: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
10210: $course_owner,$crstype,$cnum,$context,$category)=@_;
10211: $url=&declutter($url);
10212: my $cid='';
10213: if ($context eq 'requestcourses') {
10214: my $can_create = 0;
10215: my ($ownername,$ownerdom) = split(':',$course_owner);
10216: if ($udom eq $ownerdom) {
10217: if (&usertools_access($ownername,$ownerdom,$category,undef,
10218: $context)) {
10219: $can_create = 1;
10220: }
10221: } else {
10222: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
10223: $category);
10224: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
10225: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
10226: if (@curr > 0) {
10227: my @options = qw(approval validate autolimit);
10228: my $optregex = join('|',@options);
10229: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
10230: $can_create = 1;
10231: }
10232: }
10233: }
10234: }
10235: if ($can_create) {
10236: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
10237: unless (&allowed('ccc',$udom)) {
10238: return 'refused';
10239: }
10240: }
10241: } else {
10242: return 'refused';
10243: }
10244: } elsif (!&allowed('ccc',$udom)) {
10245: return 'refused';
10246: }
10247: # --------------------------------------------------------------- Get Unique ID
10248: my $uname;
10249: if ($cnum =~ /^$match_courseid$/) {
10250: my $chome=&homeserver($cnum,$udom,'true');
10251: if (($chome eq '') || ($chome eq 'no_host')) {
10252: $uname = $cnum;
10253: } else {
10254: $uname = &generate_coursenum($udom,$crstype);
10255: }
10256: } else {
10257: $uname = &generate_coursenum($udom,$crstype);
10258: }
10259: return $uname if ($uname =~ /^error/);
10260: # -------------------------------------------------- Check supplied server name
10261: if (!defined($course_server)) {
10262: if (defined(&domain($udom,'primary'))) {
10263: $course_server = &domain($udom,'primary');
10264: } else {
10265: $course_server = $env{'user.home'};
10266: }
10267: }
10268: my %host_servers =
10269: &Apache::lonnet::get_servers($udom,'library');
10270: unless ($host_servers{$course_server}) {
10271: return 'error: invalid home server for course: '.$course_server;
10272: }
10273: # ------------------------------------------------------------- Make the course
10274: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
10275: $course_server);
10276: unless ($reply eq 'ok') { return 'error: '.$reply; }
10277: my $uhome=&homeserver($uname,$udom,'true');
10278: if (($uhome eq '') || ($uhome eq 'no_host')) {
10279: return 'error: no such course';
10280: }
10281: # ----------------------------------------------------------------- Course made
10282: # log existence
10283: my $now = time;
10284: my $newcourse = {
10285: $udom.'_'.$uname => {
10286: description => $description,
10287: inst_code => $inst_code,
10288: owner => $course_owner,
10289: type => $crstype,
10290: creator => $env{'user.name'}.':'.
10291: $env{'user.domain'},
10292: created => $now,
10293: context => $context,
10294: },
10295: };
10296: &courseidput($udom,$newcourse,$uhome,'notime');
10297: # set toplevel url
10298: my $topurl=$url;
10299: unless ($nonstandard) {
10300: # ------------------------------------------ For standard courses, make top url
10301: my $mapurl=&clutter($url);
10302: if ($mapurl eq '/res/') { $mapurl=''; }
10303: $env{'form.initmap'}=(<<ENDINITMAP);
10304: <map>
10305: <resource id="1" type="start"></resource>
10306: <resource id="2" src="$mapurl"></resource>
10307: <resource id="3" type="finish"></resource>
10308: <link index="1" from="1" to="2"></link>
10309: <link index="2" from="2" to="3"></link>
10310: </map>
10311: ENDINITMAP
10312: $topurl=&declutter(
10313: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
10314: );
10315: }
10316: # ----------------------------------------------------------- Write preferences
10317: &writecoursepref($udom.'_'.$uname,
10318: ('description' => $description,
10319: 'url' => $topurl,
10320: 'internal.creator' => $env{'user.name'}.':'.
10321: $env{'user.domain'},
10322: 'internal.created' => $now,
10323: 'internal.creationcontext' => $context)
10324: );
10325: return '/'.$udom.'/'.$uname;
10326: }
10327:
10328: # ------------------------------------------------------------------- Create ID
10329: sub generate_coursenum {
10330: my ($udom,$crstype) = @_;
10331: my $domdesc = &domain($udom);
10332: return 'error: invalid domain' if ($domdesc eq '');
10333: my $first;
10334: if ($crstype eq 'Community') {
10335: $first = '0';
10336: } else {
10337: $first = int(1+rand(9));
10338: }
10339: my $uname=$first.
10340: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10341: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10342: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10343: # ----------------------------------------------- Make sure that does not exist
10344: my $uhome=&homeserver($uname,$udom,'true');
10345: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10346: if ($crstype eq 'Community') {
10347: $first = '0';
10348: } else {
10349: $first = int(1+rand(9));
10350: }
10351: $uname=$first.
10352: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
10353: substr($$.time,0,5).unpack("H8",pack("I32",time)).
10354: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
10355: $uhome=&homeserver($uname,$udom,'true');
10356: unless (($uhome eq '') || ($uhome eq 'no_host')) {
10357: return 'error: unable to generate unique course-ID';
10358: }
10359: }
10360: return $uname;
10361: }
10362:
10363: sub is_course {
10364: my ($cdom, $cnum) = scalar(@_) == 1 ?
10365: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
10366: return unless (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/));
10367: my $uhome=&homeserver($cnum,$cdom);
10368: my $iscourse;
10369: if (grep { $_ eq $uhome } current_machine_ids()) {
10370: $iscourse = &LONCAPA::Lond::is_course($cdom,$cnum);
10371: } else {
10372: my $hashid = $cdom.':'.$cnum;
10373: ($iscourse,my $cached) = &is_cached_new('iscourse',$hashid);
10374: unless (defined($cached)) {
10375: my %courses = &courseiddump($cdom, '.', 1, '.', '.',
10376: $cnum,undef,undef,'.');
10377: $iscourse = 0;
10378: if (exists($courses{$cdom.'_'.$cnum})) {
10379: $iscourse = 1;
10380: }
10381: &do_cache_new('iscourse',$hashid,$iscourse,3600);
10382: }
10383: }
10384: return unless($iscourse);
10385: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
10386: }
10387:
10388: sub store_userdata {
10389: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
10390: my $result;
10391: if ($datakey ne '') {
10392: if (ref($storehash) eq 'HASH') {
10393: if ($udom eq '' || $uname eq '') {
10394: $udom = $env{'user.domain'};
10395: $uname = $env{'user.name'};
10396: }
10397: my $uhome=&homeserver($uname,$udom);
10398: if (($uhome eq '') || ($uhome eq 'no_host')) {
10399: $result = 'error: no_host';
10400: } else {
10401: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
10402: $storehash->{'host'} = $perlvar{'lonHostID'};
10403:
10404: my $namevalue='';
10405: foreach my $key (keys(%{$storehash})) {
10406: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
10407: }
10408: $namevalue=~s/\&$//;
10409: unless ($namespace eq 'courserequests') {
10410: $datakey = &escape($datakey);
10411: }
10412: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
10413: $namevalue,$uhome);
10414: }
10415: } else {
10416: $result = 'error: data to store was not a hash reference';
10417: }
10418: } else {
10419: $result= 'error: invalid requestkey';
10420: }
10421: return $result;
10422: }
10423:
10424: # ---------------------------------------------------------- Assign Custom Role
10425:
10426: sub assigncustomrole {
10427: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
10428: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
10429: $end,$start,$deleteflag,$selfenroll,$context);
10430: }
10431:
10432: # ----------------------------------------------------------------- Revoke Role
10433:
10434: sub revokerole {
10435: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
10436: my $now=time;
10437: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
10438: }
10439:
10440: # ---------------------------------------------------------- Revoke Custom Role
10441:
10442: sub revokecustomrole {
10443: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
10444: my $now=time;
10445: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
10446: $deleteflag,$selfenroll,$context);
10447: }
10448:
10449: # ------------------------------------------------------------ Disk usage
10450: sub diskusage {
10451: my ($udom,$uname,$directorypath,$getpropath)=@_;
10452: $directorypath =~ s/\/$//;
10453: my $listing=&reply('du2:'.&escape($directorypath).':'
10454: .&escape($getpropath).':'.&escape($uname).':'
10455: .&escape($udom),homeserver($uname,$udom));
10456: if ($listing eq 'unknown_cmd') {
10457: if ($getpropath) {
10458: $directorypath = &propath($udom,$uname).'/'.$directorypath;
10459: }
10460: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
10461: }
10462: return $listing;
10463: }
10464:
10465: sub is_locked {
10466: my ($file_name, $domain, $user, $which) = @_;
10467: my @check;
10468: my $is_locked;
10469: push (@check,$file_name);
10470: my %locked = &get('file_permissions',\@check,
10471: $env{'user.domain'},$env{'user.name'});
10472: my ($tmp)=keys(%locked);
10473: if ($tmp=~/^error:/) { undef(%locked); }
10474:
10475: if (ref($locked{$file_name}) eq 'ARRAY') {
10476: $is_locked = 'false';
10477: foreach my $entry (@{$locked{$file_name}}) {
10478: if (ref($entry) eq 'ARRAY') {
10479: $is_locked = 'true';
10480: if (ref($which) eq 'ARRAY') {
10481: push(@{$which},$entry);
10482: } else {
10483: last;
10484: }
10485: }
10486: }
10487: } else {
10488: $is_locked = 'false';
10489: }
10490: return $is_locked;
10491: }
10492:
10493: sub declutter_portfile {
10494: my ($file) = @_;
10495: $file =~ s{^(/portfolio/|portfolio/)}{/};
10496: return $file;
10497: }
10498:
10499: # ------------------------------------------------------------- Mark as Read Only
10500:
10501: sub mark_as_readonly {
10502: my ($domain,$user,$files,$what) = @_;
10503: my %current_permissions = &dump('file_permissions',$domain,$user);
10504: my ($tmp)=keys(%current_permissions);
10505: if ($tmp=~/^error:/) { undef(%current_permissions); }
10506: foreach my $file (@{$files}) {
10507: $file = &declutter_portfile($file);
10508: push(@{$current_permissions{$file}},$what);
10509: }
10510: &put('file_permissions',\%current_permissions,$domain,$user);
10511: return;
10512: }
10513:
10514: # ------------------------------------------------------------Save Selected Files
10515:
10516: sub save_selected_files {
10517: my ($user, $path, @files) = @_;
10518: my $filename = $user."savedfiles";
10519: my @other_files = &files_not_in_path($user, $path);
10520: open (OUT,'>',LONCAPA::tempdir().$filename);
10521: foreach my $file (@files) {
10522: print (OUT $env{'form.currentpath'}.$file."\n");
10523: }
10524: foreach my $file (@other_files) {
10525: print (OUT $file."\n");
10526: }
10527: close (OUT);
10528: return 'ok';
10529: }
10530:
10531: sub clear_selected_files {
10532: my ($user) = @_;
10533: my $filename = $user."savedfiles";
10534: open (OUT,'>',LONCAPA::tempdir().$filename);
10535: print (OUT undef);
10536: close (OUT);
10537: return ("ok");
10538: }
10539:
10540: sub files_in_path {
10541: my ($user, $path) = @_;
10542: my $filename = $user."savedfiles";
10543: my %return_files;
10544: open (IN,'<',LONCAPA::tempdir().$filename);
10545: while (my $line_in = <IN>) {
10546: chomp ($line_in);
10547: my @paths_and_file = split (m!/!, $line_in);
10548: my $file_part = pop (@paths_and_file);
10549: my $path_part = join ('/', @paths_and_file);
10550: $path_part.='/';
10551: my $path_and_file = $path_part.$file_part;
10552: if ($path_part eq $path) {
10553: $return_files{$file_part}= 'selected';
10554: }
10555: }
10556: close (IN);
10557: return (\%return_files);
10558: }
10559:
10560: # called in portfolio select mode, to show files selected NOT in current directory
10561: sub files_not_in_path {
10562: my ($user, $path) = @_;
10563: my $filename = $user."savedfiles";
10564: my @return_files;
10565: my $path_part;
10566: open(IN, '<',LONCAPA::tempdir().$filename);
10567: while (my $line = <IN>) {
10568: #ok, I know it's clunky, but I want it to work
10569: my @paths_and_file = split(m|/|, $line);
10570: my $file_part = pop(@paths_and_file);
10571: chomp($file_part);
10572: my $path_part = join('/', @paths_and_file);
10573: $path_part .= '/';
10574: my $path_and_file = $path_part.$file_part;
10575: if ($path_part ne $path) {
10576: push(@return_files, ($path_and_file));
10577: }
10578: }
10579: close(OUT);
10580: return (@return_files);
10581: }
10582:
10583: #----------------------------------------------Get portfolio file permissions
10584:
10585: sub get_portfile_permissions {
10586: my ($domain,$user) = @_;
10587: my %current_permissions = &dump('file_permissions',$domain,$user);
10588: my ($tmp)=keys(%current_permissions);
10589: if ($tmp=~/^error:/) { undef(%current_permissions); }
10590: return \%current_permissions;
10591: }
10592:
10593: #---------------------------------------------Get portfolio file access controls
10594:
10595: sub get_access_controls {
10596: my ($current_permissions,$group,$file) = @_;
10597: my %access;
10598: my $real_file = $file;
10599: $file =~ s/\.meta$//;
10600: if (defined($file)) {
10601: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
10602: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
10603: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
10604: }
10605: }
10606: } else {
10607: foreach my $key (keys(%{$current_permissions})) {
10608: if ($key =~ /\0accesscontrol$/) {
10609: if (defined($group)) {
10610: if ($key !~ m-^\Q$group\E/-) {
10611: next;
10612: }
10613: }
10614: my ($fullpath) = split(/\0/,$key);
10615: if (ref($$current_permissions{$key}) eq 'HASH') {
10616: foreach my $control (keys(%{$$current_permissions{$key}})) {
10617: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
10618: }
10619: }
10620: }
10621: }
10622: }
10623: return %access;
10624: }
10625:
10626: sub modify_access_controls {
10627: my ($file_name,$changes,$domain,$user)=@_;
10628: my ($outcome,$deloutcome);
10629: my %store_permissions;
10630: my %new_values;
10631: my %new_control;
10632: my %translation;
10633: my @deletions = ();
10634: my $now = time;
10635: if (exists($$changes{'activate'})) {
10636: if (ref($$changes{'activate'}) eq 'HASH') {
10637: my @newitems = sort(keys(%{$$changes{'activate'}}));
10638: my $numnew = scalar(@newitems);
10639: for (my $i=0; $i<$numnew; $i++) {
10640: my $newkey = $newitems[$i];
10641: my $newid = &Apache::loncommon::get_cgi_id();
10642: if ($newkey =~ /^\d+:/) {
10643: $newkey =~ s/^(\d+)/$newid/;
10644: $translation{$1} = $newid;
10645: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
10646: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
10647: $translation{$1} = $newid;
10648: }
10649: $new_values{$file_name."\0".$newkey} =
10650: $$changes{'activate'}{$newitems[$i]};
10651: $new_control{$newkey} = $now;
10652: }
10653: }
10654: }
10655: my %todelete;
10656: my %changed_items;
10657: foreach my $action ('delete','update') {
10658: if (exists($$changes{$action})) {
10659: if (ref($$changes{$action}) eq 'HASH') {
10660: foreach my $key (keys(%{$$changes{$action}})) {
10661: my ($itemnum) = ($key =~ /^([^:]+):/);
10662: if ($action eq 'delete') {
10663: $todelete{$itemnum} = 1;
10664: } else {
10665: $changed_items{$itemnum} = $key;
10666: }
10667: }
10668: }
10669: }
10670: }
10671: # get lock on access controls for file.
10672: my $lockhash = {
10673: $file_name."\0".'locked_access_records' => $env{'user.name'}.
10674: ':'.$env{'user.domain'},
10675: };
10676: my $tries = 0;
10677: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10678:
10679: while (($gotlock ne 'ok') && $tries < 10) {
10680: $tries ++;
10681: sleep(0.1);
10682: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
10683: }
10684: if ($gotlock eq 'ok') {
10685: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
10686: my ($tmp)=keys(%curr_permissions);
10687: if ($tmp=~/^error:/) { undef(%curr_permissions); }
10688: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
10689: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
10690: if (ref($curr_controls) eq 'HASH') {
10691: foreach my $control_item (keys(%{$curr_controls})) {
10692: my ($itemnum) = ($control_item =~ /^([^:]+):/);
10693: if (defined($todelete{$itemnum})) {
10694: push(@deletions,$file_name."\0".$control_item);
10695: } else {
10696: if (defined($changed_items{$itemnum})) {
10697: $new_control{$changed_items{$itemnum}} = $now;
10698: push(@deletions,$file_name."\0".$control_item);
10699: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
10700: } else {
10701: $new_control{$control_item} = $$curr_controls{$control_item};
10702: }
10703: }
10704: }
10705: }
10706: }
10707: my ($group);
10708: if (&is_course($domain,$user)) {
10709: ($group,my $file) = split(/\//,$file_name,2);
10710: }
10711: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
10712: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
10713: $outcome = &put('file_permissions',\%new_values,$domain,$user);
10714: # remove lock
10715: my @del_lock = ($file_name."\0".'locked_access_records');
10716: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
10717: my $sqlresult =
10718: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
10719: $group);
10720: } else {
10721: $outcome = "error: could not obtain lockfile\n";
10722: }
10723: return ($outcome,$deloutcome,\%new_values,\%translation);
10724: }
10725:
10726: sub make_public_indefinitely {
10727: my ($requrl) = @_;
10728: my $now = time;
10729: my $action = 'activate';
10730: my $aclnum = 0;
10731: if (&is_portfolio_url($requrl)) {
10732: my (undef,$udom,$unum,$file_name,$group) =
10733: &parse_portfolio_url($requrl);
10734: my $current_perms = &get_portfile_permissions($udom,$unum);
10735: my %access_controls = &get_access_controls($current_perms,
10736: $group,$file_name);
10737: foreach my $key (keys(%{$access_controls{$file_name}})) {
10738: my ($num,$scope,$end,$start) =
10739: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
10740: if ($scope eq 'public') {
10741: if ($start <= $now && $end == 0) {
10742: $action = 'none';
10743: } else {
10744: $action = 'update';
10745: $aclnum = $num;
10746: }
10747: last;
10748: }
10749: }
10750: if ($action eq 'none') {
10751: return 'ok';
10752: } else {
10753: my %changes;
10754: my $newend = 0;
10755: my $newstart = $now;
10756: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
10757: $changes{$action}{$newkey} = {
10758: type => 'public',
10759: time => {
10760: start => $newstart,
10761: end => $newend,
10762: },
10763: };
10764: my ($outcome,$deloutcome,$new_values,$translation) =
10765: &modify_access_controls($file_name,\%changes,$udom,$unum);
10766: return $outcome;
10767: }
10768: } else {
10769: return 'invalid';
10770: }
10771: }
10772:
10773: #------------------------------------------------------Get Marked as Read Only
10774:
10775: sub get_marked_as_readonly {
10776: my ($domain,$user,$what,$group) = @_;
10777: my $current_permissions = &get_portfile_permissions($domain,$user);
10778: my @readonly_files;
10779: my $cmp1=$what;
10780: if (ref($what)) { $cmp1=join('',@{$what}) };
10781: while (my ($file_name,$value) = each(%{$current_permissions})) {
10782: if (defined($group)) {
10783: if ($file_name !~ m-^\Q$group\E/-) {
10784: next;
10785: }
10786: }
10787: if (ref($value) eq "ARRAY"){
10788: foreach my $stored_what (@{$value}) {
10789: my $cmp2=$stored_what;
10790: if (ref($stored_what) eq 'ARRAY') {
10791: $cmp2=join('',@{$stored_what});
10792: }
10793: if ($cmp1 eq $cmp2) {
10794: push(@readonly_files, $file_name);
10795: last;
10796: } elsif (!defined($what)) {
10797: push(@readonly_files, $file_name);
10798: last;
10799: }
10800: }
10801: }
10802: }
10803: return @readonly_files;
10804: }
10805: #-----------------------------------------------------------Get Marked as Read Only Hash
10806:
10807: sub get_marked_as_readonly_hash {
10808: my ($current_permissions,$group,$what) = @_;
10809: my %readonly_files;
10810: while (my ($file_name,$value) = each(%{$current_permissions})) {
10811: if (defined($group)) {
10812: if ($file_name !~ m-^\Q$group\E/-) {
10813: next;
10814: }
10815: }
10816: if (ref($value) eq "ARRAY"){
10817: foreach my $stored_what (@{$value}) {
10818: if (ref($stored_what) eq 'ARRAY') {
10819: foreach my $lock_descriptor(@{$stored_what}) {
10820: if ($lock_descriptor eq 'graded') {
10821: $readonly_files{$file_name} = 'graded';
10822: } elsif ($lock_descriptor eq 'handback') {
10823: $readonly_files{$file_name} = 'handback';
10824: } else {
10825: if (!exists($readonly_files{$file_name})) {
10826: $readonly_files{$file_name} = 'locked';
10827: }
10828: }
10829: }
10830: }
10831: }
10832: }
10833: }
10834: return %readonly_files;
10835: }
10836: # ------------------------------------------------------------ Unmark as Read Only
10837:
10838: sub unmark_as_readonly {
10839: # unmarks $file_name (if $file_name is defined), or all files locked by $what
10840: # for portfolio submissions, $what contains [$symb,$crsid]
10841: my ($domain,$user,$what,$file_name,$group) = @_;
10842: $file_name = &declutter_portfile($file_name);
10843: my $symb_crs = $what;
10844: if (ref($what)) { $symb_crs=join('',@$what); }
10845: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
10846: my ($tmp)=keys(%current_permissions);
10847: if ($tmp=~/^error:/) { undef(%current_permissions); }
10848: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
10849: foreach my $file (@readonly_files) {
10850: my $clean_file = &declutter_portfile($file);
10851: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
10852: my $current_locks = $current_permissions{$file};
10853: my @new_locks;
10854: my @del_keys;
10855: if (ref($current_locks) eq "ARRAY"){
10856: foreach my $locker (@{$current_locks}) {
10857: my $compare=$locker;
10858: if (ref($locker) eq 'ARRAY') {
10859: $compare=join('',@{$locker});
10860: if ($compare ne $symb_crs) {
10861: push(@new_locks, $locker);
10862: }
10863: }
10864: }
10865: if (scalar(@new_locks) > 0) {
10866: $current_permissions{$file} = \@new_locks;
10867: } else {
10868: push(@del_keys, $file);
10869: &del('file_permissions',\@del_keys, $domain, $user);
10870: delete($current_permissions{$file});
10871: }
10872: }
10873: }
10874: &put('file_permissions',\%current_permissions,$domain,$user);
10875: return;
10876: }
10877:
10878: # ------------------------------------------------------------ Directory lister
10879:
10880: sub dirlist {
10881: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
10882: $uri=~s/^\///;
10883: $uri=~s/\/$//;
10884: my ($udom, $uname);
10885: if ($getuserdir) {
10886: $udom = $userdomain;
10887: $uname = $username;
10888: } else {
10889: (undef,$udom,$uname)=split(/\//,$uri);
10890: if(defined($userdomain)) {
10891: $udom = $userdomain;
10892: }
10893: if(defined($username)) {
10894: $uname = $username;
10895: }
10896: }
10897: my ($dirRoot,$listing,@listing_results);
10898:
10899: $dirRoot = $perlvar{'lonDocRoot'};
10900: if (defined($getpropath)) {
10901: $dirRoot = &propath($udom,$uname);
10902: $dirRoot =~ s/\/$//;
10903: } elsif (defined($getuserdir)) {
10904: my $subdir=$uname.'__';
10905: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
10906: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
10907: ."/$udom/$subdir/$uname";
10908: } elsif (defined($alternateRoot)) {
10909: $dirRoot = $alternateRoot;
10910: }
10911:
10912: if($udom) {
10913: if($uname) {
10914: my $uhome = &homeserver($uname,$udom);
10915: if ($uhome eq 'no_host') {
10916: return ([],'no_host');
10917: }
10918: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
10919: .$getuserdir.':'.&escape($dirRoot)
10920: .':'.&escape($uname).':'.&escape($udom),$uhome);
10921: if ($listing eq 'unknown_cmd') {
10922: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
10923: } else {
10924: @listing_results = map { &unescape($_); } split(/:/,$listing);
10925: }
10926: if ($listing eq 'unknown_cmd') {
10927: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
10928: @listing_results = split(/:/,$listing);
10929: } else {
10930: @listing_results = map { &unescape($_); } split(/:/,$listing);
10931: }
10932: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10933: ($listing eq 'rejected') || ($listing eq 'refused') ||
10934: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10935: return ([],$listing);
10936: } else {
10937: return (\@listing_results);
10938: }
10939: } elsif(!$alternateRoot) {
10940: my (%allusers,%listerror);
10941: my %servers = &get_servers($udom,'library');
10942: foreach my $tryserver (keys(%servers)) {
10943: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
10944: &escape($udom),$tryserver);
10945: if ($listing eq 'unknown_cmd') {
10946: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
10947: $udom, $tryserver);
10948: } else {
10949: @listing_results = map { &unescape($_); } split(/:/,$listing);
10950: }
10951: if ($listing eq 'unknown_cmd') {
10952: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
10953: $udom, $tryserver);
10954: @listing_results = split(/:/,$listing);
10955: } else {
10956: @listing_results =
10957: map { &unescape($_); } split(/:/,$listing);
10958: }
10959: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
10960: ($listing eq 'rejected') || ($listing eq 'refused') ||
10961: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
10962: $listerror{$tryserver} = $listing;
10963: } else {
10964: foreach my $line (@listing_results) {
10965: my ($entry) = split(/&/,$line,2);
10966: $allusers{$entry} = 1;
10967: }
10968: }
10969: }
10970: my @alluserslist=();
10971: foreach my $user (sort(keys(%allusers))) {
10972: push(@alluserslist,$user.'&user');
10973: }
10974: if (!%listerror) {
10975: # no errors
10976: return (\@alluserslist);
10977: } elsif (scalar(keys(%servers)) == 1) {
10978: # one library server, one error
10979: my ($key) = keys(%listerror);
10980: return (\@alluserslist, $listerror{$key});
10981: } elsif ( grep { $_ eq 'con_lost' } values(%listerror) ) {
10982: # con_lost indicates that we might miss data from at least one
10983: # library server
10984: return (\@alluserslist, 'con_lost');
10985: } else {
10986: # multiple library servers and no con_lost -> data should be
10987: # complete.
10988: return (\@alluserslist);
10989: }
10990:
10991: } else {
10992: return ([],'missing username');
10993: }
10994: } elsif(!defined($getpropath)) {
10995: my $path = $perlvar{'lonDocRoot'}.'/res/';
10996: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
10997: return (\@all_domains);
10998: } else {
10999: return ([],'missing domain');
11000: }
11001: }
11002:
11003: # --------------------------------------------- GetFileTimestamp
11004: # This function utilizes dirlist and returns the date stamp for
11005: # when it was last modified. It will also return an error of -1
11006: # if an error occurs
11007:
11008: sub GetFileTimestamp {
11009: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
11010: $studentDomain = &LONCAPA::clean_domain($studentDomain);
11011: $studentName = &LONCAPA::clean_username($studentName);
11012: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
11013: undef,$getuserdir);
11014: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11015: return -1;
11016: }
11017: if (ref($fileref) eq 'ARRAY') {
11018: my @stats = split('&',$fileref->[0]);
11019: # @stats contains first the filename, then the stat output
11020: return $stats[10]; # so this is 10 instead of 9.
11021: } else {
11022: return -1;
11023: }
11024: }
11025:
11026: sub stat_file {
11027: my ($uri) = @_;
11028: $uri = &clutter_with_no_wrapper($uri);
11029:
11030: my ($udom,$uname,$file);
11031: if ($uri =~ m-^/(uploaded|editupload)/-) {
11032: ($udom,$uname,$file) =
11033: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
11034: $file = 'userfiles/'.$file;
11035: }
11036: if ($uri =~ m-^/res/-) {
11037: ($udom,$uname) =
11038: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
11039: $file = $uri;
11040: }
11041:
11042: if (!$udom || !$uname || !$file) {
11043: # unable to handle the uri
11044: return ();
11045: }
11046: my $getpropath;
11047: if ($file =~ /^userfiles\//) {
11048: $getpropath = 1;
11049: }
11050: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
11051: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
11052: return ();
11053: } else {
11054: if (ref($listref) eq 'ARRAY') {
11055: my @stats = split('&',$listref->[0]);
11056: shift(@stats); #filename is first
11057: return @stats;
11058: }
11059: }
11060: return ();
11061: }
11062:
11063: # -------------------------------------------------------- Value of a Condition
11064:
11065: # gets the value of a specific preevaluated condition
11066: # stored in the string $env{user.state.<cid>}
11067: # or looks up a condition reference in the bighash and if if hasn't
11068: # already been evaluated recurses into docondval to get the value of
11069: # the condition, then memoizing it to
11070: # $env{user.state.<cid>.<condition>}
11071: sub directcondval {
11072: my $number=shift;
11073: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
11074: &Apache::lonuserstate::evalstate();
11075: }
11076: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
11077: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
11078: } elsif ($number =~ /^_/) {
11079: my $sub_condition;
11080: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
11081: &GDBM_READER(),0640)) {
11082: $sub_condition=$bighash{'conditions'.$number};
11083: untie(%bighash);
11084: }
11085: my $value = &docondval($sub_condition);
11086: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
11087: return $value;
11088: }
11089: if ($env{'user.state.'.$env{'request.course.id'}}) {
11090: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
11091: } else {
11092: return 2;
11093: }
11094: }
11095:
11096: # get the collection of conditions for this resource
11097: sub condval {
11098: my $condidx=shift;
11099: my $allpathcond='';
11100: foreach my $cond (split(/\|/,$condidx)) {
11101: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
11102: $allpathcond.=
11103: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
11104: }
11105: }
11106: $allpathcond=~s/\|$//;
11107: return &docondval($allpathcond);
11108: }
11109:
11110: #evaluates an expression of conditions
11111: sub docondval {
11112: my ($allpathcond) = @_;
11113: my $result=0;
11114: if ($env{'request.course.id'}
11115: && defined($allpathcond)) {
11116: my $operand='|';
11117: my @stack;
11118: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
11119: if ($chunk eq '(') {
11120: push @stack,($operand,$result);
11121: } elsif ($chunk eq ')') {
11122: my $before=pop @stack;
11123: if (pop @stack eq '&') {
11124: $result=$result>$before?$before:$result;
11125: } else {
11126: $result=$result>$before?$result:$before;
11127: }
11128: } elsif (($chunk eq '&') || ($chunk eq '|')) {
11129: $operand=$chunk;
11130: } else {
11131: my $new=directcondval($chunk);
11132: if ($operand eq '&') {
11133: $result=$result>$new?$new:$result;
11134: } else {
11135: $result=$result>$new?$result:$new;
11136: }
11137: }
11138: }
11139: }
11140: return $result;
11141: }
11142:
11143: # ---------------------------------------------------- Devalidate courseresdata
11144:
11145: sub devalidatecourseresdata {
11146: my ($coursenum,$coursedomain)=@_;
11147: my $hashid=$coursenum.':'.$coursedomain;
11148: &devalidate_cache_new('courseres',$hashid);
11149: }
11150:
11151:
11152: # --------------------------------------------------- Course Resourcedata Query
11153: #
11154: # Parameters:
11155: # $coursenum - Number of the course.
11156: # $coursedomain - Domain at which the course was created.
11157: # Returns:
11158: # A hash of the course parameters along (I think) with timestamps
11159: # and version info.
11160:
11161: sub get_courseresdata {
11162: my ($coursenum,$coursedomain)=@_;
11163: my $coursehom=&homeserver($coursenum,$coursedomain);
11164: my $hashid=$coursenum.':'.$coursedomain;
11165: my ($result,$cached)=&is_cached_new('courseres',$hashid);
11166: my %dumpreply;
11167: unless (defined($cached)) {
11168: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
11169: $result=\%dumpreply;
11170: my ($tmp) = keys(%dumpreply);
11171: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
11172: &do_cache_new('courseres',$hashid,$result,600);
11173: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
11174: return $tmp;
11175: } elsif ($tmp =~ /^(error)/) {
11176: $result=undef;
11177: &do_cache_new('courseres',$hashid,$result,600);
11178: }
11179: }
11180: return $result;
11181: }
11182:
11183: sub devalidateuserresdata {
11184: my ($uname,$udom)=@_;
11185: my $hashid="$udom:$uname";
11186: &devalidate_cache_new('userres',$hashid);
11187: }
11188:
11189: sub get_userresdata {
11190: my ($uname,$udom)=@_;
11191: #most student don\'t have any data set, check if there is some data
11192: if (&EXT_cache_status($udom,$uname)) { return undef; }
11193:
11194: my $hashid="$udom:$uname";
11195: my ($result,$cached)=&is_cached_new('userres',$hashid);
11196: if (!defined($cached)) {
11197: my %resourcedata=&dump('resourcedata',$udom,$uname);
11198: $result=\%resourcedata;
11199: &do_cache_new('userres',$hashid,$result,600);
11200: }
11201: my ($tmp)=keys(%$result);
11202: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
11203: return $result;
11204: }
11205: #error 2 occurs when the .db doesn't exist
11206: if ($tmp!~/error: 2 /) {
11207: if ((!defined($cached)) || ($tmp ne 'con_lost')) {
11208: &logthis("<font color=\"blue\">WARNING:".
11209: " Trying to get resource data for ".
11210: $uname." at ".$udom.": ".
11211: $tmp."</font>");
11212: }
11213: } elsif ($tmp=~/error: 2 /) {
11214: #&EXT_cache_set($udom,$uname);
11215: &do_cache_new('userres',$hashid,undef,600);
11216: undef($tmp); # not really an error so don't send it back
11217: }
11218: return $tmp;
11219: }
11220: #----------------------------------------------- resdata - return resource data
11221: # Purpose:
11222: # Return resource data for either users or for a course.
11223: # Parameters:
11224: # $name - Course/user name.
11225: # $domain - Name of the domain the user/course is registered on.
11226: # $type - Type of thing $name is (must be 'course' or 'user'
11227: # @which - Array of names of resources desired.
11228: # Returns:
11229: # The value of the first reasource in @which that is found in the
11230: # resource hash.
11231: # Exceptional Conditions:
11232: # If the $type passed in is not valid (not the string 'course' or
11233: # 'user', an undefined reference is returned.
11234: # If none of the resources are found, an undef is returned
11235: sub resdata {
11236: my ($name,$domain,$type,@which)=@_;
11237: my $result;
11238: if ($type eq 'course') {
11239: $result=&get_courseresdata($name,$domain);
11240: } elsif ($type eq 'user') {
11241: $result=&get_userresdata($name,$domain);
11242: }
11243: if (!ref($result)) { return $result; }
11244: foreach my $item (@which) {
11245: if (defined($result->{$item->[0]})) {
11246: return [$result->{$item->[0]},$item->[1]];
11247: }
11248: }
11249: return undef;
11250: }
11251:
11252: sub get_numsuppfiles {
11253: my ($cnum,$cdom,$ignorecache)=@_;
11254: my $hashid=$cnum.':'.$cdom;
11255: my ($suppcount,$cached);
11256: unless ($ignorecache) {
11257: ($suppcount,$cached) = &is_cached_new('suppcount',$hashid);
11258: }
11259: unless (defined($cached)) {
11260: my $chome=&homeserver($cnum,$cdom);
11261: unless ($chome eq 'no_host') {
11262: ($suppcount,my $errors) = (0,0);
11263: my $suppmap = 'supplemental.sequence';
11264: ($suppcount,$errors) =
11265: &Apache::loncommon::recurse_supplemental($cnum,$cdom,$suppmap,$suppcount,$errors);
11266: }
11267: &do_cache_new('suppcount',$hashid,$suppcount,600);
11268: }
11269: return $suppcount;
11270: }
11271:
11272: #
11273: # EXT resource caching routines
11274: #
11275:
11276: sub clear_EXT_cache_status {
11277: &delenv('cache.EXT.');
11278: }
11279:
11280: sub EXT_cache_status {
11281: my ($target_domain,$target_user) = @_;
11282: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11283: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
11284: # We know already the user has no data
11285: return 1;
11286: } else {
11287: return 0;
11288: }
11289: }
11290:
11291: sub EXT_cache_set {
11292: my ($target_domain,$target_user) = @_;
11293: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
11294: #&appenv({$cachename => time});
11295: }
11296:
11297: # --------------------------------------------------------- Value of a Variable
11298: sub EXT {
11299:
11300: my ($varname,$symbparm,$udom,$uname,$usection,$recurse,$cid)=@_;
11301: unless ($varname) { return ''; }
11302: #get real user name/domain, courseid and symb
11303: my $courseid;
11304: my $publicuser;
11305: if ($symbparm) {
11306: $symbparm=&get_symb_from_alias($symbparm);
11307: }
11308: if (!($uname && $udom)) {
11309: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
11310: if (!$symbparm) { $symbparm=$cursymb; }
11311: } else {
11312: $courseid=$env{'request.course.id'};
11313: }
11314: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
11315: my $rest;
11316: if (defined($therest[0])) {
11317: $rest=join('.',@therest);
11318: } else {
11319: $rest='';
11320: }
11321:
11322: my $qualifierrest=$qualifier;
11323: if ($rest) { $qualifierrest.='.'.$rest; }
11324: my $spacequalifierrest=$space;
11325: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
11326: if ($realm eq 'user') {
11327: # --------------------------------------------------------------- user.resource
11328: if ($space eq 'resource') {
11329: if ( (defined($Apache::lonhomework::parsing_a_problem)
11330: || defined($Apache::lonhomework::parsing_a_task))
11331: &&
11332: ($symbparm eq &symbread()) ) {
11333: # if we are in the middle of processing the resource the
11334: # get the value we are planning on committing
11335: if (defined($Apache::lonhomework::results{$qualifierrest})) {
11336: return $Apache::lonhomework::results{$qualifierrest};
11337: } else {
11338: return $Apache::lonhomework::history{$qualifierrest};
11339: }
11340: } else {
11341: my %restored;
11342: if ($publicuser || $env{'request.state'} eq 'construct') {
11343: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
11344: } else {
11345: %restored=&restore($symbparm,$courseid,$udom,$uname);
11346: }
11347: return $restored{$qualifierrest};
11348: }
11349: # ----------------------------------------------------------------- user.access
11350: } elsif ($space eq 'access') {
11351: # FIXME - not supporting calls for a specific user
11352: return &allowed($qualifier,$rest);
11353: # ------------------------------------------ user.preferences, user.environment
11354: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
11355: if (($uname eq $env{'user.name'}) &&
11356: ($udom eq $env{'user.domain'})) {
11357: return $env{join('.',('environment',$qualifierrest))};
11358: } else {
11359: my %returnhash;
11360: if (!$publicuser) {
11361: %returnhash=&userenvironment($udom,$uname,
11362: $qualifierrest);
11363: }
11364: return $returnhash{$qualifierrest};
11365: }
11366: # ----------------------------------------------------------------- user.course
11367: } elsif ($space eq 'course') {
11368: # FIXME - not supporting calls for a specific user
11369: return $env{join('.',('request.course',$qualifier))};
11370: # ------------------------------------------------------------------- user.role
11371: } elsif ($space eq 'role') {
11372: # FIXME - not supporting calls for a specific user
11373: my ($role,$where)=split(/\./,$env{'request.role'});
11374: if ($qualifier eq 'value') {
11375: return $role;
11376: } elsif ($qualifier eq 'extent') {
11377: return $where;
11378: }
11379: # ----------------------------------------------------------------- user.domain
11380: } elsif ($space eq 'domain') {
11381: return $udom;
11382: # ------------------------------------------------------------------- user.name
11383: } elsif ($space eq 'name') {
11384: return $uname;
11385: # ---------------------------------------------------- Any other user namespace
11386: } else {
11387: my %reply;
11388: if (!$publicuser) {
11389: %reply=&get($space,[$qualifierrest],$udom,$uname);
11390: }
11391: return $reply{$qualifierrest};
11392: }
11393: } elsif ($realm eq 'query') {
11394: # ---------------------------------------------- pull stuff out of query string
11395: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
11396: [$spacequalifierrest]);
11397: return $env{'form.'.$spacequalifierrest};
11398: } elsif ($realm eq 'request') {
11399: # ------------------------------------------------------------- request.browser
11400: if ($space eq 'browser') {
11401: return $env{'browser.'.$qualifier};
11402: # ------------------------------------------------------------ request.filename
11403: } else {
11404: return $env{'request.'.$spacequalifierrest};
11405: }
11406: } elsif ($realm eq 'course') {
11407: # ---------------------------------------------------------- course.description
11408: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
11409: } elsif ($realm eq 'resource') {
11410:
11411: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
11412: if (!$symbparm) { $symbparm=&symbread(); }
11413: }
11414:
11415: if ($qualifier eq '') {
11416: if ($space eq 'title') {
11417: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
11418: return &gettitle($symbparm);
11419: }
11420:
11421: if ($space eq 'map') {
11422: my ($map) = &decode_symb($symbparm);
11423: return &symbread($map);
11424: }
11425: if ($space eq 'maptitle') {
11426: my ($map) = &decode_symb($symbparm);
11427: return &gettitle($map);
11428: }
11429: if ($space eq 'filename') {
11430: if ($symbparm) {
11431: return &clutter((&decode_symb($symbparm))[2]);
11432: }
11433: return &hreflocation('',$env{'request.filename'});
11434: }
11435:
11436: if ((defined($courseid)) && ($courseid eq $env{'request.course.id'}) && $symbparm) {
11437: if ($space eq 'visibleparts') {
11438: my $navmap = Apache::lonnavmaps::navmap->new();
11439: my $item;
11440: if (ref($navmap)) {
11441: my $res = $navmap->getBySymb($symbparm);
11442: my $parts = $res->parts();
11443: if (ref($parts) eq 'ARRAY') {
11444: $item = join(',',@{$parts});
11445: }
11446: undef($navmap);
11447: }
11448: return $item;
11449: }
11450: }
11451: }
11452:
11453: my ($section, $group, @groups);
11454: my ($courselevelm,$courselevel);
11455: if (($courseid eq '') && ($cid)) {
11456: $courseid = $cid;
11457: }
11458: if (($symbparm && $courseid) &&
11459: (($courseid eq $env{'request.course.id'}) || ($courseid eq $cid))) {
11460:
11461: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
11462:
11463: # ----------------------------------------------------- Cascading lookup scheme
11464: my $symbp=$symbparm;
11465: my $mapp=&deversion((&decode_symb($symbp))[0]);
11466:
11467: my $symbparm=$symbp.'.'.$spacequalifierrest;
11468: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
11469:
11470: if (($env{'user.name'} eq $uname) &&
11471: ($env{'user.domain'} eq $udom)) {
11472: $section=$env{'request.course.sec'};
11473: @groups = split(/:/,$env{'request.course.groups'});
11474: @groups=&sort_course_groups($courseid,@groups);
11475: } else {
11476: if (! defined($usection)) {
11477: $section=&getsection($udom,$uname,$courseid);
11478: } else {
11479: $section = $usection;
11480: }
11481: @groups = &get_users_groups($udom,$uname,$courseid);
11482: }
11483:
11484: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
11485: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
11486: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
11487:
11488: $courselevel=$courseid.'.'.$spacequalifierrest;
11489: my $courselevelr=$courseid.'.'.$symbparm;
11490: $courselevelm=$courseid.'.'.$mapparm;
11491:
11492: # ----------------------------------------------------------- first, check user
11493:
11494: my $userreply=&resdata($uname,$udom,'user',
11495: ([$courselevelr,'resource'],
11496: [$courselevelm,'map' ],
11497: [$courselevel, 'course' ]));
11498: if (defined($userreply)) { return &get_reply($userreply); }
11499:
11500: # ------------------------------------------------ second, check some of course
11501: my $coursereply;
11502: if (@groups > 0) {
11503: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
11504: $mapparm,$spacequalifierrest);
11505: if (defined($coursereply)) { return &get_reply($coursereply); }
11506: }
11507:
11508: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11509: $env{'course.'.$courseid.'.domain'},
11510: 'course',
11511: ([$seclevelr, 'resource'],
11512: [$seclevelm, 'map' ],
11513: [$seclevel, 'course' ],
11514: [$courselevelr,'resource']));
11515: if (defined($coursereply)) { return &get_reply($coursereply); }
11516:
11517: # ------------------------------------------------------ third, check map parms
11518: my %parmhash=();
11519: my $thisparm='';
11520: if (tie(%parmhash,'GDBM_File',
11521: $env{'request.course.fn'}.'_parms.db',
11522: &GDBM_READER(),0640)) {
11523: $thisparm=$parmhash{$symbparm};
11524: untie(%parmhash);
11525: }
11526: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
11527: }
11528: # ------------------------------------------ fourth, look in resource metadata
11529:
11530: $spacequalifierrest=~s/\./\_/;
11531: my $filename;
11532: if (!$symbparm) { $symbparm=&symbread(); }
11533: if ($symbparm) {
11534: $filename=(&decode_symb($symbparm))[2];
11535: } else {
11536: $filename=$env{'request.filename'};
11537: }
11538: my $metadata=&metadata($filename,$spacequalifierrest);
11539: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11540: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
11541: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
11542:
11543: # ---------------------------------------------- fourth, look in rest of course
11544: if ($symbparm && defined($courseid) &&
11545: $courseid eq $env{'request.course.id'}) {
11546: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
11547: $env{'course.'.$courseid.'.domain'},
11548: 'course',
11549: ([$courselevelm,'map' ],
11550: [$courselevel, 'course']));
11551: if (defined($coursereply)) { return &get_reply($coursereply); }
11552: }
11553: # ------------------------------------------------------------------ Cascade up
11554: unless ($space eq '0') {
11555: my @parts=split(/_/,$space);
11556: my $id=pop(@parts);
11557: my $part=join('_',@parts);
11558: if ($part eq '') { $part='0'; }
11559: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
11560: $symbparm,$udom,$uname,$section,1);
11561: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
11562: }
11563: if ($recurse) { return undef; }
11564: my $pack_def=&packages_tab_default($filename,$varname);
11565: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
11566: # ---------------------------------------------------- Any other user namespace
11567: } elsif ($realm eq 'environment') {
11568: # ----------------------------------------------------------------- environment
11569: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
11570: return $env{'environment.'.$spacequalifierrest};
11571: } else {
11572: if ($uname eq 'anonymous' && $udom eq '') {
11573: return '';
11574: }
11575: my %returnhash=&userenvironment($udom,$uname,
11576: $spacequalifierrest);
11577: return $returnhash{$spacequalifierrest};
11578: }
11579: } elsif ($realm eq 'system') {
11580: # ----------------------------------------------------------------- system.time
11581: if ($space eq 'time') {
11582: return time;
11583: }
11584: } elsif ($realm eq 'server') {
11585: # ----------------------------------------------------------------- system.time
11586: if ($space eq 'name') {
11587: return $ENV{'SERVER_NAME'};
11588: }
11589: }
11590: return '';
11591: }
11592:
11593: sub get_reply {
11594: my ($reply_value) = @_;
11595: if (ref($reply_value) eq 'ARRAY') {
11596: if (wantarray) {
11597: return @$reply_value;
11598: }
11599: return $reply_value->[0];
11600: } else {
11601: return $reply_value;
11602: }
11603: }
11604:
11605: sub check_group_parms {
11606: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
11607: my @groupitems = ();
11608: my $resultitem;
11609: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
11610: foreach my $group (@{$groups}) {
11611: foreach my $level (@levels) {
11612: my $item = $courseid.'.['.$group.'].'.$level->[0];
11613: push(@groupitems,[$item,$level->[1]]);
11614: }
11615: }
11616: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
11617: $env{'course.'.$courseid.'.domain'},
11618: 'course',@groupitems);
11619: return $coursereply;
11620: }
11621:
11622: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
11623: my ($courseid,@groups) = @_;
11624: @groups = sort(@groups);
11625: return @groups;
11626: }
11627:
11628: sub packages_tab_default {
11629: my ($uri,$varname)=@_;
11630: my (undef,$part,$name)=split(/\./,$varname);
11631:
11632: my (@extension,@specifics,$do_default);
11633: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
11634: my ($pack_type,$pack_part)=split(/_/,$package,2);
11635: if ($pack_type eq 'default') {
11636: $do_default=1;
11637: } elsif ($pack_type eq 'extension') {
11638: push(@extension,[$package,$pack_type,$pack_part]);
11639: } elsif ($pack_part eq $part || $pack_type eq 'part') {
11640: # only look at packages defaults for packages that this id is
11641: push(@specifics,[$package,$pack_type,$pack_part]);
11642: }
11643: }
11644: # first look for a package that matches the requested part id
11645: foreach my $package (@specifics) {
11646: my (undef,$pack_type,$pack_part)=@{$package};
11647: next if ($pack_part ne $part);
11648: if (defined($packagetab{"$pack_type&$name&default"})) {
11649: return $packagetab{"$pack_type&$name&default"};
11650: }
11651: }
11652: # look for any possible matching non extension_ package
11653: foreach my $package (@specifics) {
11654: my (undef,$pack_type,$pack_part)=@{$package};
11655: if (defined($packagetab{"$pack_type&$name&default"})) {
11656: return $packagetab{"$pack_type&$name&default"};
11657: }
11658: if ($pack_type eq 'part') { $pack_part='0'; }
11659: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
11660: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
11661: }
11662: }
11663: # look for any posible extension_ match
11664: foreach my $package (@extension) {
11665: my ($package,$pack_type)=@{$package};
11666: if (defined($packagetab{"$pack_type&$name&default"})) {
11667: return $packagetab{"$pack_type&$name&default"};
11668: }
11669: if (defined($packagetab{$package."&$name&default"})) {
11670: return $packagetab{$package."&$name&default"};
11671: }
11672: }
11673: # look for a global default setting
11674: if ($do_default && defined($packagetab{"default&$name&default"})) {
11675: return $packagetab{"default&$name&default"};
11676: }
11677: return undef;
11678: }
11679:
11680: sub add_prefix_and_part {
11681: my ($prefix,$part)=@_;
11682: my $keyroot;
11683: if (defined($prefix) && $prefix !~ /^__/) {
11684: # prefix that has a part already
11685: $keyroot=$prefix;
11686: } elsif (defined($prefix)) {
11687: # prefix that is missing a part
11688: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
11689: } else {
11690: # no prefix at all
11691: if (defined($part)) { $keyroot='_'.$part; }
11692: }
11693: return $keyroot;
11694: }
11695:
11696: # ---------------------------------------------------------------- Get metadata
11697:
11698: my %metaentry;
11699: my %importedpartids;
11700: my %importedrespids;
11701: sub metadata {
11702: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
11703: $uri=&declutter($uri);
11704: # if it is a non metadata possible uri return quickly
11705: if (($uri eq '') ||
11706: (($uri =~ m|^/*adm/|) &&
11707: ($uri !~ m|^adm/includes|) && ($uri !~ m{/(smppg|bulletinboard)$})) ||
11708: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
11709: return undef;
11710: }
11711: if (($uri =~ /^priv/ || $uri=~m{^home/httpd/html/priv})
11712: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
11713: return undef;
11714: }
11715: my $filename=$uri;
11716: $uri=~s/\.meta$//;
11717: #
11718: # Is the metadata already cached?
11719: # Look at timestamp of caching
11720: # Everything is cached by the main uri, libraries are never directly cached
11721: #
11722: if (!defined($liburi)) {
11723: my ($result,$cached)=&is_cached_new('meta',$uri);
11724: if (defined($cached)) { return $result->{':'.$what}; }
11725: }
11726: {
11727: # Imported parts would go here
11728: my @origfiletagids=();
11729: my $importedparts=0;
11730:
11731: # Imported responseids would go here
11732: my $importedresponses=0;
11733: #
11734: # Is this a recursive call for a library?
11735: #
11736: # if (! exists($metacache{$uri})) {
11737: # $metacache{$uri}={};
11738: # }
11739: my $cachetime = 60*60;
11740: if ($liburi) {
11741: $liburi=&declutter($liburi);
11742: $filename=$liburi;
11743: } else {
11744: &devalidate_cache_new('meta',$uri);
11745: undef(%metaentry);
11746: }
11747: my %metathesekeys=();
11748: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
11749: my $metastring;
11750: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
11751: my $which = &hreflocation('','/'.($liburi || $uri));
11752: $metastring =
11753: &Apache::lonnet::ssi_body($which,
11754: ('grade_target' => 'meta'));
11755: $cachetime = 1; # only want this cached in the child not long term
11756: } elsif (($uri !~ m -^(editupload)/-) &&
11757: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
11758: my $file=&filelocation('',&clutter($filename));
11759: #push(@{$metaentry{$uri.'.file'}},$file);
11760: $metastring=&getfile($file);
11761: }
11762: my $parser=HTML::LCParser->new(\$metastring);
11763: my $token;
11764: undef %metathesekeys;
11765: while ($token=$parser->get_token) {
11766: if ($token->[0] eq 'S') {
11767: if (defined($token->[2]->{'package'})) {
11768: #
11769: # This is a package - get package info
11770: #
11771: my $package=$token->[2]->{'package'};
11772: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11773: if (defined($token->[2]->{'id'})) {
11774: $keyroot.='_'.$token->[2]->{'id'};
11775: }
11776: if ($metaentry{':packages'}) {
11777: $metaentry{':packages'}.=','.$package.$keyroot;
11778: } else {
11779: $metaentry{':packages'}=$package.$keyroot;
11780: }
11781: foreach my $pack_entry (keys(%packagetab)) {
11782: my $part=$keyroot;
11783: $part=~s/^\_//;
11784: if ($pack_entry=~/^\Q$package\E\&/ ||
11785: $pack_entry=~/^\Q$package\E_0\&/) {
11786: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
11787: # ignore package.tab specified default values
11788: # here &package_tab_default() will fetch those
11789: if ($subp eq 'default') { next; }
11790: my $value=$packagetab{$pack_entry};
11791: my $unikey;
11792: if ($pack =~ /_0$/) {
11793: $unikey='parameter_0_'.$name;
11794: $part=0;
11795: } else {
11796: $unikey='parameter'.$keyroot.'_'.$name;
11797: }
11798: if ($subp eq 'display') {
11799: $value.=' [Part: '.$part.']';
11800: }
11801: $metaentry{':'.$unikey.'.part'}=$part;
11802: $metathesekeys{$unikey}=1;
11803: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
11804: $metaentry{':'.$unikey.'.'.$subp}=$value;
11805: }
11806: if (defined($metaentry{':'.$unikey.'.default'})) {
11807: $metaentry{':'.$unikey}=
11808: $metaentry{':'.$unikey.'.default'};
11809: }
11810: }
11811: }
11812: } else {
11813: #
11814: # This is not a package - some other kind of start tag
11815: #
11816: my $entry=$token->[1];
11817: my $unikey='';
11818:
11819: if ($entry eq 'import') {
11820: #
11821: # Importing a library here
11822: #
11823: my $location=$parser->get_text('/import');
11824: my $dir=$filename;
11825: $dir=~s|[^/]*$||;
11826: $location=&filelocation($dir,$location);
11827:
11828: my $importid=$token->[2]->{'id'};
11829: my $importmode=$token->[2]->{'importmode'};
11830: #
11831: # Check metadata for imported file to
11832: # see if it contained response items
11833: #
11834: my %currmetaentry = %metaentry;
11835: my $libresponseorder = &metadata($location,'responseorder');
11836: my $origfile;
11837: if ($libresponseorder ne '') {
11838: if ($#origfiletagids<0) {
11839: undef(%importedrespids);
11840: undef(%importedpartids);
11841: }
11842: @{$importedrespids{$importid}} = split(/\s*,\s*/,$libresponseorder);
11843: if (@{$importedrespids{$importid}} > 0) {
11844: $importedresponses = 1;
11845: # We need to get the original file and the imported file to get the response order correct
11846: # Load and inspect original file
11847: if ($#origfiletagids<0) {
11848: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11849: $origfile=&getfile($origfilelocation);
11850: @origfiletagids=($origfile=~/<((?:\w+)response|import|part)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11851: }
11852: }
11853: }
11854: # Do not overwrite contents of %metaentry hash for resource itself with
11855: # hash populated for imported library file
11856: %metaentry = %currmetaentry;
11857: undef(%currmetaentry);
11858: if ($importmode eq 'problem') {
11859: # Import as problem/response
11860: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11861: } elsif ($importmode eq 'part') {
11862: # Import as part(s)
11863: $importedparts=1;
11864: # We need to get the original file and the imported file to get the part order correct
11865: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
11866: # Load and inspect original file if we didn't do that already
11867: if ($#origfiletagids<0) {
11868: undef(%importedrespids);
11869: undef(%importedpartids);
11870: if ($origfile eq '') {
11871: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
11872: $origfile=&getfile($origfilelocation);
11873: @origfiletagids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11874: }
11875: }
11876:
11877: # Load and inspect imported file
11878: my $impfile=&getfile($location);
11879: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
11880: if ($#impfilepartids>=0) {
11881: # This problem had parts
11882: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
11883: } else {
11884: # Importing by turning a single problem into a problem part
11885: # It gets the import-tags ID as part-ID
11886: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
11887: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
11888: }
11889: } else {
11890: # Normal import
11891: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
11892: if (defined($token->[2]->{'id'})) {
11893: $unikey.='_'.$token->[2]->{'id'};
11894: }
11895: }
11896:
11897: if ($depthcount<20) {
11898: my $metadata =
11899: &metadata($uri,'keys', $location,$unikey,
11900: $depthcount+1);
11901: foreach my $meta (split(',',$metadata)) {
11902: $metaentry{':'.$meta}=$metaentry{':'.$meta};
11903: $metathesekeys{$meta}=1;
11904: }
11905:
11906: }
11907: } else {
11908: #
11909: # Not importing, some other kind of non-package, non-library start tag
11910: #
11911: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
11912: if (defined($token->[2]->{'id'})) {
11913: $unikey.='_'.$token->[2]->{'id'};
11914: }
11915: if (defined($token->[2]->{'name'})) {
11916: $unikey.='_'.$token->[2]->{'name'};
11917: }
11918: $metathesekeys{$unikey}=1;
11919: foreach my $param (@{$token->[3]}) {
11920: $metaentry{':'.$unikey.'.'.$param} =
11921: $token->[2]->{$param};
11922: }
11923: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
11924: my $default=$metaentry{':'.$unikey.'.default'};
11925: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
11926: # only ws inside the tag, and not in default, so use default
11927: # as value
11928: $metaentry{':'.$unikey}=$default;
11929: } elsif ( $internaltext =~ /\S/ ) {
11930: # something interesting inside the tag
11931: $metaentry{':'.$unikey}=$internaltext;
11932: } else {
11933: # no interesting values, don't set a default
11934: }
11935: # end of not-a-package not-a-library import
11936: }
11937: # end of not-a-package start tag
11938: }
11939: # the next is the end of "start tag"
11940: }
11941: }
11942: my ($extension) = ($uri =~ /\.(\w+)$/);
11943: $extension = lc($extension);
11944: if ($extension eq 'htm') { $extension='html'; }
11945:
11946: foreach my $key (keys(%packagetab)) {
11947: #no specific packages #how's our extension
11948: if ($key!~/^extension_\Q$extension\E&/) { next; }
11949: &metadata_create_package_def($uri,$key,'extension_'.$extension,
11950: \%metathesekeys);
11951: }
11952:
11953: if (!exists($metaentry{':packages'})
11954: || $packagetab{"import_defaults&extension_$extension"}) {
11955: foreach my $key (keys(%packagetab)) {
11956: #no specific packages well let's get default then
11957: if ($key!~/^default&/) { next; }
11958: &metadata_create_package_def($uri,$key,'default',
11959: \%metathesekeys);
11960: }
11961: }
11962: # are there custom rights to evaluate
11963: if ($metaentry{':copyright'} eq 'custom') {
11964:
11965: #
11966: # Importing a rights file here
11967: #
11968: unless ($depthcount) {
11969: my $location=$metaentry{':customdistributionfile'};
11970: my $dir=$filename;
11971: $dir=~s|[^/]*$||;
11972: $location=&filelocation($dir,$location);
11973: my $rights_metadata =
11974: &metadata($uri,'keys',$location,'_rights',
11975: $depthcount+1);
11976: foreach my $rights (split(',',$rights_metadata)) {
11977: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
11978: $metathesekeys{$rights}=1;
11979: }
11980: }
11981: }
11982: # uniqifiy package listing
11983: my %seen;
11984: my @uniq_packages =
11985: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
11986: $metaentry{':packages'} = join(',',@uniq_packages);
11987:
11988: if (($importedresponses) || ($importedparts)) {
11989: if ($importedparts) {
11990: # We had imported parts and need to rebuild partorder
11991: $metaentry{':partorder'}='';
11992: $metathesekeys{'partorder'}=1;
11993: }
11994: if ($importedresponses) {
11995: # We had imported responses and need to rebuild responseorder
11996: $metaentry{':responseorder'}='';
11997: $metathesekeys{'responseorder'}=1;
11998: }
11999: for (my $index=0;$index<$#origfiletagids;$index+=2) {
12000: my $origid = $origfiletagids[$index+1];
12001: if ($origfiletagids[$index] eq 'part') {
12002: # Original part, part of the problem
12003: if ($importedparts) {
12004: $metaentry{':partorder'}.=','.$origid;
12005: }
12006: } elsif ($origfiletagids[$index] eq 'import') {
12007: if ($importedparts) {
12008: # We have imported parts at this position
12009: $metaentry{':partorder'}.=','.$importedpartids{$origid};
12010: }
12011: if ($importedresponses) {
12012: # We have imported responses at this position
12013: if (ref($importedrespids{$origid}) eq 'ARRAY') {
12014: $metaentry{':responseorder'}.=','.join(',',map { $origid.'_'.$_ } @{$importedrespids{$origid}});
12015: }
12016: }
12017: } else {
12018: # Original response item, part of the problem
12019: if ($importedresponses) {
12020: $metaentry{':responseorder'}.=','.$origid;
12021: }
12022: }
12023: }
12024: if ($importedparts) {
12025: $metaentry{':partorder'}=~s/^\,//;
12026: }
12027: if ($importedresponses) {
12028: $metaentry{':responseorder'}=~s/^\,//;
12029: }
12030: }
12031:
12032: $metaentry{':keys'} = join(',',keys(%metathesekeys));
12033: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
12034: $metaentry{':allpossiblekeys'}=join(',',keys(%metathesekeys));
12035: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
12036: # this is the end of "was not already recently cached
12037: }
12038: return $metaentry{':'.$what};
12039: }
12040:
12041: sub metadata_create_package_def {
12042: my ($uri,$key,$package,$metathesekeys)=@_;
12043: my ($pack,$name,$subp)=split(/\&/,$key);
12044: if ($subp eq 'default') { next; }
12045:
12046: if (defined($metaentry{':packages'})) {
12047: $metaentry{':packages'}.=','.$package;
12048: } else {
12049: $metaentry{':packages'}=$package;
12050: }
12051: my $value=$packagetab{$key};
12052: my $unikey;
12053: $unikey='parameter_0_'.$name;
12054: $metaentry{':'.$unikey.'.part'}=0;
12055: $$metathesekeys{$unikey}=1;
12056: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
12057: $metaentry{':'.$unikey.'.'.$subp}=$value;
12058: }
12059: if (defined($metaentry{':'.$unikey.'.default'})) {
12060: $metaentry{':'.$unikey}=
12061: $metaentry{':'.$unikey.'.default'};
12062: }
12063: }
12064:
12065: sub metadata_generate_part0 {
12066: my ($metadata,$metacache,$uri) = @_;
12067: my %allnames;
12068: foreach my $metakey (keys(%$metadata)) {
12069: if ($metakey=~/^parameter\_(.*)/) {
12070: my $part=$$metacache{':'.$metakey.'.part'};
12071: my $name=$$metacache{':'.$metakey.'.name'};
12072: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
12073: $allnames{$name}=$part;
12074: }
12075: }
12076: }
12077: foreach my $name (keys(%allnames)) {
12078: $$metadata{"parameter_0_$name"}=1;
12079: my $key=":parameter_0_$name";
12080: $$metacache{"$key.part"}='0';
12081: $$metacache{"$key.name"}=$name;
12082: $$metacache{"$key.type"}=$$metacache{':parameter_'.
12083: $allnames{$name}.'_'.$name.
12084: '.type'};
12085: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
12086: '.display'};
12087: my $expr='[Part: '.$allnames{$name}.']';
12088: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
12089: $$metacache{"$key.display"}=$olddis;
12090: }
12091: }
12092:
12093: # ------------------------------------------------------ Devalidate title cache
12094:
12095: sub devalidate_title_cache {
12096: my ($url)=@_;
12097: if (!$env{'request.course.id'}) { return; }
12098: my $symb=&symbread($url);
12099: if (!$symb) { return; }
12100: my $key=$env{'request.course.id'}."\0".$symb;
12101: &devalidate_cache_new('title',$key);
12102: }
12103:
12104: # ------------------------------------------------- Get the title of a course
12105:
12106: sub current_course_title {
12107: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
12108: }
12109: # ------------------------------------------------- Get the title of a resource
12110:
12111: sub gettitle {
12112: my $urlsymb=shift;
12113: my $symb=&symbread($urlsymb);
12114: if ($symb) {
12115: my $key=$env{'request.course.id'}."\0".$symb;
12116: my ($result,$cached)=&is_cached_new('title',$key);
12117: if (defined($cached)) {
12118: return $result;
12119: }
12120: my ($map,$resid,$url)=&decode_symb($symb);
12121: my $title='';
12122: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
12123: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
12124: } else {
12125: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12126: &GDBM_READER(),0640)) {
12127: my $mapid=$bighash{'map_pc_'.&clutter($map)};
12128: $title=$bighash{'title_'.$mapid.'.'.$resid};
12129: untie(%bighash);
12130: }
12131: }
12132: $title=~s/\&colon\;/\:/gs;
12133: if ($title) {
12134: # Remember both $symb and $title for dynamic metadata
12135: $accesshash{$symb.'___crstitle'}=$title;
12136: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
12137: # Cache this title and then return it
12138: return &do_cache_new('title',$key,$title,600);
12139: }
12140: $urlsymb=$url;
12141: }
12142: my $title=&metadata($urlsymb,'title');
12143: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
12144: return $title;
12145: }
12146:
12147: sub get_slot {
12148: my ($which,$cnum,$cdom)=@_;
12149: if (!$cnum || !$cdom) {
12150: (undef,my $courseid)=&whichuser();
12151: $cdom=$env{'course.'.$courseid.'.domain'};
12152: $cnum=$env{'course.'.$courseid.'.num'};
12153: }
12154: my $key=join("\0",'slots',$cdom,$cnum,$which);
12155: my %slotinfo;
12156: if (exists($remembered{$key})) {
12157: $slotinfo{$which} = $remembered{$key};
12158: } else {
12159: %slotinfo=&get('slots',[$which],$cdom,$cnum);
12160: &Apache::lonhomework::showhash(%slotinfo);
12161: my ($tmp)=keys(%slotinfo);
12162: if ($tmp=~/^error:/) { return (); }
12163: $remembered{$key} = $slotinfo{$which};
12164: }
12165: if (ref($slotinfo{$which}) eq 'HASH') {
12166: return %{$slotinfo{$which}};
12167: }
12168: return $slotinfo{$which};
12169: }
12170:
12171: sub get_reservable_slots {
12172: my ($cnum,$cdom,$uname,$udom) = @_;
12173: my $now = time;
12174: my $reservable_info;
12175: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
12176: if (exists($remembered{$key})) {
12177: $reservable_info = $remembered{$key};
12178: } else {
12179: my %resv;
12180: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
12181: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
12182: $reservable_info = \%resv;
12183: $remembered{$key} = $reservable_info;
12184: }
12185: return $reservable_info;
12186: }
12187:
12188: sub get_course_slots {
12189: my ($cnum,$cdom) = @_;
12190: my $hashid=$cnum.':'.$cdom;
12191: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
12192: if (defined($cached)) {
12193: if (ref($result) eq 'HASH') {
12194: return %{$result};
12195: }
12196: } else {
12197: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
12198: my ($tmp) = keys(%slots);
12199: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
12200: &do_cache_new('allslots',$hashid,\%slots,600);
12201: return %slots;
12202: }
12203: }
12204: return;
12205: }
12206:
12207: sub devalidate_slots_cache {
12208: my ($cnum,$cdom)=@_;
12209: my $hashid=$cnum.':'.$cdom;
12210: &devalidate_cache_new('allslots',$hashid);
12211: }
12212:
12213: sub get_coursechange {
12214: my ($cdom,$cnum) = @_;
12215: if ($cdom eq '' || $cnum eq '') {
12216: return unless ($env{'request.course.id'});
12217: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
12218: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
12219: }
12220: my $hashid=$cdom.'_'.$cnum;
12221: my ($change,$cached)=&is_cached_new('crschange',$hashid);
12222: if ((defined($cached)) && ($change ne '')) {
12223: return $change;
12224: } else {
12225: my %crshash;
12226: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
12227: if ($crshash{'internal.contentchange'} eq '') {
12228: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
12229: if ($change eq '') {
12230: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
12231: $change = $crshash{'internal.created'};
12232: }
12233: } else {
12234: $change = $crshash{'internal.contentchange'};
12235: }
12236: my $cachetime = 600;
12237: &do_cache_new('crschange',$hashid,$change,$cachetime);
12238: }
12239: return $change;
12240: }
12241:
12242: sub devalidate_coursechange_cache {
12243: my ($cnum,$cdom)=@_;
12244: my $hashid=$cnum.':'.$cdom;
12245: &devalidate_cache_new('crschange',$hashid);
12246: }
12247:
12248: # ------------------------------------------------- Update symbolic store links
12249:
12250: sub symblist {
12251: my ($mapname,%newhash)=@_;
12252: $mapname=&deversion(&declutter($mapname));
12253: my %hash;
12254: if (($env{'request.course.fn'}) && (%newhash)) {
12255: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12256: &GDBM_WRCREAT(),0640)) {
12257: foreach my $url (keys(%newhash)) {
12258: next if ($url eq 'last_known'
12259: && $env{'form.no_update_last_known'});
12260: $hash{declutter($url)}=&encode_symb($mapname,
12261: $newhash{$url}->[1],
12262: $newhash{$url}->[0]);
12263: }
12264: if (untie(%hash)) {
12265: return 'ok';
12266: }
12267: }
12268: }
12269: return 'error';
12270: }
12271:
12272: # --------------------------------------------------------------- Verify a symb
12273:
12274: sub symbverify {
12275: my ($symb,$thisurl,$encstate)=@_;
12276: my $thisfn=$thisurl;
12277: $thisfn=&declutter($thisfn);
12278: # direct jump to resource in page or to a sequence - will construct own symbs
12279: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
12280: # check URL part
12281: my ($map,$resid,$url)=&decode_symb($symb);
12282:
12283: unless ($url eq $thisfn) { return 0; }
12284:
12285: $symb=&symbclean($symb);
12286: $thisurl=&deversion($thisurl);
12287: $thisfn=&deversion($thisfn);
12288:
12289: my %bighash;
12290: my $okay=0;
12291:
12292: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12293: &GDBM_READER(),0640)) {
12294: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
12295: $thisurl =~ s/\?.+$//;
12296: if ($map =~ m{^uploaded/.+\.page$}) {
12297: $thisurl =~ s{^(/adm/wrapper|)/ext/}{http://};
12298: $thisurl =~ s{^\Qhttp://https://\E}{https://};
12299: }
12300: }
12301: my $ids;
12302: if ($map =~ m{^uploaded/.+\.page$}) {
12303: $ids=$bighash{'ids_'.&clutter_with_no_wrapper($thisurl)};
12304: } else {
12305: $ids=$bighash{'ids_'.&clutter($thisurl)};
12306: }
12307: unless ($ids) {
12308: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
12309: $ids=$bighash{$idkey};
12310: }
12311: if ($ids) {
12312: # ------------------------------------------------------------------- Has ID(s)
12313: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
12314: $symb =~ s/\?.+$//;
12315: }
12316: foreach my $id (split(/\,/,$ids)) {
12317: my ($mapid,$resid)=split(/\./,$id);
12318: if (
12319: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
12320: eq $symb) {
12321: if (ref($encstate)) {
12322: $$encstate = $bighash{'encrypted_'.$id};
12323: }
12324: if (($env{'request.role.adv'}) ||
12325: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
12326: ($thisurl eq '/adm/navmaps')) {
12327: $okay=1;
12328: last;
12329: }
12330: }
12331: }
12332: }
12333: untie(%bighash);
12334: }
12335: return $okay;
12336: }
12337:
12338: # --------------------------------------------------------------- Clean-up symb
12339:
12340: sub symbclean {
12341: my $symb=shift;
12342: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12343: # remove version from map
12344: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
12345:
12346: # remove version from URL
12347: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
12348:
12349: # remove wrapper
12350:
12351: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
12352: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
12353: return $symb;
12354: }
12355:
12356: # ---------------------------------------------- Split symb to find map and url
12357:
12358: sub encode_symb {
12359: my ($map,$resid,$url)=@_;
12360: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
12361: }
12362:
12363: sub decode_symb {
12364: my $symb=shift;
12365: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
12366: my ($map,$resid,$url)=split(/___/,$symb);
12367: return (&fixversion($map),$resid,&fixversion($url));
12368: }
12369:
12370: sub fixversion {
12371: my $fn=shift;
12372: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
12373: my %bighash;
12374: my $uri=&clutter($fn);
12375: my $key=$env{'request.course.id'}.'_'.$uri;
12376: # is this cached?
12377: my ($result,$cached)=&is_cached_new('courseresversion',$key);
12378: if (defined($cached)) { return $result; }
12379: # unfortunately not cached, or expired
12380: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12381: &GDBM_READER(),0640)) {
12382: if ($bighash{'version_'.$uri}) {
12383: my $version=$bighash{'version_'.$uri};
12384: unless (($version eq 'mostrecent') ||
12385: ($version==&getversion($uri))) {
12386: $uri=~s/\.(\w+)$/\.$version\.$1/;
12387: }
12388: }
12389: untie %bighash;
12390: }
12391: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
12392: }
12393:
12394: sub deversion {
12395: my $url=shift;
12396: $url=~s/\.\d+\.(\w+)$/\.$1/;
12397: return $url;
12398: }
12399:
12400: # ------------------------------------------------------ Return symb list entry
12401:
12402: sub symbread {
12403: my ($thisfn,$donotrecurse,$ignorecachednull,$checkforblock,$possibles)=@_;
12404: my $cache_str='request.symbread.cached.'.$thisfn;
12405: if (defined($env{$cache_str})) {
12406: if ($ignorecachednull) {
12407: return $env{$cache_str} unless ($env{$cache_str} eq '');
12408: } else {
12409: return $env{$cache_str};
12410: }
12411: }
12412: # no filename provided? try from environment
12413: unless ($thisfn) {
12414: if ($env{'request.symb'}) {
12415: return $env{$cache_str}=&symbclean($env{'request.symb'});
12416: }
12417: $thisfn=$env{'request.filename'};
12418: }
12419: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
12420: # is that filename actually a symb? Verify, clean, and return
12421: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
12422: if (&symbverify($thisfn,$1)) {
12423: return $env{$cache_str}=&symbclean($thisfn);
12424: }
12425: }
12426: $thisfn=declutter($thisfn);
12427: my %hash;
12428: my %bighash;
12429: my $syval='';
12430: if (($env{'request.course.fn'}) && ($thisfn)) {
12431: my $targetfn = $thisfn;
12432: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
12433: $targetfn = 'adm/wrapper/'.$thisfn;
12434: }
12435: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
12436: $targetfn=$1;
12437: }
12438: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
12439: &GDBM_READER(),0640)) {
12440: $syval=$hash{$targetfn};
12441: untie(%hash);
12442: }
12443: # ---------------------------------------------------------- There was an entry
12444: if ($syval) {
12445: #unless ($syval=~/\_\d+$/) {
12446: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
12447: #&appenv({'request.ambiguous' => $thisfn});
12448: #return $env{$cache_str}='';
12449: #}
12450: #$syval.=$1;
12451: #}
12452: } else {
12453: # ------------------------------------------------------- Was not in symb table
12454: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
12455: &GDBM_READER(),0640)) {
12456: # ---------------------------------------------- Get ID(s) for current resource
12457: my $ids=$bighash{'ids_'.&clutter($thisfn)};
12458: unless ($ids) {
12459: $ids=$bighash{'ids_/'.$thisfn};
12460: }
12461: unless ($ids) {
12462: # alias?
12463: $ids=$bighash{'mapalias_'.$thisfn};
12464: }
12465: if ($ids) {
12466: # ------------------------------------------------------------------- Has ID(s)
12467: my @possibilities=split(/\,/,$ids);
12468: if ($#possibilities==0) {
12469: # ----------------------------------------------- There is only one possibility
12470: my ($mapid,$resid)=split(/\./,$ids);
12471: $syval=&encode_symb($bighash{'map_id_'.$mapid},
12472: $resid,$thisfn);
12473: if (ref($possibles) eq 'HASH') {
12474: $possibles->{$syval} = 1;
12475: }
12476: if ($checkforblock) {
12477: my @blockers = &has_comm_blocking('bre',$syval,$bighash{'src_'.$ids});
12478: if (@blockers) {
12479: $syval = '';
12480: return;
12481: }
12482: }
12483: } elsif ((!$donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12484: # ------------------------------------------ There is more than one possibility
12485: my $realpossible=0;
12486: foreach my $id (@possibilities) {
12487: my $file=$bighash{'src_'.$id};
12488: my $canaccess;
12489: if (($donotrecurse) || ($checkforblock) || (ref($possibles) eq 'HASH')) {
12490: $canaccess = 1;
12491: } else {
12492: $canaccess = &allowed('bre',$file);
12493: }
12494: if ($canaccess) {
12495: my ($mapid,$resid)=split(/\./,$id);
12496: if ($bighash{'map_type_'.$mapid} ne 'page') {
12497: my $poss_syval=&encode_symb($bighash{'map_id_'.$mapid},
12498: $resid,$thisfn);
12499: if (ref($possibles) eq 'HASH') {
12500: $possibles->{$syval} = 1;
12501: }
12502: if ($checkforblock) {
12503: my @blockers = &has_comm_blocking('bre',$poss_syval,$file);
12504: unless (@blockers > 0) {
12505: $syval = $poss_syval;
12506: $realpossible++;
12507: }
12508: } else {
12509: $syval = $poss_syval;
12510: $realpossible++;
12511: }
12512: }
12513: }
12514: }
12515: if ($realpossible!=1) { $syval=''; }
12516: } else {
12517: $syval='';
12518: }
12519: }
12520: untie(%bighash);
12521: }
12522: }
12523: if ($syval) {
12524: return $env{$cache_str}=$syval;
12525: }
12526: }
12527: &appenv({'request.ambiguous' => $thisfn});
12528: return $env{$cache_str}='';
12529: }
12530:
12531: # ---------------------------------------------------------- Return random seed
12532:
12533: sub numval {
12534: my $txt=shift;
12535: $txt=~tr/A-J/0-9/;
12536: $txt=~tr/a-j/0-9/;
12537: $txt=~tr/K-T/0-9/;
12538: $txt=~tr/k-t/0-9/;
12539: $txt=~tr/U-Z/0-5/;
12540: $txt=~tr/u-z/0-5/;
12541: $txt=~s/\D//g;
12542: if ($_64bit) { if ($txt > 2**32) { return -1; } }
12543: return int($txt);
12544: }
12545:
12546: sub numval2 {
12547: my $txt=shift;
12548: $txt=~tr/A-J/0-9/;
12549: $txt=~tr/a-j/0-9/;
12550: $txt=~tr/K-T/0-9/;
12551: $txt=~tr/k-t/0-9/;
12552: $txt=~tr/U-Z/0-5/;
12553: $txt=~tr/u-z/0-5/;
12554: $txt=~s/\D//g;
12555: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12556: my $total;
12557: foreach my $val (@txts) { $total+=$val; }
12558: if ($_64bit) { if ($total > 2**32) { return -1; } }
12559: return int($total);
12560: }
12561:
12562: sub numval3 {
12563: use integer;
12564: my $txt=shift;
12565: $txt=~tr/A-J/0-9/;
12566: $txt=~tr/a-j/0-9/;
12567: $txt=~tr/K-T/0-9/;
12568: $txt=~tr/k-t/0-9/;
12569: $txt=~tr/U-Z/0-5/;
12570: $txt=~tr/u-z/0-5/;
12571: $txt=~s/\D//g;
12572: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
12573: my $total;
12574: foreach my $val (@txts) { $total+=$val; }
12575: if ($_64bit) { $total=(($total<<32)>>32); }
12576: return $total;
12577: }
12578:
12579: sub digest {
12580: my ($data)=@_;
12581: my $digest=&Digest::MD5::md5($data);
12582: my ($a,$b,$c,$d)=unpack("iiii",$digest);
12583: my ($e,$f);
12584: {
12585: use integer;
12586: $e=($a+$b);
12587: $f=($c+$d);
12588: if ($_64bit) {
12589: $e=(($e<<32)>>32);
12590: $f=(($f<<32)>>32);
12591: }
12592: }
12593: if (wantarray) {
12594: return ($e,$f);
12595: } else {
12596: my $g;
12597: {
12598: use integer;
12599: $g=($e+$f);
12600: if ($_64bit) {
12601: $g=(($g<<32)>>32);
12602: }
12603: }
12604: return $g;
12605: }
12606: }
12607:
12608: sub latest_rnd_algorithm_id {
12609: return '64bit5';
12610: }
12611:
12612: sub get_rand_alg {
12613: my ($courseid)=@_;
12614: if (!$courseid) { $courseid=(&whichuser())[1]; }
12615: if ($courseid) {
12616: return $env{"course.$courseid.rndseed"};
12617: }
12618: return &latest_rnd_algorithm_id();
12619: }
12620:
12621: sub validCODE {
12622: my ($CODE)=@_;
12623: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
12624: return 0;
12625: }
12626:
12627: sub getCODE {
12628: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
12629: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
12630: defined($Apache::lonhomework::parsing_a_task) ) &&
12631: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
12632: return $Apache::lonhomework::history{'resource.CODE'};
12633: }
12634: return undef;
12635: }
12636: #
12637: # Determines the random seed for a specific context:
12638: #
12639: # parameters:
12640: # symb - in course context the symb for the seed.
12641: # course_id - The course id of the form domain_coursenum.
12642: # domain - Domain for the user.
12643: # course - Course for the user.
12644: # cenv - environment of the course.
12645: #
12646: # NOTE:
12647: # All parameters are picked out of the environment if missing
12648: # or not defined.
12649: # If a symb cannot be determined the current time is used instead.
12650: #
12651: # For a given well defined symb, courside, domain, username,
12652: # and course environment, the seed is reproducible.
12653: #
12654: sub rndseed {
12655: my ($symb,$courseid,$domain,$username, $cenv)=@_;
12656: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
12657: if (!defined($symb)) {
12658: unless ($symb=$wsymb) { return time; }
12659: }
12660: if (!defined $courseid) {
12661: $courseid=$wcourseid;
12662: }
12663: if (!defined $domain) { $domain=$wdomain; }
12664: if (!defined $username) { $username=$wusername }
12665:
12666: my $which;
12667: if (defined($cenv->{'rndseed'})) {
12668: $which = $cenv->{'rndseed'};
12669: } else {
12670: $which =&get_rand_alg($courseid);
12671: }
12672: if (defined(&getCODE())) {
12673: if ($which eq '64bit5') {
12674: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
12675: } elsif ($which eq '64bit4') {
12676: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
12677: } else {
12678: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
12679: }
12680: } elsif ($which eq '64bit5') {
12681: return &rndseed_64bit5($symb,$courseid,$domain,$username);
12682: } elsif ($which eq '64bit4') {
12683: return &rndseed_64bit4($symb,$courseid,$domain,$username);
12684: } elsif ($which eq '64bit3') {
12685: return &rndseed_64bit3($symb,$courseid,$domain,$username);
12686: } elsif ($which eq '64bit2') {
12687: return &rndseed_64bit2($symb,$courseid,$domain,$username);
12688: } elsif ($which eq '64bit') {
12689: return &rndseed_64bit($symb,$courseid,$domain,$username);
12690: }
12691: return &rndseed_32bit($symb,$courseid,$domain,$username);
12692: }
12693:
12694: sub rndseed_32bit {
12695: my ($symb,$courseid,$domain,$username)=@_;
12696: {
12697: use integer;
12698: my $symbchck=unpack("%32C*",$symb) << 27;
12699: my $symbseed=numval($symb) << 22;
12700: my $namechck=unpack("%32C*",$username) << 17;
12701: my $nameseed=numval($username) << 12;
12702: my $domainseed=unpack("%32C*",$domain) << 7;
12703: my $courseseed=unpack("%32C*",$courseid);
12704: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
12705: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12706: #&logthis("rndseed :$num:$symb");
12707: if ($_64bit) { $num=(($num<<32)>>32); }
12708: return $num;
12709: }
12710: }
12711:
12712: sub rndseed_64bit {
12713: my ($symb,$courseid,$domain,$username)=@_;
12714: {
12715: use integer;
12716: my $symbchck=unpack("%32S*",$symb) << 21;
12717: my $symbseed=numval($symb) << 10;
12718: my $namechck=unpack("%32S*",$username);
12719:
12720: my $nameseed=numval($username) << 21;
12721: my $domainseed=unpack("%32S*",$domain) << 10;
12722: my $courseseed=unpack("%32S*",$courseid);
12723:
12724: my $num1=$symbchck+$symbseed+$namechck;
12725: my $num2=$nameseed+$domainseed+$courseseed;
12726: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12727: #&logthis("rndseed :$num:$symb");
12728: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12729: return "$num1,$num2";
12730: }
12731: }
12732:
12733: sub rndseed_64bit2 {
12734: my ($symb,$courseid,$domain,$username)=@_;
12735: {
12736: use integer;
12737: # strings need to be an even # of cahracters long, it it is odd the
12738: # last characters gets thrown away
12739: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12740: my $symbseed=numval($symb) << 10;
12741: my $namechck=unpack("%32S*",$username.' ');
12742:
12743: my $nameseed=numval($username) << 21;
12744: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12745: my $courseseed=unpack("%32S*",$courseid.' ');
12746:
12747: my $num1=$symbchck+$symbseed+$namechck;
12748: my $num2=$nameseed+$domainseed+$courseseed;
12749: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12750: #&logthis("rndseed :$num:$symb");
12751: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12752: return "$num1,$num2";
12753: }
12754: }
12755:
12756: sub rndseed_64bit3 {
12757: my ($symb,$courseid,$domain,$username)=@_;
12758: {
12759: use integer;
12760: # strings need to be an even # of cahracters long, it it is odd the
12761: # last characters gets thrown away
12762: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12763: my $symbseed=numval2($symb) << 10;
12764: my $namechck=unpack("%32S*",$username.' ');
12765:
12766: my $nameseed=numval2($username) << 21;
12767: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12768: my $courseseed=unpack("%32S*",$courseid.' ');
12769:
12770: my $num1=$symbchck+$symbseed+$namechck;
12771: my $num2=$nameseed+$domainseed+$courseseed;
12772: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12773: #&logthis("rndseed :$num1:$num2:$_64bit");
12774: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12775:
12776: return "$num1:$num2";
12777: }
12778: }
12779:
12780: sub rndseed_64bit4 {
12781: my ($symb,$courseid,$domain,$username)=@_;
12782: {
12783: use integer;
12784: # strings need to be an even # of cahracters long, it it is odd the
12785: # last characters gets thrown away
12786: my $symbchck=unpack("%32S*",$symb.' ') << 21;
12787: my $symbseed=numval3($symb) << 10;
12788: my $namechck=unpack("%32S*",$username.' ');
12789:
12790: my $nameseed=numval3($username) << 21;
12791: my $domainseed=unpack("%32S*",$domain.' ') << 10;
12792: my $courseseed=unpack("%32S*",$courseid.' ');
12793:
12794: my $num1=$symbchck+$symbseed+$namechck;
12795: my $num2=$nameseed+$domainseed+$courseseed;
12796: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
12797: #&logthis("rndseed :$num1:$num2:$_64bit");
12798: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
12799:
12800: return "$num1:$num2";
12801: }
12802: }
12803:
12804: sub rndseed_64bit5 {
12805: my ($symb,$courseid,$domain,$username)=@_;
12806: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
12807: return "$num1:$num2";
12808: }
12809:
12810: sub rndseed_CODE_64bit {
12811: my ($symb,$courseid,$domain,$username)=@_;
12812: {
12813: use integer;
12814: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12815: my $symbseed=numval2($symb);
12816: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12817: my $CODEseed=numval(&getCODE());
12818: my $courseseed=unpack("%32S*",$courseid.' ');
12819: my $num1=$symbseed+$CODEchck;
12820: my $num2=$CODEseed+$courseseed+$symbchck;
12821: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12822: #&logthis("rndseed :$num1:$num2:$symb");
12823: if ($_64bit) { $num1=(($num1<<32)>>32); }
12824: if ($_64bit) { $num2=(($num2<<32)>>32); }
12825: return "$num1:$num2";
12826: }
12827: }
12828:
12829: sub rndseed_CODE_64bit4 {
12830: my ($symb,$courseid,$domain,$username)=@_;
12831: {
12832: use integer;
12833: my $symbchck=unpack("%32S*",$symb.' ') << 16;
12834: my $symbseed=numval3($symb);
12835: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
12836: my $CODEseed=numval3(&getCODE());
12837: my $courseseed=unpack("%32S*",$courseid.' ');
12838: my $num1=$symbseed+$CODEchck;
12839: my $num2=$CODEseed+$courseseed+$symbchck;
12840: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
12841: #&logthis("rndseed :$num1:$num2:$symb");
12842: if ($_64bit) { $num1=(($num1<<32)>>32); }
12843: if ($_64bit) { $num2=(($num2<<32)>>32); }
12844: return "$num1:$num2";
12845: }
12846: }
12847:
12848: sub rndseed_CODE_64bit5 {
12849: my ($symb,$courseid,$domain,$username)=@_;
12850: my $code = &getCODE();
12851: my ($num1,$num2)=&digest("$symb,$courseid,$code");
12852: return "$num1:$num2";
12853: }
12854:
12855: sub setup_random_from_rndseed {
12856: my ($rndseed)=@_;
12857: if ($rndseed =~/([,:])/) {
12858: my ($num1,$num2) = map { abs($_); } (split(/[,:]/,$rndseed));
12859: if ((!$num1) || (!$num2) || ($num1 > 2147483562) || ($num2 > 2147483398)) {
12860: &Math::Random::random_set_seed_from_phrase($rndseed);
12861: } else {
12862: &Math::Random::random_set_seed($num1,$num2);
12863: }
12864: } else {
12865: &Math::Random::random_set_seed_from_phrase($rndseed);
12866: }
12867: }
12868:
12869: sub latest_receipt_algorithm_id {
12870: return 'receipt3';
12871: }
12872:
12873: sub recunique {
12874: my $fucourseid=shift;
12875: my $unique;
12876: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
12877: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12878: $unique=$env{"course.$fucourseid.internal.encseed"};
12879: } else {
12880: $unique=$perlvar{'lonReceipt'};
12881: }
12882: return unpack("%32C*",$unique);
12883: }
12884:
12885: sub recprefix {
12886: my $fucourseid=shift;
12887: my $prefix;
12888: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
12889: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
12890: $prefix=$env{"course.$fucourseid.internal.encpref"};
12891: } else {
12892: $prefix=$perlvar{'lonHostID'};
12893: }
12894: return unpack("%32C*",$prefix);
12895: }
12896:
12897: sub ireceipt {
12898: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
12899:
12900: my $return =&recprefix($fucourseid).'-';
12901:
12902: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
12903: $env{'request.state'} eq 'construct') {
12904: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
12905: return $return;
12906: }
12907:
12908: my $cuname=unpack("%32C*",$funame);
12909: my $cudom=unpack("%32C*",$fudom);
12910: my $cucourseid=unpack("%32C*",$fucourseid);
12911: my $cusymb=unpack("%32C*",$fusymb);
12912: my $cunique=&recunique($fucourseid);
12913: my $cpart=unpack("%32S*",$part);
12914: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
12915:
12916: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
12917:
12918: $return.= ($cunique%$cuname+
12919: $cunique%$cudom+
12920: $cusymb%$cuname+
12921: $cusymb%$cudom+
12922: $cucourseid%$cuname+
12923: $cucourseid%$cudom+
12924: $cpart%$cuname+
12925: $cpart%$cudom);
12926: } else {
12927: $return.= ($cunique%$cuname+
12928: $cunique%$cudom+
12929: $cusymb%$cuname+
12930: $cusymb%$cudom+
12931: $cucourseid%$cuname+
12932: $cucourseid%$cudom);
12933: }
12934: return $return;
12935: }
12936:
12937: sub receipt {
12938: my ($part)=@_;
12939: my ($symb,$courseid,$domain,$name) = &whichuser();
12940: return &ireceipt($name,$domain,$courseid,$symb,$part);
12941: }
12942:
12943: sub whichuser {
12944: my ($passedsymb)=@_;
12945: my ($symb,$courseid,$domain,$name,$publicuser);
12946: if (defined($env{'form.grade_symb'})) {
12947: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
12948: my $allowed=&allowed('vgr',$tmp_courseid);
12949: if (!$allowed &&
12950: exists($env{'request.course.sec'}) &&
12951: $env{'request.course.sec'} !~ /^\s*$/) {
12952: $allowed=&allowed('vgr',$tmp_courseid.
12953: '/'.$env{'request.course.sec'});
12954: }
12955: if ($allowed) {
12956: ($symb)=&get_env_multiple('form.grade_symb');
12957: $courseid=$tmp_courseid;
12958: ($domain)=&get_env_multiple('form.grade_domain');
12959: ($name)=&get_env_multiple('form.grade_username');
12960: return ($symb,$courseid,$domain,$name,$publicuser);
12961: }
12962: }
12963: if (!$passedsymb) {
12964: $symb=&symbread();
12965: } else {
12966: $symb=$passedsymb;
12967: }
12968: $courseid=$env{'request.course.id'};
12969: $domain=$env{'user.domain'};
12970: $name=$env{'user.name'};
12971: if ($name eq 'public' && $domain eq 'public') {
12972: if (!defined($env{'form.username'})) {
12973: $env{'form.username'}.=time.rand(10000000);
12974: }
12975: $name.=$env{'form.username'};
12976: }
12977: return ($symb,$courseid,$domain,$name,$publicuser);
12978:
12979: }
12980:
12981: # ------------------------------------------------------------ Serves up a file
12982: # returns either the contents of the file or
12983: # -1 if the file doesn't exist
12984: #
12985: # if the target is a file that was uploaded via DOCS,
12986: # a check will be made to see if a current copy exists on the local server,
12987: # if it does this will be served, otherwise a copy will be retrieved from
12988: # the home server for the course and stored in /home/httpd/html/userfiles on
12989: # the local server.
12990:
12991: sub getfile {
12992: my ($file) = @_;
12993: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
12994: &repcopy($file);
12995: return &readfile($file);
12996: }
12997:
12998: sub repcopy_userfile {
12999: my ($file)=@_;
13000: my $londocroot = $perlvar{'lonDocRoot'};
13001: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
13002: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
13003: my ($cdom,$cnum,$filename) =
13004: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
13005: my $uri="/uploaded/$cdom/$cnum/$filename";
13006: if (-e "$file") {
13007: # we already have a local copy, check it out
13008: my @fileinfo = stat($file);
13009: my $rtncode;
13010: my $info;
13011: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
13012: if ($lwpresp ne 'ok') {
13013: # there is no such file anymore, even though we had a local copy
13014: if ($rtncode eq '404') {
13015: unlink($file);
13016: }
13017: return -1;
13018: }
13019: if ($info < $fileinfo[9]) {
13020: # nice, the file we have is up-to-date, just say okay
13021: return 'ok';
13022: } else {
13023: # the file is outdated, get rid of it
13024: unlink($file);
13025: }
13026: }
13027: # one way or the other, at this point, we don't have the file
13028: # construct the correct path for the file
13029: my @parts = ($cdom,$cnum);
13030: if ($filename =~ m|^(.+)/[^/]+$|) {
13031: push @parts, split(/\//,$1);
13032: }
13033: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
13034: foreach my $part (@parts) {
13035: $path .= '/'.$part;
13036: if (!-e $path) {
13037: mkdir($path,0770);
13038: }
13039: }
13040: # now the path exists for sure
13041: # get a user agent
13042: my $ua=new LWP::UserAgent;
13043: my $transferfile=$file.'.in.transfer';
13044: # FIXME: this should flock
13045: if (-e $transferfile) { return 'ok'; }
13046: my $request;
13047: $uri=~s/^\///;
13048: my $homeserver = &homeserver($cnum,$cdom);
13049: my $hostname = &hostname($homeserver);
13050: my $protocol = $protocol{$homeserver};
13051: $protocol = 'http' if ($protocol ne 'https');
13052: $request=new HTTP::Request('GET',$protocol.'://'.$hostname.'/raw/'.$uri);
13053: my $response=$ua->request($request,$transferfile);
13054: # did it work?
13055: if ($response->is_error()) {
13056: unlink($transferfile);
13057: &logthis("Userfile repcopy failed for $uri");
13058: return -1;
13059: }
13060: # worked, rename the transfer file
13061: rename($transferfile,$file);
13062: return 'ok';
13063: }
13064:
13065: sub tokenwrapper {
13066: my $uri=shift;
13067: $uri=~s|^https?\://([^/]+)||;
13068: $uri=~s|^/||;
13069: $env{'user.environment'}=~/\/([^\/]+)\.id/;
13070: my $token=$1;
13071: my (undef,$udom,$uname,$file)=split('/',$uri,4);
13072: if ($udom && $uname && $file) {
13073: $file=~s|(\?\.*)*$||;
13074: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
13075: my $homeserver = &homeserver($uname,$udom);
13076: my $hostname = &hostname($homeserver);
13077: my $protocol = $protocol{$homeserver};
13078: $protocol = 'http' if ($protocol ne 'https');
13079: return $protocol.'://'.$hostname.'/'.$uri.
13080: (($uri=~/\?/)?'&':'?').'token='.$token.
13081: '&tokenissued='.$perlvar{'lonHostID'};
13082: } else {
13083: return '/adm/notfound.html';
13084: }
13085: }
13086:
13087: # call with reqtype HEAD: get last modification time
13088: # call with reqtype GET: get the file contents
13089: # Do not call this with reqtype GET for large files! It loads everything into memory
13090: #
13091: sub getuploaded {
13092: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
13093: $uri=~s/^\///;
13094: my $homeserver = &homeserver($cnum,$cdom);
13095: my $hostname = &hostname($homeserver);
13096: my $protocol = $protocol{$homeserver};
13097: $protocol = 'http' if ($protocol ne 'https');
13098: $uri = $protocol.'://'.$hostname.'/raw/'.$uri;
13099: my $ua=new LWP::UserAgent;
13100: my $request=new HTTP::Request($reqtype,$uri);
13101: my $response=$ua->request($request);
13102: $$rtncode = $response->code;
13103: if (! $response->is_success()) {
13104: return 'failed';
13105: }
13106: if ($reqtype eq 'HEAD') {
13107: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
13108: } elsif ($reqtype eq 'GET') {
13109: $$info = $response->content;
13110: }
13111: return 'ok';
13112: }
13113:
13114: sub readfile {
13115: my $file = shift;
13116: if ( (! -e $file ) || ($file eq '') ) { return -1; };
13117: my $fh;
13118: open($fh,"<",$file);
13119: my $a='';
13120: while (my $line = <$fh>) { $a .= $line; }
13121: return $a;
13122: }
13123:
13124: sub filelocation {
13125: my ($dir,$file) = @_;
13126: my $location;
13127: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
13128:
13129: if ($file =~ m-^/adm/-) {
13130: $file=~s-^/adm/wrapper/-/-;
13131: $file=~s-^/adm/coursedocs/showdoc/-/-;
13132: }
13133:
13134: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
13135: $location = $file;
13136: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
13137: my ($udom,$uname,$filename)=
13138: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
13139: my $home=&homeserver($uname,$udom);
13140: my $is_me=0;
13141: my @ids=¤t_machine_ids();
13142: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
13143: if ($is_me) {
13144: $location=propath($udom,$uname).'/userfiles/'.$filename;
13145: } else {
13146: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
13147: $udom.'/'.$uname.'/'.$filename;
13148: }
13149: } elsif ($file =~ m-^/adm/-) {
13150: $location = $perlvar{'lonDocRoot'}.'/'.$file;
13151: } else {
13152: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
13153: $file=~s:^/(res|priv)/:/:;
13154: my $space=$1;
13155: if ( !( $file =~ m:^/:) ) {
13156: $location = $dir. '/'.$file;
13157: } else {
13158: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
13159: }
13160: }
13161: $location=~s://+:/:g; # remove duplicate /
13162: while ($location=~m{/\.\./}) {
13163: if ($location =~ m{/[^/]+/\.\./}) {
13164: $location=~ s{/[^/]+/\.\./}{/}g;
13165: } else {
13166: $location=~ s{/\.\./}{/}g;
13167: }
13168: } #remove dir/..
13169: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
13170: return $location;
13171: }
13172:
13173: sub hreflocation {
13174: my ($dir,$file)=@_;
13175: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
13176: $file=filelocation($dir,$file);
13177: } elsif ($file=~m-^/adm/-) {
13178: $file=~s-^/adm/wrapper/-/-;
13179: $file=~s-^/adm/coursedocs/showdoc/-/-;
13180: }
13181: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
13182: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
13183: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
13184: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
13185: {/uploaded/$1/$2/}x;
13186: }
13187: if ($file=~ m{^/userfiles/}) {
13188: $file =~ s{^/userfiles/}{/uploaded/};
13189: }
13190: return $file;
13191: }
13192:
13193:
13194:
13195:
13196:
13197: sub current_machine_domains {
13198: return &machine_domains(&hostname($perlvar{'lonHostID'}));
13199: }
13200:
13201: sub machine_domains {
13202: my ($hostname) = @_;
13203: my @domains;
13204: my %hostname = &all_hostnames();
13205: while( my($id, $name) = each(%hostname)) {
13206: # &logthis("-$id-$name-$hostname-");
13207: if ($hostname eq $name) {
13208: push(@domains,&host_domain($id));
13209: }
13210: }
13211: return @domains;
13212: }
13213:
13214: sub current_machine_ids {
13215: return &machine_ids(&hostname($perlvar{'lonHostID'}));
13216: }
13217:
13218: sub machine_ids {
13219: my ($hostname) = @_;
13220: $hostname ||= &hostname($perlvar{'lonHostID'});
13221: my @ids;
13222: my %name_to_host = &all_names();
13223: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
13224: return @{ $name_to_host{$hostname} };
13225: }
13226: return;
13227: }
13228:
13229: sub additional_machine_domains {
13230: my @domains;
13231: open(my $fh,"<","$perlvar{'lonTabDir'}/expected_domains.tab");
13232: while( my $line = <$fh>) {
13233: $line =~ s/\s//g;
13234: push(@domains,$line);
13235: }
13236: return @domains;
13237: }
13238:
13239: sub default_login_domain {
13240: my $domain = $perlvar{'lonDefDomain'};
13241: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
13242: foreach my $posdom (¤t_machine_domains(),
13243: &additional_machine_domains()) {
13244: if (lc($posdom) eq lc($testdomain)) {
13245: $domain=$posdom;
13246: last;
13247: }
13248: }
13249: return $domain;
13250: }
13251:
13252: sub shared_institution {
13253: my ($dom) = @_;
13254: my $same_intdom;
13255: my $hostintdom = &internet_dom($perlvar{'lonHostID'});
13256: if ($hostintdom ne '') {
13257: my %iphost = &get_iphost();
13258: my $primary_id = &domain($dom,'primary');
13259: my $primary_ip = &get_host_ip($primary_id);
13260: if (ref($iphost{$primary_ip}) eq 'ARRAY') {
13261: foreach my $id (@{$iphost{$primary_ip}}) {
13262: my $intdom = &internet_dom($id);
13263: if ($intdom eq $hostintdom) {
13264: $same_intdom = 1;
13265: last;
13266: }
13267: }
13268: }
13269: }
13270: return $same_intdom;
13271: }
13272:
13273: sub uses_sts {
13274: my ($ignore_cache) = @_;
13275: my $lonhost = $perlvar{'lonHostID'};
13276: my $hostname = &hostname($lonhost);
13277: my $sts_on;
13278: if ($protocol{$lonhost} eq 'https') {
13279: my $cachetime = 12*3600;
13280: if (!$ignore_cache) {
13281: ($sts_on,my $cached)=&is_cached_new('stspolicy',$lonhost);
13282: if (defined($cached)) {
13283: return $sts_on;
13284: }
13285: }
13286: my $ua=new LWP::UserAgent;
13287: my $url = $protocol{$lonhost}.'://'.$hostname.'/index.html';
13288: my $request=new HTTP::Request('HEAD',$url);
13289: my $response=$ua->request($request);
13290: if ($response->is_success) {
13291: my $has_sts = $response->header('Strict-Transport-Security');
13292: if ($has_sts eq '') {
13293: $sts_on = 0;
13294: } else {
13295: if ($has_sts =~ /\Qmax-age=\E(\d+)/) {
13296: my $maxage = $1;
13297: if ($maxage) {
13298: $sts_on = 1;
13299: } else {
13300: $sts_on = 0;
13301: }
13302: } else {
13303: $sts_on = 0;
13304: }
13305: }
13306: return &do_cache_new('stspolicy',$lonhost,$sts_on,$cachetime);
13307: }
13308: }
13309: return;
13310: }
13311:
13312: # ------------------------------------------------------------- Declutters URLs
13313:
13314: sub declutter {
13315: my $thisfn=shift;
13316: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
13317: unless ($thisfn=~m{^/home/httpd/html/priv/}) {
13318: $thisfn=~s{^/home/httpd/html}{};
13319: }
13320: $thisfn=~s/^\///;
13321: $thisfn=~s|^adm/wrapper/||;
13322: $thisfn=~s|^adm/coursedocs/showdoc/||;
13323: $thisfn=~s/^res\///;
13324: $thisfn=~s/^priv\///;
13325: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
13326: $thisfn=~s/\?.+$//;
13327: }
13328: return $thisfn;
13329: }
13330:
13331: # ------------------------------------------------------------- Clutter up URLs
13332:
13333: sub clutter {
13334: my $thisfn='/'.&declutter(shift);
13335: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
13336: || $thisfn =~ m{^/adm/(includes|pages)} ) {
13337: $thisfn='/res'.$thisfn;
13338: }
13339: if ($thisfn !~m|^/adm|) {
13340: if ($thisfn =~ m|^/ext/|) {
13341: $thisfn='/adm/wrapper'.$thisfn;
13342: } else {
13343: my ($ext) = ($thisfn =~ /\.(\w+)$/);
13344: my $embstyle=&Apache::loncommon::fileembstyle($ext);
13345: if ($embstyle eq 'ssi'
13346: || ($embstyle eq 'hdn')
13347: || ($embstyle eq 'rat')
13348: || ($embstyle eq 'prv')
13349: || ($embstyle eq 'ign')) {
13350: #do nothing with these
13351: } elsif (($embstyle eq 'img')
13352: || ($embstyle eq 'emb')
13353: || ($embstyle eq 'wrp')) {
13354: $thisfn='/adm/wrapper'.$thisfn;
13355: } elsif ($embstyle eq 'unk'
13356: && $thisfn!~/\.(sequence|page)$/) {
13357: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
13358: } else {
13359: # &logthis("Got a blank emb style");
13360: }
13361: }
13362: }
13363: return $thisfn;
13364: }
13365:
13366: sub clutter_with_no_wrapper {
13367: my $uri = &clutter(shift);
13368: if ($uri =~ m-^/adm/-) {
13369: $uri =~ s-^/adm/wrapper/-/-;
13370: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
13371: }
13372: return $uri;
13373: }
13374:
13375: sub freeze_escape {
13376: my ($value)=@_;
13377: if (ref($value)) {
13378: $value=&nfreeze($value);
13379: return '__FROZEN__'.&escape($value);
13380: }
13381: return &escape($value);
13382: }
13383:
13384:
13385: sub thaw_unescape {
13386: my ($value)=@_;
13387: if ($value =~ /^__FROZEN__/) {
13388: substr($value,0,10,undef);
13389: $value=&unescape($value);
13390: return &thaw($value);
13391: }
13392: return &unescape($value);
13393: }
13394:
13395: sub correct_line_ends {
13396: my ($result)=@_;
13397: $$result =~s/\r\n/\n/mg;
13398: $$result =~s/\r/\n/mg;
13399: }
13400: # ================================================================ Main Program
13401:
13402: sub goodbye {
13403: &logthis("Starting Shut down");
13404: #not converted to using infrastruture and probably shouldn't be
13405: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
13406: #converted
13407: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
13408: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
13409: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
13410: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
13411: #1.1 only
13412: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
13413: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
13414: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
13415: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
13416: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
13417: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
13418: &logthis(sprintf("%-20s is %s",'hits',$hits));
13419: &flushcourselogs();
13420: &logthis("Shutting down");
13421: }
13422:
13423: sub get_dns {
13424: my ($url,$func,$ignore_cache,$nocache,$hashref) = @_;
13425: if (!$ignore_cache) {
13426: my ($content,$cached)=
13427: &Apache::lonnet::is_cached_new('dns',$url);
13428: if ($cached) {
13429: &$func($content,$hashref);
13430: return;
13431: }
13432: }
13433:
13434: my %alldns;
13435: if (open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab")) {
13436: foreach my $dns (<$config>) {
13437: next if ($dns !~ /^\^(\S*)/x);
13438: my $line = $1;
13439: my ($host,$protocol) = split(/:/,$line);
13440: if ($protocol ne 'https') {
13441: $protocol = 'http';
13442: }
13443: $alldns{$host} = $protocol;
13444: }
13445: close($config);
13446: }
13447: while (%alldns) {
13448: my ($dns) = sort { $b cmp $a } keys(%alldns);
13449: my $ua=new LWP::UserAgent;
13450: $ua->timeout(30);
13451: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
13452: my $response=$ua->request($request);
13453: delete($alldns{$dns});
13454: next if ($response->is_error());
13455: my @content = split("\n",$response->content);
13456: unless ($nocache) {
13457: &do_cache_new('dns',$url,\@content,30*24*60*60);
13458: }
13459: &$func(\@content,$hashref);
13460: return;
13461: }
13462: my $which = (split('/',$url))[3];
13463: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
13464: if (open(my $config,"<","$perlvar{'lonTabDir'}/dns_$which.tab")) {
13465: my @content = <$config>;
13466: &$func(\@content,$hashref);
13467: }
13468: return;
13469: }
13470:
13471: # ------------------------------------------------------Get DNS checksums file
13472: sub parse_dns_checksums_tab {
13473: my ($lines,$hashref) = @_;
13474: my $lonhost = $perlvar{'lonHostID'};
13475: my $machine_dom = &Apache::lonnet::host_domain($lonhost);
13476: my $loncaparev = &get_server_loncaparev($machine_dom);
13477: my $distro = (split(/\:/,&get_server_distarch($lonhost)))[0];
13478: my $webconfdir = '/etc/httpd/conf';
13479: if ($distro =~ /^(ubuntu|debian)(\d+)$/) {
13480: $webconfdir = '/etc/apache2';
13481: } elsif ($distro =~ /^sles(\d+)$/) {
13482: if ($1 >= 10) {
13483: $webconfdir = '/etc/apache2';
13484: }
13485: } elsif ($distro =~ /^suse(\d+\.\d+)$/) {
13486: if ($1 >= 10.0) {
13487: $webconfdir = '/etc/apache2';
13488: }
13489: }
13490: my ($release,$timestamp) = split(/\-/,$loncaparev);
13491: my (%chksum,%revnum);
13492: if (ref($lines) eq 'ARRAY') {
13493: chomp(@{$lines});
13494: my $version = shift(@{$lines});
13495: if ($version eq $release) {
13496: foreach my $line (@{$lines}) {
13497: my ($file,$version,$shasum) = split(/,/,$line);
13498: if ($file =~ m{^/etc/httpd/conf}) {
13499: if ($webconfdir eq '/etc/apache2') {
13500: $file =~ s{^\Q/etc/httpd/conf/\E}{$webconfdir/};
13501: }
13502: }
13503: $chksum{$file} = $shasum;
13504: $revnum{$file} = $version;
13505: }
13506: if (ref($hashref) eq 'HASH') {
13507: %{$hashref} = (
13508: sums => \%chksum,
13509: versions => \%revnum,
13510: );
13511: }
13512: }
13513: }
13514: return;
13515: }
13516:
13517: sub fetch_dns_checksums {
13518: my %checksums;
13519: my $machine_dom = &Apache::lonnet::host_domain($perlvar{'lonHostID'});
13520: my $loncaparev = &get_server_loncaparev($machine_dom,$perlvar{'lonHostID'});
13521: my ($release,$timestamp) = split(/\-/,$loncaparev);
13522: &get_dns("/adm/dns/checksums/$release",\&parse_dns_checksums_tab,1,1,
13523: \%checksums);
13524: return \%checksums;
13525: }
13526:
13527: # ------------------------------------------------------------ Read domain file
13528: {
13529: my $loaded;
13530: my %domain;
13531:
13532: sub parse_domain_tab {
13533: my ($lines) = @_;
13534: foreach my $line (@$lines) {
13535: next if ($line =~ /^(\#|\s*$ )/x);
13536:
13537: chomp($line);
13538: my ($name,@elements) = split(/:/,$line,9);
13539: my %this_domain;
13540: foreach my $field ('description', 'auth_def', 'auth_arg_def',
13541: 'lang_def', 'city', 'longi', 'lati',
13542: 'primary') {
13543: $this_domain{$field} = shift(@elements);
13544: }
13545: $domain{$name} = \%this_domain;
13546: }
13547: }
13548:
13549: sub reset_domain_info {
13550: undef($loaded);
13551: undef(%domain);
13552: }
13553:
13554: sub load_domain_tab {
13555: my ($ignore_cache,$nocache) = @_;
13556: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache,$nocache);
13557: my $fh;
13558: if (open($fh,"<",$perlvar{'lonTabDir'}.'/domain.tab')) {
13559: my @lines = <$fh>;
13560: &parse_domain_tab(\@lines);
13561: }
13562: close($fh);
13563: $loaded = 1;
13564: }
13565:
13566: sub domain {
13567: &load_domain_tab() if (!$loaded);
13568:
13569: my ($name,$what) = @_;
13570: return if ( !exists($domain{$name}) );
13571:
13572: if (!$what) {
13573: return $domain{$name}{'description'};
13574: }
13575: return $domain{$name}{$what};
13576: }
13577:
13578: sub domain_info {
13579: &load_domain_tab() if (!$loaded);
13580: return %domain;
13581: }
13582:
13583: }
13584:
13585:
13586: # ------------------------------------------------------------- Read hosts file
13587: {
13588: my %hostname;
13589: my %hostdom;
13590: my %libserv;
13591: my $loaded;
13592: my %name_to_host;
13593: my %internetdom;
13594: my %LC_dns_serv;
13595:
13596: sub parse_hosts_tab {
13597: my ($file) = @_;
13598: foreach my $configline (@$file) {
13599: next if ($configline =~ /^(\#|\s*$ )/x);
13600: chomp($configline);
13601: if ($configline =~ /^\^/) {
13602: if ($configline =~ /^\^([\w.\-]+)/) {
13603: $LC_dns_serv{$1} = 1;
13604: }
13605: next;
13606: }
13607: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
13608: $name=~s/\s//g;
13609: if ($id && $domain && $role && $name) {
13610: if ((exists($hostname{$id})) && ($hostname{$id} ne '')) {
13611: my $curr = $hostname{$id};
13612: my $skip;
13613: if (ref($name_to_host{$curr}) eq 'ARRAY') {
13614: if (($curr eq $name) && (@{$name_to_host{$curr}} == 1)) {
13615: $skip = 1;
13616: } else {
13617: @{$name_to_host{$curr}} = grep { $_ ne $id } @{$name_to_host{$curr}};
13618: }
13619: }
13620: unless ($skip) {
13621: push(@{$name_to_host{$name}},$id);
13622: }
13623: } else {
13624: push(@{$name_to_host{$name}},$id);
13625: }
13626: $hostname{$id}=$name;
13627: $hostdom{$id}=$domain;
13628: if ($role eq 'library') { $libserv{$id}=$name; }
13629: if (defined($protocol)) {
13630: if ($protocol eq 'https') {
13631: $protocol{$id} = $protocol;
13632: } else {
13633: $protocol{$id} = 'http';
13634: }
13635: } else {
13636: $protocol{$id} = 'http';
13637: }
13638: if (defined($intdom)) {
13639: $internetdom{$id} = $intdom;
13640: }
13641: }
13642: }
13643: }
13644:
13645: sub reset_hosts_info {
13646: &purge_remembered();
13647: &reset_domain_info();
13648: &reset_hosts_ip_info();
13649: undef(%name_to_host);
13650: undef(%hostname);
13651: undef(%hostdom);
13652: undef(%libserv);
13653: undef($loaded);
13654: }
13655:
13656: sub load_hosts_tab {
13657: my ($ignore_cache,$nocache) = @_;
13658: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache,$nocache);
13659: open(my $config,"<","$perlvar{'lonTabDir'}/hosts.tab");
13660: my @config = <$config>;
13661: &parse_hosts_tab(\@config);
13662: close($config);
13663: $loaded=1;
13664: }
13665:
13666: sub hostname {
13667: &load_hosts_tab() if (!$loaded);
13668:
13669: my ($lonid) = @_;
13670: return $hostname{$lonid};
13671: }
13672:
13673: sub all_hostnames {
13674: &load_hosts_tab() if (!$loaded);
13675:
13676: return %hostname;
13677: }
13678:
13679: sub all_names {
13680: my ($ignore_cache,$nocache) = @_;
13681: &load_hosts_tab($ignore_cache,$nocache) if (!$loaded);
13682:
13683: return %name_to_host;
13684: }
13685:
13686: sub all_host_domain {
13687: &load_hosts_tab() if (!$loaded);
13688: return %hostdom;
13689: }
13690:
13691: sub is_library {
13692: &load_hosts_tab() if (!$loaded);
13693:
13694: return exists($libserv{$_[0]});
13695: }
13696:
13697: sub all_library {
13698: &load_hosts_tab() if (!$loaded);
13699:
13700: return %libserv;
13701: }
13702:
13703: sub unique_library {
13704: #2x reverse removes all hostnames that appear more than once
13705: my %unique = reverse &all_library();
13706: return reverse %unique;
13707: }
13708:
13709: sub get_servers {
13710: &load_hosts_tab() if (!$loaded);
13711:
13712: my ($domain,$type) = @_;
13713: my %possible_hosts = ($type eq 'library') ? %libserv
13714: : %hostname;
13715: my %result;
13716: if (ref($domain) eq 'ARRAY') {
13717: while ( my ($host,$hostname) = each(%possible_hosts)) {
13718: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
13719: $result{$host} = $hostname;
13720: }
13721: }
13722: } else {
13723: while ( my ($host,$hostname) = each(%possible_hosts)) {
13724: if ($hostdom{$host} eq $domain) {
13725: $result{$host} = $hostname;
13726: }
13727: }
13728: }
13729: return %result;
13730: }
13731:
13732: sub get_unique_servers {
13733: my %unique = reverse &get_servers(@_);
13734: return reverse %unique;
13735: }
13736:
13737: sub host_domain {
13738: &load_hosts_tab() if (!$loaded);
13739:
13740: my ($lonid) = @_;
13741: return $hostdom{$lonid};
13742: }
13743:
13744: sub all_domains {
13745: &load_hosts_tab() if (!$loaded);
13746:
13747: my %seen;
13748: my @uniq = grep(!$seen{$_}++, values(%hostdom));
13749: return @uniq;
13750: }
13751:
13752: sub internet_dom {
13753: &load_hosts_tab() if (!$loaded);
13754:
13755: my ($lonid) = @_;
13756: return $internetdom{$lonid};
13757: }
13758:
13759: sub is_LC_dns {
13760: &load_hosts_tab() if (!$loaded);
13761:
13762: my ($hostname) = @_;
13763: return exists($LC_dns_serv{$hostname});
13764: }
13765:
13766: }
13767:
13768: {
13769: my %iphost;
13770: my %name_to_ip;
13771: my %lonid_to_ip;
13772:
13773: sub get_hosts_from_ip {
13774: my ($ip) = @_;
13775: my %iphosts = &get_iphost();
13776: if (ref($iphosts{$ip})) {
13777: return @{$iphosts{$ip}};
13778: }
13779: return;
13780: }
13781:
13782: sub reset_hosts_ip_info {
13783: undef(%iphost);
13784: undef(%name_to_ip);
13785: undef(%lonid_to_ip);
13786: }
13787:
13788: sub get_host_ip {
13789: my ($lonid) = @_;
13790: if (exists($lonid_to_ip{$lonid})) {
13791: return $lonid_to_ip{$lonid};
13792: }
13793: my $name=&hostname($lonid);
13794: my $ip = gethostbyname($name);
13795: return if (!$ip || length($ip) ne 4);
13796: $ip=inet_ntoa($ip);
13797: $name_to_ip{$name} = $ip;
13798: $lonid_to_ip{$lonid} = $ip;
13799: return $ip;
13800: }
13801:
13802: sub get_iphost {
13803: my ($ignore_cache,$nocache) = @_;
13804:
13805: if (!$ignore_cache) {
13806: if (%iphost) {
13807: return %iphost;
13808: }
13809: my ($ip_info,$cached)=
13810: &Apache::lonnet::is_cached_new('iphost','iphost');
13811: if ($cached) {
13812: %iphost = %{$ip_info->[0]};
13813: %name_to_ip = %{$ip_info->[1]};
13814: %lonid_to_ip = %{$ip_info->[2]};
13815: return %iphost;
13816: }
13817: }
13818:
13819: # get yesterday's info for fallback
13820: my %old_name_to_ip;
13821: my ($ip_info,$cached)=
13822: &Apache::lonnet::is_cached_new('iphost','iphost');
13823: if ($cached) {
13824: %old_name_to_ip = %{$ip_info->[1]};
13825: }
13826:
13827: my %name_to_host = &all_names($ignore_cache,$nocache);
13828: foreach my $name (keys(%name_to_host)) {
13829: my $ip;
13830: if (!exists($name_to_ip{$name})) {
13831: $ip = gethostbyname($name);
13832: if (!$ip || length($ip) ne 4) {
13833: if (defined($old_name_to_ip{$name})) {
13834: $ip = $old_name_to_ip{$name};
13835: &logthis("Can't find $name defaulting to old $ip");
13836: } else {
13837: &logthis("Name $name no IP found");
13838: next;
13839: }
13840: } else {
13841: $ip=inet_ntoa($ip);
13842: }
13843: $name_to_ip{$name} = $ip;
13844: } else {
13845: $ip = $name_to_ip{$name};
13846: }
13847: foreach my $id (@{ $name_to_host{$name} }) {
13848: $lonid_to_ip{$id} = $ip;
13849: }
13850: push(@{$iphost{$ip}},@{$name_to_host{$name}});
13851: }
13852: unless ($nocache) {
13853: &do_cache_new('iphost','iphost',
13854: [\%iphost,\%name_to_ip,\%lonid_to_ip],
13855: 48*60*60);
13856: }
13857:
13858: return %iphost;
13859: }
13860:
13861: #
13862: # Given a DNS returns the loncapa host name for that DNS
13863: #
13864: sub host_from_dns {
13865: my ($dns) = @_;
13866: my @hosts;
13867: my $ip;
13868:
13869: if (exists($name_to_ip{$dns})) {
13870: $ip = $name_to_ip{$dns};
13871: }
13872: if (!$ip) {
13873: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
13874: if (length($ip) == 4) {
13875: $ip = &IO::Socket::inet_ntoa($ip);
13876: }
13877: }
13878: if ($ip) {
13879: @hosts = get_hosts_from_ip($ip);
13880: return $hosts[0];
13881: }
13882: return undef;
13883: }
13884:
13885: sub get_internet_names {
13886: my ($lonid) = @_;
13887: return if ($lonid eq '');
13888: my ($idnref,$cached)=
13889: &Apache::lonnet::is_cached_new('internetnames',$lonid);
13890: if ($cached) {
13891: return $idnref;
13892: }
13893: my $ip = &get_host_ip($lonid);
13894: my @hosts = &get_hosts_from_ip($ip);
13895: my %iphost = &get_iphost();
13896: my (@idns,%seen);
13897: foreach my $id (@hosts) {
13898: my $dom = &host_domain($id);
13899: my $prim_id = &domain($dom,'primary');
13900: my $prim_ip = &get_host_ip($prim_id);
13901: next if ($seen{$prim_ip});
13902: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
13903: foreach my $id (@{$iphost{$prim_ip}}) {
13904: my $intdom = &internet_dom($id);
13905: unless (grep(/^\Q$intdom\E$/,@idns)) {
13906: push(@idns,$intdom);
13907: }
13908: }
13909: }
13910: $seen{$prim_ip} = 1;
13911: }
13912: return &do_cache_new('internetnames',$lonid,\@idns,12*60*60);
13913: }
13914:
13915: }
13916:
13917: sub all_loncaparevs {
13918: 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);
13919: }
13920:
13921: # ------------------------------------------------------- Read loncaparev table
13922: {
13923: sub load_loncaparevs {
13924: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
13925: if (open(my $config,"<","$perlvar{'lonTabDir'}/loncaparevs.tab")) {
13926: while (my $configline=<$config>) {
13927: chomp($configline);
13928: my ($hostid,$loncaparev)=split(/:/,$configline);
13929: $loncaparevs{$hostid}=$loncaparev;
13930: }
13931: close($config);
13932: }
13933: }
13934: }
13935: }
13936:
13937: # ----------------------------------------------------- Read serverhostID table
13938: {
13939: sub load_serverhomeIDs {
13940: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
13941: if (open(my $config,"<","$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
13942: while (my $configline=<$config>) {
13943: chomp($configline);
13944: my ($name,$id)=split(/:/,$configline);
13945: $serverhomeIDs{$name}=$id;
13946: }
13947: close($config);
13948: }
13949: }
13950: }
13951: }
13952:
13953:
13954: BEGIN {
13955:
13956: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
13957: unless ($readit) {
13958: {
13959: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
13960: %perlvar = (%perlvar,%{$configvars});
13961: }
13962:
13963:
13964: # ------------------------------------------------------ Read spare server file
13965: {
13966: open(my $config,"<","$perlvar{'lonTabDir'}/spare.tab");
13967:
13968: while (my $configline=<$config>) {
13969: chomp($configline);
13970: if ($configline) {
13971: my ($host,$type) = split(':',$configline,2);
13972: if (!defined($type) || $type eq '') { $type = 'default' };
13973: push(@{ $spareid{$type} }, $host);
13974: }
13975: }
13976: close($config);
13977: }
13978: # ------------------------------------------------------------ Read permissions
13979: {
13980: open(my $config,"<","$perlvar{'lonTabDir'}/roles.tab");
13981:
13982: while (my $configline=<$config>) {
13983: chomp($configline);
13984: if ($configline) {
13985: my ($role,$perm)=split(/ /,$configline);
13986: if ($perm ne '') { $pr{$role}=$perm; }
13987: }
13988: }
13989: close($config);
13990: }
13991:
13992: # -------------------------------------------- Read plain texts for permissions
13993: {
13994: open(my $config,"<","$perlvar{'lonTabDir'}/rolesplain.tab");
13995:
13996: while (my $configline=<$config>) {
13997: chomp($configline);
13998: if ($configline) {
13999: my ($short,@plain)=split(/:/,$configline);
14000: %{$prp{$short}} = ();
14001: if (@plain > 0) {
14002: $prp{$short}{'std'} = $plain[0];
14003: for (my $i=1; $i<@plain; $i++) {
14004: $prp{$short}{'alt'.$i} = $plain[$i];
14005: }
14006: }
14007: }
14008: }
14009: close($config);
14010: }
14011:
14012: # ---------------------------------------------------------- Read package table
14013: {
14014: open(my $config,"<","$perlvar{'lonTabDir'}/packages.tab");
14015:
14016: while (my $configline=<$config>) {
14017: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
14018: chomp($configline);
14019: my ($short,$plain)=split(/:/,$configline);
14020: my ($pack,$name)=split(/\&/,$short);
14021: if ($plain ne '') {
14022: $packagetab{$pack.'&'.$name.'&name'}=$name;
14023: $packagetab{$short}=$plain;
14024: }
14025: }
14026: close($config);
14027: }
14028:
14029: # --------------------------------------------------------- Read loncaparev table
14030:
14031: &load_loncaparevs();
14032:
14033: # ------------------------------------------------------- Read serverhostID table
14034:
14035: &load_serverhomeIDs();
14036:
14037: # ---------------------------------------------------------- Read releaseslist XML
14038: {
14039: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
14040: if (-e $file) {
14041: my $parser = HTML::LCParser->new($file);
14042: while (my $token = $parser->get_token()) {
14043: if ($token->[0] eq 'S') {
14044: my $item = $token->[1];
14045: my $name = $token->[2]{'name'};
14046: my $value = $token->[2]{'value'};
14047: if ($item ne '' && $name ne '' && $value ne '') {
14048: my $release = $parser->get_text();
14049: $release =~ s/(^\s*|\s*$ )//gx;
14050: $needsrelease{$item.':'.$name.':'.$value} = $release;
14051: }
14052: }
14053: }
14054: }
14055: }
14056:
14057: # ---------------------------------------------------------- Read managers table
14058: {
14059: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
14060: if (open(my $config,"<","$perlvar{'lonTabDir'}/managers.tab")) {
14061: while (my $configline=<$config>) {
14062: chomp($configline);
14063: next if ($configline =~ /^\#/);
14064: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
14065: $managerstab{$configline} = 1;
14066: }
14067: }
14068: close($config);
14069: }
14070: }
14071: }
14072:
14073: # ------------- set up temporary directory
14074: {
14075: $tmpdir = LONCAPA::tempdir();
14076:
14077: }
14078:
14079: # ------------- set default texengine (domain default overrides this)
14080: {
14081: $deftex = LONCAPA::texengine();
14082: }
14083:
14084: # ------------- set default minimum length for passwords for internal auth users
14085: {
14086: $passwdmin = LONCAPA::passwd_min();
14087: }
14088:
14089: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
14090: 'compress_threshold'=> 20_000,
14091: });
14092:
14093: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
14094: $dumpcount=0;
14095: $locknum=0;
14096:
14097: &logtouch();
14098: &logthis('<font color="yellow">INFO: Read configuration</font>');
14099: $readit=1;
14100: {
14101: use integer;
14102: my $test=(2**32)+1;
14103: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
14104: &logthis(" Detected 64bit platform ($_64bit)");
14105: }
14106: }
14107: }
14108:
14109: 1;
14110: __END__
14111:
14112: =pod
14113:
14114: =head1 NAME
14115:
14116: Apache::lonnet - Subroutines to ask questions about things in the network.
14117:
14118: =head1 SYNOPSIS
14119:
14120: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
14121:
14122: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
14123:
14124: Common parameters:
14125:
14126: =over 4
14127:
14128: =item *
14129:
14130: $uname : an internal username (if $cname expecting a course Id specifically)
14131:
14132: =item *
14133:
14134: $udom : a domain (if $cdom expecting a course's domain specifically)
14135:
14136: =item *
14137:
14138: $symb : a resource instance identifier
14139:
14140: =item *
14141:
14142: $namespace : the name of a .db file that contains the data needed or
14143: being set.
14144:
14145: =back
14146:
14147: =head1 OVERVIEW
14148:
14149: lonnet provides subroutines which interact with the
14150: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
14151: about classes, users, and resources.
14152:
14153: For many of these objects you can also use this to store data about
14154: them or modify them in various ways.
14155:
14156: =head2 Symbs
14157:
14158: To identify a specific instance of a resource, LON-CAPA uses symbols
14159: or "symbs"X<symb>. These identifiers are built from the URL of the
14160: map, the resource number of the resource in the map, and the URL of
14161: the resource itself. The latter is somewhat redundant, but might help
14162: if maps change.
14163:
14164: An example is
14165:
14166: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
14167:
14168: The respective map entry is
14169:
14170: <resource id="19" src="/res/msu/korte/tests/part12.problem"
14171: title="Problem 2">
14172: </resource>
14173:
14174: Symbs are used by the random number generator, as well as to store and
14175: restore data specific to a certain instance of for example a problem.
14176:
14177: =head2 Storing And Retrieving Data
14178:
14179: X<store()>X<cstore()>X<restore()>Three of the most important functions
14180: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
14181: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
14182: is is the non-critical message twin of cstore. These functions are for
14183: handlers to store a perl hash to a user's permanent data space in an
14184: easy manner, and to retrieve it again on another call. It is expected
14185: that a handler would use this once at the beginning to retrieve data,
14186: and then again once at the end to send only the new data back.
14187:
14188: The data is stored in the user's data directory on the user's
14189: homeserver under the ID of the course.
14190:
14191: The hash that is returned by restore will have all of the previous
14192: value for all of the elements of the hash.
14193:
14194: Example:
14195:
14196: #creating a hash
14197: my %hash;
14198: $hash{'foo'}='bar';
14199:
14200: #storing it
14201: &Apache::lonnet::cstore(\%hash);
14202:
14203: #changing a value
14204: $hash{'foo'}='notbar';
14205:
14206: #adding a new value
14207: $hash{'bar'}='foo';
14208: &Apache::lonnet::cstore(\%hash);
14209:
14210: #retrieving the hash
14211: my %history=&Apache::lonnet::restore();
14212:
14213: #print the hash
14214: foreach my $key (sort(keys(%history))) {
14215: print("\%history{$key} = $history{$key}");
14216: }
14217:
14218: Will print out:
14219:
14220: %history{1:foo} = bar
14221: %history{1:keys} = foo:timestamp
14222: %history{1:timestamp} = 990455579
14223: %history{2:bar} = foo
14224: %history{2:foo} = notbar
14225: %history{2:keys} = foo:bar:timestamp
14226: %history{2:timestamp} = 990455580
14227: %history{bar} = foo
14228: %history{foo} = notbar
14229: %history{timestamp} = 990455580
14230: %history{version} = 2
14231:
14232: Note that the special hash entries C<keys>, C<version> and
14233: C<timestamp> were added to the hash. C<version> will be equal to the
14234: total number of versions of the data that have been stored. The
14235: C<timestamp> attribute will be the UNIX time the hash was
14236: stored. C<keys> is available in every historical section to list which
14237: keys were added or changed at a specific historical revision of a
14238: hash.
14239:
14240: B<Warning>: do not store the hash that restore returns directly. This
14241: will cause a mess since it will restore the historical keys as if the
14242: were new keys. I.E. 1:foo will become 1:1:foo etc.
14243:
14244: Calling convention:
14245:
14246: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname);
14247: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$laststore);
14248:
14249: For more detailed information, see lonnet specific documentation.
14250:
14251: =head1 RETURN MESSAGES
14252:
14253: =over 4
14254:
14255: =item * B<con_lost>: unable to contact remote host
14256:
14257: =item * B<con_delayed>: unable to contact remote host, message will be delivered
14258: when the connection is brought back up
14259:
14260: =item * B<con_failed>: unable to contact remote host and unable to save message
14261: for later delivery
14262:
14263: =item * B<error:>: an error a occurred, a description of the error follows the :
14264:
14265: =item * B<no_such_host>: unable to fund a host associated with the user/domain
14266: that was requested
14267:
14268: =back
14269:
14270: =head1 PUBLIC SUBROUTINES
14271:
14272: =head2 Session Environment Functions
14273:
14274: =over 4
14275:
14276: =item *
14277: X<appenv()>
14278: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
14279: the user envirnoment file, and will be restored for each access this
14280: user makes during this session, also modifies the %env for the current
14281: process. Optional rolesarrayref - if defined contains a reference to an array
14282: of roles which are exempt from the restriction on modifying user.role entries
14283: in the user's environment.db and in %env.
14284:
14285: =item *
14286: X<delenv()>
14287: B<delenv($delthis,$regexp)>: removes all items from the session
14288: environment file that begin with $delthis. If the
14289: optional second arg - $regexp - is true, $delthis is treated as a
14290: regular expression, otherwise \Q$delthis\E is used.
14291: The values are also deleted from the current processes %env.
14292:
14293: =item * get_env_multiple($name)
14294:
14295: gets $name from the %env hash, it seemlessly handles the cases where multiple
14296: values may be defined and end up as an array ref.
14297:
14298: returns an array of values
14299:
14300: =back
14301:
14302: =head2 User Information
14303:
14304: =over 4
14305:
14306: =item *
14307: X<queryauthenticate()>
14308: B<queryauthenticate($uname,$udom)>: try to determine user's current
14309: authentication scheme
14310:
14311: =item *
14312: X<authenticate()>
14313: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
14314: authenticate user from domain's lib servers (first use the current
14315: one). C<$upass> should be the users password.
14316: $checkdefauth is optional (value is 1 if a check should be made to
14317: authenticate user using default authentication method, and allow
14318: account creation if username does not have account in the domain).
14319: $clientcancheckhost is optional (value is 1 if checking whether the
14320: server can host will occur on the client side in lonauth.pm).
14321:
14322: =item *
14323: X<homeserver()>
14324: B<homeserver($uname,$udom)>: find the server which has
14325: the user's directory and files (there must be only one), this caches
14326: the answer, and also caches if there is a borken connection.
14327:
14328: =item *
14329: X<idget()>
14330: B<idget($udom,@ids)>: find the usernames behind a list of IDs
14331: (IDs are a unique resource in a domain, there must be only 1 ID per
14332: username, and only 1 username per ID in a specific domain) (returns
14333: hash: id=>name,id=>name)
14334:
14335: =item *
14336: X<idrget()>
14337: B<idrget($udom,@unames)>: find the IDs behind a list of
14338: usernames (returns hash: name=>id,name=>id)
14339:
14340: =item *
14341: X<idput()>
14342: B<idput($udom,%ids)>: store away a list of names and associated IDs
14343:
14344: =item *
14345: X<rolesinit()>
14346: B<rolesinit($udom,$username)>: get user privileges.
14347: returns user role, first access and timer interval hashes
14348:
14349: =item *
14350: X<privileged()>
14351: B<privileged($username,$domain)>: returns a true if user has a
14352: privileged and active role (i.e. su or dc), false otherwise.
14353:
14354: =item *
14355: X<getsection()>
14356: B<getsection($udom,$uname,$cname)>: finds the section of student in the
14357: course $cname, return section name/number or '' for "not in course"
14358: and '-1' for "no section"
14359:
14360: =item *
14361: X<userenvironment()>
14362: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
14363: passed in @what from the requested user's environment, returns a hash
14364:
14365: =item *
14366: X<userlog_query()>
14367: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
14368: activity.log file. %filters defines filters applied when parsing the
14369: log file. These can be start or end timestamps, or the type of action
14370: - log to look for Login or Logout events, check for Checkin or
14371: Checkout, role for role selection. The response is in the form
14372: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
14373: escaped strings of the action recorded in the activity.log file.
14374:
14375: =back
14376:
14377: =head2 User Roles
14378:
14379: =over 4
14380:
14381: =item *
14382:
14383: allowed($priv,$uri,$symb,$role,$clientip,$noblockcheck) : check for a user privilege;
14384: returns codes for allowed actions.
14385:
14386: The first argument is required, all others are optional.
14387:
14388: $priv is the privilege being checked.
14389: $uri contains additional information about what is being checked for access (e.g.,
14390: URL, course ID etc.).
14391: $symb is the unique resource instance identifier in a course; if needed,
14392: but not provided, it will be retrieved via a call to &symbread().
14393: $role is the role for which a priv is being checked (only used if priv is evb).
14394: $clientip is the user's IP address (only used when checking for access to portfolio
14395: files).
14396: $noblockcheck, if true, skips calls to &has_comm_blocking() for the bre priv. This
14397: prevents recursive calls to &allowed.
14398:
14399: F: full access
14400: U,I,K: authentication modes (cxx only)
14401: '': forbidden
14402: 1: user needs to choose course
14403: 2: browse allowed
14404: A: passphrase authentication needed
14405: B: access temporarily blocked because of a blocking event in a course.
14406:
14407: =item *
14408:
14409: constructaccess($url,$setpriv) : check for access to construction space URL
14410:
14411: See if the owner domain and name in the URL match those in the
14412: expected environment. If so, return three element list
14413: ($ownername,$ownerdomain,$ownerhome).
14414:
14415: Otherwise return the null string.
14416:
14417: If second argument 'setpriv' is true, it assigns the privileges,
14418: and returns the same three element list, unless the owner has
14419: blocked "ad hoc" Domain Coordinator access to the Author Space,
14420: in which case the null string is returned.
14421:
14422: =item *
14423:
14424: definerole($rolename,$sysrole,$domrole,$courole,$uname,$udom) : define role;
14425: define a custom role rolename set privileges in format of lonTabs/roles.tab
14426: for system, domain, and course level. $uname and $udom are optional (current
14427: user's username and domain will be used when either of $uname or $udom are absent.
14428:
14429: =item *
14430:
14431: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
14432: (rolesplain.tab); plain text explanation of a user role term.
14433: $type is Course (default) or Community.
14434: If $forcedefault evaluates to true, text returned will be default
14435: text for $type. Otherwise, if this is a course, the text returned
14436: will be a custom name for the role (if defined in the course's
14437: environment). If no custom name is defined the default is returned.
14438:
14439: =item *
14440:
14441: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv) :
14442: All arguments are optional. Returns a hash of a roles, either for
14443: co-author/assistant author roles for a user's Construction Space
14444: (default), or if $context is 'userroles', roles for the user himself,
14445: In the hash, keys are set to colon-separated $uname,$udom,$role, and
14446: (optionally) if $withsec is true, a fourth colon-separated item - $section.
14447: For each key, value is set to colon-separated start and end times for
14448: the role. If no username and domain are specified, will default to
14449: current user/domain. Types, roles, and roledoms are references to arrays
14450: of role statuses (active, future or previous), roles
14451: (e.g., cc,in, st etc.) and domains of the roles which can be used
14452: to restrict the list of roles reported. If no array ref is
14453: provided for types, will default to return only active roles.
14454:
14455: =item *
14456:
14457: in_course($udom,$uname,$cdom,$cnum,$type,$hideprivileged) : determine if
14458: user: $uname:$udom has a role in the course: $cdom_$cnum.
14459:
14460: Additional optional arguments are: $type (if role checking is to be restricted
14461: to certain user status types -- previous (expired roles), active (currently
14462: available roles) or future (roles available in the future), and
14463: $hideprivileged -- if true will not report course roles for users who
14464: have active Domain Coordinator role in course's domain or in additional
14465: domains (specified in 'Domains to check for privileged users' in course
14466: environment -- set via: Course Settings -> Classlists and staff listing).
14467:
14468: =item *
14469:
14470: privileged($username,$domain,$possdomains,$possroles) : returns 1 if user
14471: $username:$domain is a privileged user (e.g., Domain Coordinator or Super User)
14472: $possdomains and $possroles are optional array refs -- to domains to check and
14473: roles to check. If $possdomains is not specified, a dump will be done of the
14474: users' roles.db to check for a dc or su role in any domain. This can be
14475: time consuming if &privileged is called repeatedly (e.g., when displaying a
14476: classlist), so in such cases, supplying a $possdomains array is preferred, as
14477: this then allows &privileged_by_domain() to be used, which caches the identity
14478: of privileged users, eliminating the need for repeated calls to &dump().
14479:
14480: =item *
14481:
14482: privileged_by_domain($possdomains,$roles) : returns a hash of a hash of a hash,
14483: where the outer hash keys are domains specified in the $possdomains array ref,
14484: next inner hash keys are privileged roles specified in the $roles array ref,
14485: and the innermost hash contains key = value pairs for username:domain = end:start
14486: for active or future "privileged" users with that role in that domain. To avoid
14487: repeated dumps of domain roles -- via &get_domain_roles() -- contents of the
14488: innerhash are cached using priv_$role and $dom as the identifiers.
14489:
14490: =back
14491:
14492: =head2 User Modification
14493:
14494: =over 4
14495:
14496: =item *
14497:
14498: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
14499: user for the level given by URL. Optional start and end dates (leave empty
14500: string or zero for "no date")
14501:
14502: =item *
14503:
14504: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
14505: change a users, password, possible return values are: ok,
14506: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
14507: refused
14508:
14509: =item *
14510:
14511: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
14512:
14513: =item *
14514:
14515: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
14516: $forceid,$desiredhome,$email,$inststatus,$candelete) :
14517:
14518: will update user information (firstname,middlename,lastname,generation,
14519: permanentemail), and if forceid is true, student/employee ID also.
14520: A user's institutional affiliation(s) can also be updated.
14521: User information fields will not be overwritten with empty entries
14522: unless the field is included in the $candelete array reference.
14523: This array is included when a single user is modified via "Manage Users",
14524: or when Autoupdate.pl is run by cron in a domain.
14525:
14526: =item *
14527:
14528: modifystudent
14529:
14530: modify a student's enrollment and identification information.
14531: The course id is resolved based on the current user's environment.
14532: This means the invoking user must be a course coordinator or otherwise
14533: associated with a course.
14534:
14535: This call is essentially a wrapper for lonnet::modifyuser and
14536: lonnet::modify_student_enrollment
14537:
14538: Inputs:
14539:
14540: =over 4
14541:
14542: =item B<$udom> Student's loncapa domain
14543:
14544: =item B<$uname> Student's loncapa login name
14545:
14546: =item B<$uid> Student/Employee ID
14547:
14548: =item B<$umode> Student's authentication mode
14549:
14550: =item B<$upass> Student's password
14551:
14552: =item B<$first> Student's first name
14553:
14554: =item B<$middle> Student's middle name
14555:
14556: =item B<$last> Student's last name
14557:
14558: =item B<$gene> Student's generation
14559:
14560: =item B<$usec> Student's section in course
14561:
14562: =item B<$end> Unix time of the roles expiration
14563:
14564: =item B<$start> Unix time of the roles start date
14565:
14566: =item B<$forceid> If defined, allow $uid to be changed
14567:
14568: =item B<$desiredhome> server to use as home server for student
14569:
14570: =item B<$email> Student's permanent e-mail address
14571:
14572: =item B<$type> Type of enrollment (auto or manual)
14573:
14574: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
14575:
14576: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
14577:
14578: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
14579:
14580: =item B<$context> role change context (shown in User Management Logs display in a course)
14581:
14582: =item B<$inststatus> institutional status of user - : separated string of escaped status types
14583:
14584: =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.
14585:
14586: =back
14587:
14588: =item *
14589:
14590: modify_student_enrollment
14591:
14592: Change a student's enrollment status in a class. The environment variable
14593: 'role.request.course' must be defined for this function to proceed.
14594:
14595: Inputs:
14596:
14597: =over 4
14598:
14599: =item $udom, student's domain
14600:
14601: =item $uname, student's name
14602:
14603: =item $uid, student's user id
14604:
14605: =item $first, student's first name
14606:
14607: =item $middle
14608:
14609: =item $last
14610:
14611: =item $gene
14612:
14613: =item $usec
14614:
14615: =item $end
14616:
14617: =item $start
14618:
14619: =item $type
14620:
14621: =item $locktype
14622:
14623: =item $cid
14624:
14625: =item $selfenroll
14626:
14627: =item $context
14628:
14629: =item $credits, number of credits student will earn from this class
14630:
14631: =item $instsec, institutional course section code for student
14632:
14633: =back
14634:
14635:
14636: =item *
14637:
14638: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
14639: custom role; give a custom role to a user for the level given by URL. Specify
14640: name and domain of role author, and role name
14641:
14642: =item *
14643:
14644: revokerole($udom,$uname,$url,$role) : revoke a role for url
14645:
14646: =item *
14647:
14648: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
14649:
14650: =back
14651:
14652: =head2 Course Infomation
14653:
14654: =over 4
14655:
14656: =item *
14657:
14658: coursedescription($courseid,$options) : returns a hash of information about the
14659: specified course id, including all environment settings for the
14660: course, the description of the course will be in the hash under the
14661: key 'description'
14662:
14663: $options is an optional parameter that if supplied is a hash reference that controls
14664: what how this function works. It has the following key/values:
14665:
14666: =over 4
14667:
14668: =item freshen_cache
14669:
14670: If defined, and the environment cache for the course is valid, it is
14671: returned in the returned hash.
14672:
14673: =item one_time
14674:
14675: If defined, the last cache time is set to _now_
14676:
14677: =item user
14678:
14679: If defined, the supplied username is used instead of the current user.
14680:
14681:
14682: =back
14683:
14684: =item *
14685:
14686: resdata($name,$domain,$type,@which) : request for current parameter
14687: setting for a specific $type, where $type is either 'course' or 'user',
14688: @what should be a list of parameters to ask about. This routine caches
14689: answers for 10 minutes.
14690:
14691: =item *
14692:
14693: get_courseresdata($courseid, $domain) : dump the entire course resource
14694: data base, returning a hash that is keyed by the resource name and has
14695: values that are the resource value. I believe that the timestamps and
14696: versions are also returned.
14697:
14698: get_numsuppfiles($cnum,$cdom) : retrieve number of files in a course's
14699: supplemental content area. This routine caches the number of files for
14700: 10 minutes.
14701:
14702: =back
14703:
14704: =head2 Course Modification
14705:
14706: =over 4
14707:
14708: =item *
14709:
14710: writecoursepref($courseid,%prefs) : write preferences (environment
14711: database) for a course
14712:
14713: =item *
14714:
14715: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
14716:
14717: =item *
14718:
14719: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
14720:
14721: =item *
14722:
14723: is_course($courseid), is_course($cdom, $cnum)
14724:
14725: Accepts either a combined $courseid (in the form of domain_courseid) or the
14726: two component version $cdom, $cnum. It checks if the specified course exists.
14727:
14728: Returns:
14729: undef if the course doesn't exist, otherwise
14730: in scalar context the combined courseid.
14731: in list context the two components of the course identifier, domain and
14732: courseid.
14733:
14734: =back
14735:
14736: =head2 Bubblesheet Configuration
14737:
14738: =over 4
14739:
14740: =item *
14741:
14742: get_scantron_config($which)
14743:
14744: $which - the name of the configuration to parse from the file.
14745:
14746: Parses and returns the bubblesheet configuration line selected as a
14747: hash of configuration file fields.
14748:
14749:
14750: Returns:
14751: If the named configuration is not in the file, an empty
14752: hash is returned.
14753:
14754: a hash with the fields
14755: name - internal name for the this configuration setup
14756: description - text to display to operator that describes this config
14757: CODElocation - if 0 or the string 'none'
14758: - no CODE exists for this config
14759: if -1 || the string 'letter'
14760: - a CODE exists for this config and is
14761: a string of letters
14762: Unsupported value (but planned for future support)
14763: if a positive integer
14764: - The CODE exists as the first n items from
14765: the question section of the form
14766: if the string 'number'
14767: - The CODE exists for this config and is
14768: a string of numbers
14769: CODEstart - (only matter if a CODE exists) column in the line where
14770: the CODE starts
14771: CODElength - length of the CODE
14772: IDstart - column where the student/employee ID starts
14773: IDlength - length of the student/employee ID info
14774: Qstart - column where the information from the bubbled
14775: 'questions' start
14776: Qlength - number of columns comprising a single bubble line from
14777: the sheet. (usually either 1 or 10)
14778: Qon - either a single character representing the character used
14779: to signal a bubble was chosen in the positional setup, or
14780: the string 'letter' if the letter of the chosen bubble is
14781: in the final, or 'number' if a number representing the
14782: chosen bubble is in the file (1->A 0->J)
14783: Qoff - the character used to represent that a bubble was
14784: left blank
14785: PaperID - if the scanning process generates a unique number for each
14786: sheet scanned the column that this ID number starts in
14787: PaperIDlength - number of columns that comprise the unique ID number
14788: for the sheet of paper
14789: FirstName - column that the first name starts in
14790: FirstNameLength - number of columns that the first name spans
14791: LastName - column that the last name starts in
14792: LastNameLength - number of columns that the last name spans
14793: BubblesPerRow - number of bubbles available in each row used to
14794: bubble an answer. (If not specified, 10 assumed).
14795:
14796:
14797: =item *
14798:
14799: get_scantronformat_file($cdom)
14800:
14801: $cdom - the course's domain (optional); if not supplied, uses
14802: domain for current $env{'request.course.id'}.
14803:
14804: Returns an array containing lines from the scantron format file for
14805: the domain of the course.
14806:
14807: If a url for a custom.tab file is listed in domain's configuration.db,
14808: lines are from this file.
14809:
14810: Otherwise, if a default.tab has been published in RES space by the
14811: domainconfig user, lines are from this file.
14812:
14813: Otherwise, fall back to getting lines from the legacy file on the
14814: local server: /home/httpd/lonTabs/default_scantronformat.tab
14815:
14816: =back
14817:
14818: =head2 Resource Subroutines
14819:
14820: =over 4
14821:
14822: =item *
14823:
14824: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
14825:
14826: =item *
14827:
14828: repcopy($filename) : subscribes to the requested file, and attempts to
14829: replicate from the owning library server, Might return
14830: 'unavailable', 'not_found', 'forbidden', 'ok', or
14831: 'bad_request', also attempts to grab the metadata for the
14832: resource. Expects the local filesystem pathname
14833: (/home/httpd/html/res/....)
14834:
14835: =back
14836:
14837: =head2 Resource Information
14838:
14839: =over 4
14840:
14841: =item *
14842:
14843: EXT($varname,$symb,$udom,$uname,$usection,$recurse,$cid) : evaluates
14844: and returns the value of a variety of different possible values,
14845: $varname should be a request string, and the other parameters can be
14846: used to specify who and what one is asking about. Ordinarily, $cid
14847: does not need to be specified, as it is retrived from
14848: $env{'request.course.id'}, but &Apache::lonnet::EXT() is called
14849: within lonuserstate::loadmap() when initializing a course, before
14850: $env{'request.course.id'} has been set, so it needs to be provided
14851: in that one case.
14852:
14853: Possible values for $varname are environment.lastname (or other item
14854: from the envirnment hash), user.name (or someother aspect about the
14855: user), resource.0.maxtries (or some other part and parameter of a
14856: resource)
14857:
14858: =item *
14859:
14860: directcondval($number) : get current value of a condition; reads from a state
14861: string
14862:
14863: =item *
14864:
14865: condval($condidx) : value of condition index based on state
14866:
14867: =item *
14868:
14869: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
14870: resource's metadata, $what should be either a specific key, or either
14871: 'keys' (to get a list of possible keys) or 'packages' to get a list of
14872: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
14873:
14874: this function automatically caches all requests
14875:
14876: =item *
14877:
14878: metadata_query($query,$custom,$customshow) : make a metadata query against the
14879: network of library servers; returns file handle of where SQL and regex results
14880: will be stored for query
14881:
14882: =item *
14883:
14884: symbread($filename,$donotrecurse,$ignorecachednull,$checkforblock,$possibles) :
14885: return symbolic list entry (all arguments optional).
14886:
14887: Args: filename is the filename (including path) for the file for which a symb
14888: is required; donotrecurse, if true will prevent calls to allowed() being made
14889: to check access status if more than one resource was found in the bighash
14890: (see rev. 1.249) to avoid an infinite loop if an ambiguous resource is part of
14891: a randompick); ignorecachednull, if true will prevent a symb of '' being
14892: returned if $env{$cache_str} is defined as ''; checkforblock if true will
14893: cause possible symbs to be checked to determine if they are subject to content
14894: blocking, if so they will not be included as possible symbs; possibles is a
14895: ref to a hash, which, as a side effect, will be populated with all possible
14896: symbs (content blocking not tested).
14897:
14898: returns the data handle
14899:
14900: =item *
14901:
14902: symbverify($symb,$thisfn,$encstate) : verifies that $symb actually exists
14903: and is a possible symb for the URL in $thisfn, and if is an encrypted
14904: resource that the user accessed using /enc/ returns a 1 on success, 0
14905: on failure, user must be in a course, as it assumes the existence of
14906: the course initial hash, and uses $env('request.course.id'}. The third
14907: arg is an optional reference to a scalar. If this arg is passed in the
14908: call to symbverify, it will be set to 1 if the symb has been set to be
14909: encrypted; otherwise it will be null.
14910:
14911: =item *
14912:
14913: symbclean($symb) : removes versions numbers from a symb, returns the
14914: cleaned symb
14915:
14916: =item *
14917:
14918: is_on_map($uri) : checks if the $uri is somewhere on the current
14919: course map, user must be in a course for it to work.
14920:
14921: =item *
14922:
14923: numval($salt) : return random seed value (addend for rndseed)
14924:
14925: =item *
14926:
14927: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
14928: a random seed, all arguments are optional, if they aren't sent it uses the
14929: environment to derive them. Note: if symb isn't sent and it can't get one
14930: from &symbread it will use the current time as its return value
14931:
14932: =item *
14933:
14934: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
14935: unfakeable, receipt
14936:
14937: =item *
14938:
14939: receipt() : API to ireceipt working off of env values; given out to users
14940:
14941: =item *
14942:
14943: countacc($url) : count the number of accesses to a given URL
14944:
14945: =item *
14946:
14947: 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
14948:
14949: =item *
14950:
14951: 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)
14952:
14953: =item *
14954:
14955: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
14956:
14957: =item *
14958:
14959: devalidate($symb) : devalidate temporary spreadsheet calculations,
14960: forcing spreadsheet to reevaluate the resource scores next time.
14961:
14962: =item *
14963:
14964: can_edit_resource($file,$cnum,$cdom,$resurl,$symb,$group) : determine if current user can edit a particular resource,
14965: when viewing in course context.
14966:
14967: input: six args -- filename (decluttered), course number, course domain,
14968: url, symb (if registered) and group (if this is a
14969: group item -- e.g., bulletin board, group page etc.).
14970:
14971: output: array of five scalars --
14972: $cfile -- url for file editing if editable on current server
14973: $home -- homeserver of resource (i.e., for author if published,
14974: or course if uploaded.).
14975: $switchserver -- 1 if server switch will be needed.
14976: $forceedit -- 1 if icon/link should be to go to edit mode
14977: $forceview -- 1 if icon/link should be to go to view mode
14978:
14979: =item *
14980:
14981: is_course_upload($file,$cnum,$cdom)
14982:
14983: Used in course context to determine if current file was uploaded to
14984: the course (i.e., would be found in /userfiles/docs on the course's
14985: homeserver.
14986:
14987: input: 3 args -- filename (decluttered), course number and course domain.
14988: output: boolean -- 1 if file was uploaded.
14989:
14990: =back
14991:
14992: =head2 Storing/Retreiving Data
14993:
14994: =over 4
14995:
14996: =item *
14997:
14998: store($storehash,$symb,$namespace,$udom,$uname,$laststore) : stores hash
14999: permanently for this url; hashref needs to be given and should be a \%hashname;
15000: the remaining args aren't required and if they aren't passed or are '' they will
15001: be derived from the env (with the exception of $laststore, which is an
15002: optional arg used when a user's submission is stored in grading).
15003: $laststore is $version=$timestamp, where $version is the most recent version
15004: number retrieved for the corresponding $symb in the $namespace db file, and
15005: $timestamp is the timestamp for that transaction (UNIX time).
15006: $laststore is currently only passed when cstore() is called by
15007: structuretags::finalize_storage().
15008:
15009: =item *
15010:
15011: cstore($storehash,$symb,$namespace,$udom,$uname,$laststore) : same as store
15012: but uses critical subroutine
15013:
15014: =item *
15015:
15016: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
15017: all args are optional
15018:
15019: =item *
15020:
15021: dumpstore($namespace,$udom,$uname,$regexp,$range) :
15022: dumps the complete (or key matching regexp) namespace into a hash
15023: ($udom, $uname, $regexp, $range are optional) for a namespace that is
15024: normally &store()ed into
15025:
15026: $range should be either an integer '100' (give me the first 100
15027: matching records)
15028: or be two integers sperated by a - with no spaces
15029: '30-50' (give me the 30th through the 50th matching
15030: records)
15031:
15032:
15033: =item *
15034:
15035: putstore($namespace,$symb,$version,$storehash,$udomain,$uname,$tolog) :
15036: replaces a &store() version of data with a replacement set of data
15037: for a particular resource in a namespace passed in the $storehash hash
15038: reference. If $tolog is true, the transaction is logged in the courselog
15039: with an action=PUTSTORE.
15040:
15041: =item *
15042:
15043: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
15044: works very similar to store/cstore, but all data is stored in a
15045: temporary location and can be reset using tmpreset, $storehash should
15046: be a hash reference, returns nothing on success
15047:
15048: =item *
15049:
15050: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
15051: similar to restore, but all data is stored in a temporary location and
15052: can be reset using tmpreset. Returns a hash of values on success,
15053: error string otherwise.
15054:
15055: =item *
15056:
15057: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
15058: deltes all keys for $symb form the temporary storage hash.
15059:
15060: =item *
15061:
15062: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15063: reference filled in from namesp ($udom and $uname are optional)
15064:
15065: =item *
15066:
15067: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
15068: namesp ($udom and $uname are optional)
15069:
15070: =item *
15071:
15072: dump($namespace,$udom,$uname,$regexp,$range) :
15073: dumps the complete (or key matching regexp) namespace into a hash
15074: ($udom, $uname, $regexp, $range are optional)
15075:
15076: $range should be either an integer '100' (give me the first 100
15077: matching records)
15078: or be two integers sperated by a - with no spaces
15079: '30-50' (give me the 30th through the 50th matching
15080: records)
15081: =item *
15082:
15083: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
15084: $store can be a scalar, an array reference, or if the amount to be
15085: incremented is > 1, a hash reference.
15086:
15087: ($udom and $uname are optional)
15088:
15089: =item *
15090:
15091: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
15092: ($udom and $uname are optional)
15093:
15094: =item *
15095:
15096: cput($namespace,$storehash,$udom,$uname) : critical put
15097: ($udom and $uname are optional)
15098:
15099: =item *
15100:
15101: newput($namespace,$storehash,$udom,$uname) :
15102:
15103: Attempts to store the items in the $storehash, but only if they don't
15104: currently exist, if this succeeds you can be certain that you have
15105: successfully created a new key value pair in the $namespace db.
15106:
15107:
15108: Args:
15109: $namespace: name of database to store values to
15110: $storehash: hashref to store to the db
15111: $udom: (optional) domain of user containing the db
15112: $uname: (optional) name of user caontaining the db
15113:
15114: Returns:
15115: 'ok' -> succeeded in storing all keys of $storehash
15116: 'key_exists: <key>' -> failed to anything out of $storehash, as at
15117: least <key> already existed in the db (other
15118: requested keys may also already exist)
15119: 'error: <msg>' -> unable to tie the DB or other error occurred
15120: 'con_lost' -> unable to contact request server
15121: 'refused' -> action was not allowed by remote machine
15122:
15123:
15124: =item *
15125:
15126: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
15127: reference filled in from namesp (encrypts the return communication)
15128: ($udom and $uname are optional)
15129:
15130: =item *
15131:
15132: log($udom,$name,$home,$message) : write to permanent log for user; use
15133: critical subroutine
15134:
15135: =item *
15136:
15137: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
15138: array reference filled in from namespace found in domain level on either
15139: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
15140:
15141: =item *
15142:
15143: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
15144: domain level either on specified domain server ($uhome) or primary domain
15145: server ($udom and $uhome are optional)
15146:
15147: =item *
15148:
15149: get_domain_defaults($target_domain,$ignore_cache) : returns hash with defaults
15150: for: authentication, language, quotas, timezone, date locale, and portal URL in
15151: the target domain.
15152:
15153: May also include additional key => value pairs for the following groups:
15154:
15155: =over
15156:
15157: =item
15158: disk quotas (MB allocated by default to portfolios and authoring spaces).
15159:
15160: =over
15161:
15162: =item defaultquota, authorquota
15163:
15164: =back
15165:
15166: =item
15167: tools (availability of aboutme page, blog, webDAV access for authoring spaces,
15168: portfolio for users).
15169:
15170: =over
15171:
15172: =item
15173: aboutme, blog, webdav, portfolio
15174:
15175: =back
15176:
15177: =item
15178: requestcourses: ability to request courses, and how requests are processed.
15179:
15180: =over
15181:
15182: =item
15183: official, unofficial, community, textbook
15184:
15185: =back
15186:
15187: =item
15188: inststatus: types of institutional affiliation, and order in which they are displayed.
15189:
15190: =over
15191:
15192: =item
15193: inststatustypes, inststatusorder, inststatusguest
15194:
15195: =back
15196:
15197: =item
15198: coursedefaults: can PDF forms can be created, default credits for courses, default quotas (MB)
15199: for course's uploaded content.
15200:
15201: =over
15202:
15203: =item
15204: canuse_pdfforms, officialcredits, unofficialcredits, textbookcredits, officialquota, unofficialquota,
15205: communityquota, textbookquota
15206:
15207: =back
15208:
15209: =item
15210: usersessions: set options for hosting of your users in other domains, and hosting of users from other domains
15211: on your servers.
15212:
15213: =over
15214:
15215: =item
15216: remotesessions, hostedsessions
15217:
15218: =back
15219:
15220: =back
15221:
15222: In cases where a domain coordinator has never used the "Set Domain Configuration"
15223: utility to create a configuration.db file on a domain's primary library server
15224: only the following domain defaults: auth_def, auth_arg_def, lang_def
15225: -- corresponding values are authentication type (internal, krb4, krb5,
15226: or localauth), initial password or a kerberos realm, language (e.g., en-us) --
15227: will be available. Values are retrieved from cache (if current), unless the
15228: optional $ignore_cache arg is true, or from domain's configuration.db (if available),
15229: or lastly from values in lonTabs/dns_domain,tab, or lonTabs/domain.tab.
15230:
15231: Typical usage:
15232:
15233: %domdefaults = &get_domain_defaults($target_domain);
15234:
15235: =back
15236:
15237: =head2 Network Status Functions
15238:
15239: =over 4
15240:
15241: =item *
15242:
15243: dirlist() : return directory list based on URI (first arg).
15244:
15245: Inputs: 1 required, 5 optional.
15246:
15247: =over
15248:
15249: =item
15250: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
15251:
15252: =item
15253: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
15254:
15255: =item
15256: $username - username of user/course to be listed. Extracted from $uri if absent.
15257:
15258: =item
15259: $getpropath - boolean: 1 if prepend path using &propath().
15260:
15261: =item
15262: $getuserdir - boolean: 1 if prepend path for "userfiles".
15263:
15264: =item
15265: $alternateRoot - path to prepend in place of path from $uri.
15266:
15267: =back
15268:
15269: Returns: Array of up to two items.
15270:
15271: =over
15272:
15273: a reference to an array of files/subdirectories
15274:
15275: =over
15276:
15277: Each element in the array of files/subdirectories is a & separated list of
15278: item name and the result of running stat on the item. If dirlist was requested
15279: for a file instead of a directory, the item name will be ''. For a directory
15280: listing, if the item is a metadata file, the element will end &N&M
15281: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
15282: default copyright set (1).
15283:
15284: =back
15285:
15286: a scalar containing error condition (if encountered).
15287:
15288: =over
15289:
15290: =item
15291: no_host (no homeserver identified for $username:$domain).
15292:
15293: =item
15294: no_such_host (server contacted for listing not identified as valid host).
15295:
15296: =item
15297: con_lost (connection to remote server failed).
15298:
15299: =item
15300: refused (invalid $username:$domain received on lond side).
15301:
15302: =item
15303: no_such_dir (directory at specified path on lond side does not exist).
15304:
15305: =item
15306: empty (directory at specified path on lond side is empty).
15307:
15308: =over
15309:
15310: This is currently not encountered because the &ls3, &ls2,
15311: &ls (_handler) routines on the lond side do not filter out
15312: . and .. from a directory listing.
15313:
15314: =back
15315:
15316: =back
15317:
15318: =back
15319:
15320: =item *
15321:
15322: spareserver() : find server with least workload from spare.tab
15323:
15324:
15325: =item *
15326:
15327: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
15328: if there is no corresponding loncapa host.
15329:
15330: =back
15331:
15332:
15333: =head2 Apache Request
15334:
15335: =over 4
15336:
15337: =item *
15338:
15339: ssi($url,%hash) : server side include, does a complete request cycle on url to
15340: localhost, posts hash
15341:
15342: =back
15343:
15344: =head2 Data to String to Data
15345:
15346: =over 4
15347:
15348: =item *
15349:
15350: hash2str(%hash) : convert a hash into a string complete with escaping and '='
15351: and '&' separators, supports elements that are arrayrefs and hashrefs
15352:
15353: =item *
15354:
15355: hashref2str($hashref) : convert a hashref into a string complete with
15356: escaping and '=' and '&' separators, supports elements that are
15357: arrayrefs and hashrefs
15358:
15359: =item *
15360:
15361: arrayref2str($arrayref) : convert an arrayref into a string complete
15362: with escaping and '&' separators, supports elements that are arrayrefs
15363: and hashrefs
15364:
15365: =item *
15366:
15367: str2hash($string) : convert string to hash using unescaping and
15368: splitting on '=' and '&', supports elements that are arrayrefs and
15369: hashrefs
15370:
15371: =item *
15372:
15373: str2array($string) : convert string to hash using unescaping and
15374: splitting on '&', supports elements that are arrayrefs and hashrefs
15375:
15376: =back
15377:
15378: =head2 Logging Routines
15379:
15380:
15381: These routines allow one to make log messages in the lonnet.log and
15382: lonnet.perm logfiles.
15383:
15384: =over 4
15385:
15386: =item *
15387:
15388: logtouch() : make sure the logfile, lonnet.log, exists
15389:
15390: =item *
15391:
15392: logthis() : append message to the normal lonnet.log file, it gets
15393: preiodically rolled over and deleted.
15394:
15395: =item *
15396:
15397: logperm() : append a permanent message to lonnet.perm.log, this log
15398: file never gets deleted by any automated portion of the system, only
15399: messages of critical importance should go in here.
15400:
15401:
15402: =back
15403:
15404: =head2 General File Helper Routines
15405:
15406: =over 4
15407:
15408: =item *
15409:
15410: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
15411: (a) files in /uploaded
15412: (i) If a local copy of the file exists -
15413: compares modification date of local copy with last-modified date for
15414: definitive version stored on home server for course. If local copy is
15415: stale, requests a new version from the home server and stores it.
15416: If the original has been removed from the home server, then local copy
15417: is unlinked.
15418: (ii) If local copy does not exist -
15419: requests the file from the home server and stores it.
15420:
15421: If $caller is 'uploadrep':
15422: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
15423: for request for files originally uploaded via DOCS.
15424: - returns 'ok' if fresh local copy now available, -1 otherwise.
15425:
15426: Otherwise:
15427: This indicates a call from the content generation phase of the request.
15428: - returns the entire contents of the file or -1.
15429:
15430: (b) files in /res
15431: - returns the entire contents of a file or -1;
15432: it properly subscribes to and replicates the file if neccessary.
15433:
15434:
15435: =item *
15436:
15437: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
15438: reference
15439:
15440: returns either a stat() list of data about the file or an empty list
15441: if the file doesn't exist or couldn't find out about it (connection
15442: problems or user unknown)
15443:
15444: =item *
15445:
15446: filelocation($dir,$file) : returns file system location of a file
15447: based on URI; meant to be "fairly clean" absolute reference, $dir is a
15448: directory that relative $file lookups are to looked in ($dir of /a/dir
15449: and a file of ../bob will become /a/bob)
15450:
15451: =item *
15452:
15453: hreflocation($dir,$file) : returns file system location or a URL; same as
15454: filelocation except for hrefs
15455:
15456: =item *
15457:
15458: declutter() : declutters URLs -- remove beginning slashes, 'res' etc.
15459: also removes beginning /home/httpd/html unless /priv/ follows it.
15460:
15461: =back
15462:
15463: =head2 Usererfile file routines (/uploaded*)
15464:
15465: =over 4
15466:
15467: =item *
15468:
15469: userfileupload(): main rotine for putting a file in a user or course's
15470: filespace, arguments are,
15471:
15472: formname - required - this is the name of the element in $env where the
15473: filename, and the contents of the file to create/modifed exist
15474: the filename is in $env{'form.'.$formname.'.filename'} and the
15475: contents of the file is located in $env{'form.'.$formname}
15476: context - if coursedoc, store the file in the course of the active role
15477: of the current user;
15478: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
15479: if 'canceloverwrite': delete file in tmp/overwrites directory
15480: subdir - required - subdirectory to put the file in under ../userfiles/
15481: if undefined, it will be placed in "unknown"
15482:
15483: (This routine calls clean_filename() to remove any dangerous
15484: characters from the filename, and then calls finuserfileupload() to
15485: complete the transaction)
15486:
15487: returns either the url of the uploaded file (/uploaded/....) if successful
15488: and /adm/notfound.html if unsuccessful
15489:
15490: =item *
15491:
15492: clean_filename(): routine for cleaing a filename up for storage in
15493: userfile space, argument is:
15494:
15495: filename - proposed filename
15496:
15497: returns: the new clean filename
15498:
15499: =item *
15500:
15501: finishuserfileupload(): routine that creates and sends the file to
15502: userspace, probably shouldn't be called directly
15503:
15504: docuname: username or courseid of destination for the file
15505: docudom: domain of user/course of destination for the file
15506: formname: same as for userfileupload()
15507: fname: filename (including subdirectories) for the file
15508: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
15509: if hashref, and context is scantron, will convert csv format to standard format
15510: allfiles: reference to hash used to store objects found by parser
15511: codebase: reference to hash used for codebases of java objects found by parser
15512: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
15513: thumbheight: height (pixels) of thumbnail to be created for uploaded image
15514: resizewidth: width to be used to resize image using resizeImage from ImageMagick
15515: resizeheight: height to be used to resize image using resizeImage from ImageMagick
15516: context: if 'overwrite', will move the uploaded file from its temporary location to
15517: userfiles to facilitate overwriting a previously uploaded file with same name.
15518: mimetype: reference to scalar to accommodate mime type determined
15519: from File::MMagic if $parser = parse.
15520:
15521: returns either the url of the uploaded file (/uploaded/....) if successful
15522: and /adm/notfound.html if unsuccessful (or an error message if context
15523: was 'overwrite').
15524:
15525:
15526: =item *
15527:
15528: renameuserfile(): renames an existing userfile to a new name
15529:
15530: Args:
15531: docuname: username or courseid of destination for the file
15532: docudom: domain of user/course of destination for the file
15533: old: current file name (including any subdirs under userfiles)
15534: new: desired file name (including any subdirs under userfiles)
15535:
15536: =item *
15537:
15538: mkdiruserfile(): creates a directory is a userfiles dir
15539:
15540: Args:
15541: docuname: username or courseid of destination for the file
15542: docudom: domain of user/course of destination for the file
15543: dir: dir to create (including any subdirs under userfiles)
15544:
15545: =item *
15546:
15547: removeuserfile(): removes a file that exists in userfiles
15548:
15549: Args:
15550: docuname: username or courseid of destination for the file
15551: docudom: domain of user/course of destination for the file
15552: fname: filname to delete (including any subdirs under userfiles)
15553:
15554: =item *
15555:
15556: removeuploadedurl(): convience function for removeuserfile()
15557:
15558: Args:
15559: url: a full /uploaded/... url to delete
15560:
15561: =item *
15562:
15563: get_portfile_permissions():
15564: Args:
15565: domain: domain of user or course contain the portfolio files
15566: user: name of user or num of course contain the portfolio files
15567: Returns:
15568: hashref of a dump of the proper file_permissions.db
15569:
15570:
15571: =item *
15572:
15573: get_access_controls():
15574:
15575: Args:
15576: current_permissions: the hash ref returned from get_portfile_permissions()
15577: group: (optional) the group you want the files associated with
15578: file: (optional) the file you want access info on
15579:
15580: Returns:
15581: a hash (keys are file names) of hashes containing
15582: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
15583: values are XML containing access control settings (see below)
15584:
15585: Internal notes:
15586:
15587: access controls are stored in file_permissions.db as key=value pairs.
15588: key -> path to file/file_name\0uniqueID:scope_end_start
15589: where scope -> public,guest,course,group,domains or users.
15590: end -> UNIX time for end of access (0 -> no end date)
15591: start -> UNIX time for start of access
15592:
15593: value -> XML description of access control
15594: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
15595: <start></start>
15596: <end></end>
15597:
15598: <password></password> for scope type = guest
15599:
15600: <domain></domain> for scope type = course or group
15601: <number></number>
15602: <roles id="">
15603: <role></role>
15604: <access></access>
15605: <section></section>
15606: <group></group>
15607: </roles>
15608:
15609: <dom></dom> for scope type = domains
15610:
15611: <users> for scope type = users
15612: <user>
15613: <uname></uname>
15614: <udom></udom>
15615: </user>
15616: </users>
15617: </scope>
15618:
15619: Access data is also aggregated for each file in an additional key=value pair:
15620: key -> path to file/file_name\0accesscontrol
15621: value -> reference to hash
15622: hash contains key = value pairs
15623: where key = uniqueID:scope_end_start
15624: value = UNIX time record was last updated
15625:
15626: Used to improve speed of look-ups of access controls for each file.
15627:
15628: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
15629:
15630: =item *
15631:
15632: modify_access_controls():
15633:
15634: Modifies access controls for a portfolio file
15635: Args
15636: 1. file name
15637: 2. reference to hash of required changes,
15638: 3. domain
15639: 4. username
15640: where domain,username are the domain of the portfolio owner
15641: (either a user or a course)
15642:
15643: Returns:
15644: 1. result of additions or updates ('ok' or 'error', with error message).
15645: 2. result of deletions ('ok' or 'error', with error message).
15646: 3. reference to hash of any new or updated access controls.
15647: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
15648: key = integer (inbound ID)
15649: value = uniqueID
15650:
15651: =item *
15652:
15653: get_timebased_id():
15654:
15655: Attempts to get a unique timestamp-based suffix for use with items added to a
15656: course via the Course Editor (e.g., folders, composite pages,
15657: group bulletin boards).
15658:
15659: Args: (first three required; six others optional)
15660:
15661: 1. prefix (alphanumeric): of keys in hash, e.g., suppsequence, docspage,
15662: docssequence, or name of group
15663:
15664: 2. keyid (alphanumeric): name of temporary locking key in hash,
15665: e.g., num, boardids
15666:
15667: 3. namespace: name of gdbm file used to store suffixes already assigned;
15668: file will be named nohist_namespace.db
15669:
15670: 4. cdom: domain of course; default is current course domain from %env
15671:
15672: 5. cnum: course number; default is current course number from %env
15673:
15674: 6. idtype: set to concat if an additional digit is to be appended to the
15675: unix timestamp to form the suffix, if the plain timestamp is already
15676: in use. Default is to not do this, but simply increment the unix
15677: timestamp by 1 until a unique key is obtained.
15678:
15679: 7. who: holder of locking key; defaults to user:domain for user.
15680:
15681: 8. locktries: number of attempts to obtain a lock (sleep of 1s before
15682: retrying); default is 3.
15683:
15684: 9. maxtries: number of attempts to obtain a unique suffix; default is 20.
15685:
15686: Returns:
15687:
15688: 1. suffix obtained (numeric)
15689:
15690: 2. result of deleting locking key (ok if deleted, or lock never obtained)
15691:
15692: 3. error: contains (localized) error message if an error occurred.
15693:
15694:
15695: =back
15696:
15697: =head2 HTTP Helper Routines
15698:
15699: =over 4
15700:
15701: =item *
15702:
15703: escape() : unpack non-word characters into CGI-compatible hex codes
15704:
15705: =item *
15706:
15707: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
15708:
15709: =back
15710:
15711: =head1 PRIVATE SUBROUTINES
15712:
15713: =head2 Underlying communication routines (Shouldn't call)
15714:
15715: =over 4
15716:
15717: =item *
15718:
15719: subreply() : tries to pass a message to lonc, returns con_lost if incapable
15720:
15721: =item *
15722:
15723: reply() : uses subreply to send a message to remote machine, logs all failures
15724:
15725: =item *
15726:
15727: critical() : passes a critical message to another server; if cannot
15728: get through then place message in connection buffer directory and
15729: returns con_delayed, if incapable of saving message, returns
15730: con_failed
15731:
15732: =item *
15733:
15734: reconlonc() : tries to reconnect lonc client processes.
15735:
15736: =back
15737:
15738: =head2 Resource Access Logging
15739:
15740: =over 4
15741:
15742: =item *
15743:
15744: flushcourselogs() : flush (save) buffer logs and access logs
15745:
15746: =item *
15747:
15748: courselog($what) : save message for course in hash
15749:
15750: =item *
15751:
15752: courseacclog($what) : save message for course using &courselog(). Perform
15753: special processing for specific resource types (problems, exams, quizzes, etc).
15754:
15755: =item *
15756:
15757: goodbye() : flush course logs and log shutting down; it is called in srm.conf
15758: as a PerlChildExitHandler
15759:
15760: =back
15761:
15762: =head2 Other
15763:
15764: =over 4
15765:
15766: =item *
15767:
15768: symblist($mapname,%newhash) : update symbolic storage links
15769:
15770: =back
15771:
15772: =cut
15773:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>