1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1022 2009/08/23 03:57:20 raeburn Exp $
5: #
6: # Copyright Michigan State University Board of Trustees
7: #
8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
9: #
10: # LON-CAPA is free software; you can redistribute it and/or modify
11: # it under the terms of the GNU General Public License as published by
12: # the Free Software Foundation; either version 2 of the License, or
13: # (at your option) any later version.
14: #
15: # LON-CAPA is distributed in the hope that it will be useful,
16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18: # GNU General Public License for more details.
19: #
20: # You should have received a copy of the GNU General Public License
21: # along with LON-CAPA; if not, write to the Free Software
22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
23: #
24: # /home/httpd/html/adm/gpl.txt
25: #
26: # http://www.lon-capa.org/
27: #
28: ###
29:
30: =pod
31:
32: =head1 NAME
33:
34: Apache::lonnet.pm
35:
36: =head1 SYNOPSIS
37:
38: This file is an interface to the lonc processes of
39: the LON-CAPA network as well as set of elaborated functions for handling information
40: necessary for navigating through a given cluster of LON-CAPA machines within a
41: domain. There are over 40 specialized functions in this module which handle the
42: reading and transmission of metadata, user information (ids, names, environments, roles,
43: logs), file information (storage, reading, directories, extensions, replication, embedded
44: styles and descriptors), educational resources (course descriptions, section names and
45: numbers), url hashing (to assign roles on a url basis), and translating abbreviated symbols to
46: and from more descriptive phrases or explanations.
47:
48: This is part of the LearningOnline Network with CAPA project
49: described at http://www.lon-capa.org.
50:
51: =head1 Package Variables
52:
53: These are largely undocumented, so if you decipher one please note it here.
54:
55: =over 4
56:
57: =item $processmarker
58:
59: Contains the time this process was started and this servers host id.
60:
61: =item $dumpcount
62:
63: Counts the number of times a message log flush has been attempted (regardless
64: of success) by this process. Used as part of the filename when messages are
65: delayed.
66:
67: =back
68:
69: =cut
70:
71: package Apache::lonnet;
72:
73: use strict;
74: use LWP::UserAgent();
75: use HTTP::Date;
76: use Image::Magick;
77:
78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
79: $_64bit %env %protocol);
80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
84: %courseownerbuf, %coursetypebuf,$locknum);
85:
86: use IO::Socket;
87: use GDBM_File;
88: use HTML::LCParser;
89: use Fcntl qw(:flock);
90: use Storable qw(thaw nfreeze);
91: use Time::HiRes qw( gettimeofday tv_interval );
92: use Cache::Memcached;
93: use Digest::MD5;
94: use Math::Random;
95: use LONCAPA qw(:DEFAULT :match);
96: use LONCAPA::Configuration;
97:
98: my $readit;
99: my $max_connection_retries = 10; # Or some such value.
100:
101: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
102:
103: require Exporter;
104:
105: our @ISA = qw (Exporter);
106: our @EXPORT = qw(%env);
107:
108:
109: # --------------------------------------------------------------------- Logging
110: {
111: my $logid;
112: sub instructor_log {
113: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
114: if (($cnum eq '') || ($cdom eq '')) {
115: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
116: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
117: }
118: $logid++;
119: my $now = time();
120: my $id=$now.'00000'.$$.'00000'.$logid;
121: return &Apache::lonnet::put('nohist_'.$hash_name,
122: { $id => {
123: 'exe_uname' => $env{'user.name'},
124: 'exe_udom' => $env{'user.domain'},
125: 'exe_time' => $now,
126: 'exe_ip' => $ENV{'REMOTE_ADDR'},
127: 'delflag' => $delflag,
128: 'logentry' => $storehash,
129: 'uname' => $uname,
130: 'udom' => $udom,
131: }
132: },$cdom,$cnum);
133: }
134: }
135:
136: sub logtouch {
137: my $execdir=$perlvar{'lonDaemons'};
138: unless (-e "$execdir/logs/lonnet.log") {
139: open(my $fh,">>$execdir/logs/lonnet.log");
140: close $fh;
141: }
142: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
143: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
144: }
145:
146: sub logthis {
147: my $message=shift;
148: my $execdir=$perlvar{'lonDaemons'};
149: my $now=time;
150: my $local=localtime($now);
151: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
152: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
153: print $fh $logstring;
154: close($fh);
155: }
156: return 1;
157: }
158:
159: sub logperm {
160: my $message=shift;
161: my $execdir=$perlvar{'lonDaemons'};
162: my $now=time;
163: my $local=localtime($now);
164: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
165: print $fh "$now:$message:$local\n";
166: close($fh);
167: }
168: return 1;
169: }
170:
171: sub create_connection {
172: my ($hostname,$lonid) = @_;
173: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
174: Type => SOCK_STREAM,
175: Timeout => 10);
176: return 0 if (!$client);
177: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
178: my $result = <$client>;
179: chomp($result);
180: return 1 if ($result eq 'done');
181: return 0;
182: }
183:
184: sub get_server_timezone {
185: my ($cnum,$cdom) = @_;
186: my $home=&homeserver($cnum,$cdom);
187: if ($home ne 'no_host') {
188: my $cachetime = 24*3600;
189: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
190: if (defined($cached)) {
191: return $timezone;
192: } else {
193: my $timezone = &reply('servertimezone',$home);
194: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
195: }
196: }
197: }
198:
199: sub get_server_loncaparev {
200: my ($dom,$lonhost) = @_;
201: if (defined($lonhost)) {
202: if (!defined(&hostname($lonhost))) {
203: undef($lonhost);
204: }
205: }
206: if (!defined($lonhost)) {
207: if (defined(&domain($dom,'primary'))) {
208: $lonhost=&domain($dom,'primary');
209: if ($lonhost eq 'no_host') {
210: undef($lonhost);
211: }
212: }
213: }
214: if (defined($lonhost)) {
215: my $cachetime = 24*3600;
216: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
217: if (defined($cached)) {
218: return $loncaparev;
219: } else {
220: my $loncaparev = &reply('serverloncaparev',$lonhost);
221: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
222: }
223: }
224: }
225:
226: # -------------------------------------------------- Non-critical communication
227: sub subreply {
228: my ($cmd,$server)=@_;
229: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
230: #
231: # With loncnew process trimming, there's a timing hole between lonc server
232: # process exit and the master server picking up the listen on the AF_UNIX
233: # socket. In that time interval, a lock file will exist:
234:
235: my $lockfile=$peerfile.".lock";
236: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
237: sleep(1);
238: }
239: # At this point, either a loncnew parent is listening or an old lonc
240: # or loncnew child is listening so we can connect or everything's dead.
241: #
242: # We'll give the connection a few tries before abandoning it. If
243: # connection is not possible, we'll con_lost back to the client.
244: #
245: my $client;
246: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
247: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
248: Type => SOCK_STREAM,
249: Timeout => 10);
250: if ($client) {
251: last; # Connected!
252: } else {
253: &create_connection(&hostname($server),$server);
254: }
255: sleep(1); # Try again later if failed connection.
256: }
257: my $answer;
258: if ($client) {
259: print $client "sethost:$server:$cmd\n";
260: $answer=<$client>;
261: if (!$answer) { $answer="con_lost"; }
262: chomp($answer);
263: } else {
264: $answer = 'con_lost'; # Failed connection.
265: }
266: return $answer;
267: }
268:
269: sub reply {
270: my ($cmd,$server)=@_;
271: unless (defined(&hostname($server))) { return 'no_such_host'; }
272: my $answer=subreply($cmd,$server);
273: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
274: &logthis("<font color=\"blue\">WARNING:".
275: " $cmd to $server returned $answer</font>");
276: }
277: return $answer;
278: }
279:
280: # ----------------------------------------------------------- Send USR1 to lonc
281:
282: sub reconlonc {
283: my ($lonid) = @_;
284: my $hostname = &hostname($lonid);
285: if ($lonid) {
286: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
287: if ($hostname && -e $peerfile) {
288: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
289: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
290: Type => SOCK_STREAM,
291: Timeout => 10);
292: if ($client) {
293: print $client ("reset_retries\n");
294: my $answer=<$client>;
295: #reset just this one.
296: }
297: }
298: return;
299: }
300:
301: &logthis("Trying to reconnect lonc");
302: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
303: if (open(my $fh,"<$loncfile")) {
304: my $loncpid=<$fh>;
305: chomp($loncpid);
306: if (kill 0 => $loncpid) {
307: &logthis("lonc at pid $loncpid responding, sending USR1");
308: kill USR1 => $loncpid;
309: sleep 1;
310: } else {
311: &logthis(
312: "<font color=\"blue\">WARNING:".
313: " lonc at pid $loncpid not responding, giving up</font>");
314: }
315: } else {
316: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
317: }
318: }
319:
320: # ------------------------------------------------------ Critical communication
321:
322: sub critical {
323: my ($cmd,$server)=@_;
324: unless (&hostname($server)) {
325: &logthis("<font color=\"blue\">WARNING:".
326: " Critical message to unknown server ($server)</font>");
327: return 'no_such_host';
328: }
329: my $answer=reply($cmd,$server);
330: if ($answer eq 'con_lost') {
331: &reconlonc("$perlvar{'lonSockDir'}/$server");
332: my $answer=reply($cmd,$server);
333: if ($answer eq 'con_lost') {
334: my $now=time;
335: my $middlename=$cmd;
336: $middlename=substr($middlename,0,16);
337: $middlename=~s/\W//g;
338: my $dfilename=
339: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
340: $dumpcount++;
341: {
342: my $dfh;
343: if (open($dfh,">$dfilename")) {
344: print $dfh "$cmd\n";
345: close($dfh);
346: }
347: }
348: sleep 2;
349: my $wcmd='';
350: {
351: my $dfh;
352: if (open($dfh,"<$dfilename")) {
353: $wcmd=<$dfh>;
354: close($dfh);
355: }
356: }
357: chomp($wcmd);
358: if ($wcmd eq $cmd) {
359: &logthis("<font color=\"blue\">WARNING: ".
360: "Connection buffer $dfilename: $cmd</font>");
361: &logperm("D:$server:$cmd");
362: return 'con_delayed';
363: } else {
364: &logthis("<font color=\"red\">CRITICAL:"
365: ." Critical connection failed: $server $cmd</font>");
366: &logperm("F:$server:$cmd");
367: return 'con_failed';
368: }
369: }
370: }
371: return $answer;
372: }
373:
374: # ------------------------------------------- check if return value is an error
375:
376: sub error {
377: my ($result) = @_;
378: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
379: if ($2 == 2) { return undef; }
380: return $1;
381: }
382: return undef;
383: }
384:
385: sub convert_and_load_session_env {
386: my ($lonidsdir,$handle)=@_;
387: my @profile;
388: {
389: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
390: if (!$opened) {
391: return 0;
392: }
393: flock($idf,LOCK_SH);
394: @profile=<$idf>;
395: close($idf);
396: }
397: my %temp_env;
398: foreach my $line (@profile) {
399: if ($line !~ m/=/) {
400: return 0;
401: }
402: chomp($line);
403: my ($envname,$envvalue)=split(/=/,$line,2);
404: $temp_env{&unescape($envname)} = &unescape($envvalue);
405: }
406: unlink("$lonidsdir/$handle.id");
407: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
408: 0640)) {
409: %disk_env = %temp_env;
410: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
411: untie(%disk_env);
412: }
413: return 1;
414: }
415:
416: # ------------------------------------------- Transfer profile into environment
417: my $env_loaded;
418: sub transfer_profile_to_env {
419: my ($lonidsdir,$handle,$force_transfer) = @_;
420: if (!$force_transfer && $env_loaded) { return; }
421:
422: if (!defined($lonidsdir)) {
423: $lonidsdir = $perlvar{'lonIDsDir'};
424: }
425: if (!defined($handle)) {
426: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
427: }
428:
429: my $convert;
430: {
431: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
432: if (!$opened) {
433: return;
434: }
435: flock($idf,LOCK_SH);
436: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
437: &GDBM_READER(),0640)) {
438: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
439: untie(%disk_env);
440: } else {
441: $convert = 1;
442: }
443: }
444: if ($convert) {
445: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
446: &logthis("Failed to load session, or convert session.");
447: }
448: }
449:
450: my %remove;
451: while ( my $envname = each(%env) ) {
452: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
453: if ($time < time-300) {
454: $remove{$key}++;
455: }
456: }
457: }
458:
459: $env{'user.environment'} = "$lonidsdir/$handle.id";
460: $env_loaded=1;
461: foreach my $expired_key (keys(%remove)) {
462: &delenv($expired_key);
463: }
464: }
465:
466: # ---------------------------------------------------- Check for valid session
467: sub check_for_valid_session {
468: my ($r) = @_;
469: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
470: my $lonid=$cookies{'lonID'};
471: return undef if (!$lonid);
472:
473: my $handle=&LONCAPA::clean_handle($lonid->value);
474: my $lonidsdir=$r->dir_config('lonIDsDir');
475: return undef if (!-e "$lonidsdir/$handle.id");
476:
477: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
478: return undef if (!$opened);
479:
480: flock($idf,LOCK_SH);
481: my %disk_env;
482: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
483: &GDBM_READER(),0640)) {
484: return undef;
485: }
486:
487: if (!defined($disk_env{'user.name'})
488: || !defined($disk_env{'user.domain'})) {
489: return undef;
490: }
491: return $handle;
492: }
493:
494: sub timed_flock {
495: my ($file,$lock_type) = @_;
496: my $failed=0;
497: eval {
498: local $SIG{__DIE__}='DEFAULT';
499: local $SIG{ALRM}=sub {
500: $failed=1;
501: die("failed lock");
502: };
503: alarm(13);
504: flock($file,$lock_type);
505: alarm(0);
506: };
507: if ($failed) {
508: return undef;
509: } else {
510: return 1;
511: }
512: }
513:
514: # ---------------------------------------------------------- Append Environment
515:
516: sub appenv {
517: my ($newenv,$roles) = @_;
518: if (ref($newenv) eq 'HASH') {
519: foreach my $key (keys(%{$newenv})) {
520: my $refused = 0;
521: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
522: $refused = 1;
523: if (ref($roles) eq 'ARRAY') {
524: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
525: if (grep(/^\Q$role\E$/,@{$roles})) {
526: $refused = 0;
527: }
528: }
529: }
530: if ($refused) {
531: &logthis("<font color=\"blue\">WARNING: ".
532: "Attempt to modify environment ".$key." to ".$newenv->{$key}
533: .'</font>');
534: delete($newenv->{$key});
535: } else {
536: $env{$key}=$newenv->{$key};
537: }
538: }
539: my $opened = open(my $env_file,'+<',$env{'user.environment'});
540: if ($opened
541: && &timed_flock($env_file,LOCK_EX)
542: &&
543: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
544: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
545: while (my ($key,$value) = each(%{$newenv})) {
546: $disk_env{$key} = $value;
547: }
548: untie(%disk_env);
549: }
550: }
551: return 'ok';
552: }
553: # ----------------------------------------------------- Delete from Environment
554:
555: sub delenv {
556: my ($delthis,$regexp) = @_;
557: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
558: &logthis("<font color=\"blue\">WARNING: ".
559: "Attempt to delete from environment ".$delthis);
560: return 'error';
561: }
562: my $opened = open(my $env_file,'+<',$env{'user.environment'});
563: if ($opened
564: && &timed_flock($env_file,LOCK_EX)
565: &&
566: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
567: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
568: foreach my $key (keys(%disk_env)) {
569: if ($regexp) {
570: if ($key=~/^$delthis/) {
571: delete($env{$key});
572: delete($disk_env{$key});
573: }
574: } else {
575: if ($key=~/^\Q$delthis\E/) {
576: delete($env{$key});
577: delete($disk_env{$key});
578: }
579: }
580: }
581: untie(%disk_env);
582: }
583: return 'ok';
584: }
585:
586: sub get_env_multiple {
587: my ($name) = @_;
588: my @values;
589: if (defined($env{$name})) {
590: # exists is it an array
591: if (ref($env{$name})) {
592: @values=@{ $env{$name} };
593: } else {
594: $values[0]=$env{$name};
595: }
596: }
597: return(@values);
598: }
599:
600: # ------------------------------------------------------------------- Locking
601:
602: sub set_lock {
603: my ($text)=@_;
604: $locknum++;
605: my $id=$$.'-'.$locknum;
606: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
607: 'session.lock.'.$id => $text});
608: return $id;
609: }
610:
611: sub get_locks {
612: my $num=0;
613: my %texts=();
614: foreach my $lock (split(/\,/,$env{'session.locks'})) {
615: if ($lock=~/\w/) {
616: $num++;
617: $texts{$lock}=$env{'session.lock.'.$lock};
618: }
619: }
620: return ($num,%texts);
621: }
622:
623: sub remove_lock {
624: my ($id)=@_;
625: my $newlocks='';
626: foreach my $lock (split(/\,/,$env{'session.locks'})) {
627: if (($lock=~/\w/) && ($lock ne $id)) {
628: $newlocks.=','.$lock;
629: }
630: }
631: &appenv({'session.locks' => $newlocks});
632: &delenv('session.lock.'.$id);
633: }
634:
635: sub remove_all_locks {
636: my $activelocks=$env{'session.locks'};
637: foreach my $lock (split(/\,/,$env{'session.locks'})) {
638: if ($lock=~/\w/) {
639: &remove_lock($lock);
640: }
641: }
642: }
643:
644:
645: # ------------------------------------------ Find out current server userload
646: sub userload {
647: my $numusers=0;
648: {
649: opendir(LONIDS,$perlvar{'lonIDsDir'});
650: my $filename;
651: my $curtime=time;
652: while ($filename=readdir(LONIDS)) {
653: next if ($filename eq '.' || $filename eq '..');
654: next if ($filename =~ /publicuser_\d+\.id/);
655: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
656: if ($curtime-$mtime < 1800) { $numusers++; }
657: }
658: closedir(LONIDS);
659: }
660: my $userloadpercent=0;
661: my $maxuserload=$perlvar{'lonUserLoadLim'};
662: if ($maxuserload) {
663: $userloadpercent=100*$numusers/$maxuserload;
664: }
665: $userloadpercent=sprintf("%.2f",$userloadpercent);
666: return $userloadpercent;
667: }
668:
669: # ------------------------------------------ Fight off request when overloaded
670:
671: sub overloaderror {
672: my ($r,$checkserver)=@_;
673: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
674: my $loadavg;
675: if ($checkserver eq $perlvar{'lonHostID'}) {
676: open(my $loadfile,'/proc/loadavg');
677: $loadavg=<$loadfile>;
678: $loadavg =~ s/\s.*//g;
679: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
680: close($loadfile);
681: } else {
682: $loadavg=&reply('load',$checkserver);
683: }
684: my $overload=$loadavg-100;
685: if ($overload>0) {
686: $r->err_headers_out->{'Retry-After'}=$overload;
687: $r->log_error('Overload of '.$overload.' on '.$checkserver);
688: return 413;
689: }
690: return '';
691: }
692:
693: # ------------------------------ Find server with least workload from spare.tab
694:
695: sub spareserver {
696: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
697: my $spare_server;
698: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
699: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
700: : $userloadpercent;
701:
702: foreach my $try_server (@{ $spareid{'primary'} }) {
703: ($spare_server, $lowest_load) =
704: &compare_server_load($try_server, $spare_server, $lowest_load);
705: }
706:
707: my $found_server = ($spare_server ne '' && $lowest_load < 100);
708:
709: if (!$found_server) {
710: foreach my $try_server (@{ $spareid{'default'} }) {
711: ($spare_server, $lowest_load) =
712: &compare_server_load($try_server, $spare_server, $lowest_load);
713: }
714: }
715:
716: if (!$want_server_name) {
717: my $protocol = 'http';
718: if ($protocol{$spare_server} eq 'https') {
719: $protocol = $protocol{$spare_server};
720: }
721: if (defined($spare_server)) {
722: my $hostname = &hostname($spare_server);
723: if (defined($hostname)) {
724: $spare_server = $protocol.'://'.$hostname;
725: }
726: }
727: }
728: return $spare_server;
729: }
730:
731: sub compare_server_load {
732: my ($try_server, $spare_server, $lowest_load) = @_;
733:
734: my $loadans = &reply('load', $try_server);
735: my $userloadans = &reply('userload',$try_server);
736:
737: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
738: next; #didn't get a number from the server
739: }
740:
741: my $load;
742: if ($loadans =~ /\d/) {
743: if ($userloadans =~ /\d/) {
744: #both are numbers, pick the bigger one
745: $load = ($loadans > $userloadans) ? $loadans
746: : $userloadans;
747: } else {
748: $load = $loadans;
749: }
750: } else {
751: $load = $userloadans;
752: }
753:
754: if (($load =~ /\d/) && ($load < $lowest_load)) {
755: $spare_server = $try_server;
756: $lowest_load = $load;
757: }
758: return ($spare_server,$lowest_load);
759: }
760:
761: # --------------------------- ask offload servers if user already has a session
762: sub find_existing_session {
763: my ($udom,$uname) = @_;
764: foreach my $try_server (@{ $spareid{'primary'} },
765: @{ $spareid{'default'} }) {
766: return $try_server if (&has_user_session($try_server, $udom, $uname));
767: }
768: return;
769: }
770:
771: # -------------------------------- ask if server already has a session for user
772: sub has_user_session {
773: my ($lonid,$udom,$uname) = @_;
774: my $result = &reply(join(':','userhassession',
775: map {&escape($_)} ($udom,$uname)),$lonid);
776: return 1 if ($result eq 'ok');
777:
778: return 0;
779: }
780:
781: # --------------------------------------------- Try to change a user's password
782:
783: sub changepass {
784: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
785: $currentpass = &escape($currentpass);
786: $newpass = &escape($newpass);
787: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
788: $server);
789: if (! $answer) {
790: &logthis("No reply on password change request to $server ".
791: "by $uname in domain $udom.");
792: } elsif ($answer =~ "^ok") {
793: &logthis("$uname in $udom successfully changed their password ".
794: "on $server.");
795: } elsif ($answer =~ "^pwchange_failure") {
796: &logthis("$uname in $udom was unable to change their password ".
797: "on $server. The action was blocked by either lcpasswd ".
798: "or pwchange");
799: } elsif ($answer =~ "^non_authorized") {
800: &logthis("$uname in $udom did not get their password correct when ".
801: "attempting to change it on $server.");
802: } elsif ($answer =~ "^auth_mode_error") {
803: &logthis("$uname in $udom attempted to change their password despite ".
804: "not being locally or internally authenticated on $server.");
805: } elsif ($answer =~ "^unknown_user") {
806: &logthis("$uname in $udom attempted to change their password ".
807: "on $server but were unable to because $server is not ".
808: "their home server.");
809: } elsif ($answer =~ "^refused") {
810: &logthis("$server refused to change $uname in $udom password because ".
811: "it was sent an unencrypted request to change the password.");
812: }
813: return $answer;
814: }
815:
816: # ----------------------- Try to determine user's current authentication scheme
817:
818: sub queryauthenticate {
819: my ($uname,$udom)=@_;
820: my $uhome=&homeserver($uname,$udom);
821: if (!$uhome) {
822: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
823: return 'no_host';
824: }
825: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
826: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
827: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
828: }
829: return $answer;
830: }
831:
832: # --------- Try to authenticate user from domain's lib servers (first this one)
833:
834: sub authenticate {
835: my ($uname,$upass,$udom,$checkdefauth)=@_;
836: $upass=&escape($upass);
837: $uname= &LONCAPA::clean_username($uname);
838: my $uhome=&homeserver($uname,$udom,1);
839: my $newhome;
840: if ((!$uhome) || ($uhome eq 'no_host')) {
841: # Maybe the machine was offline and only re-appeared again recently?
842: &reconlonc();
843: # One more
844: $uhome=&homeserver($uname,$udom,1);
845: if (($uhome eq 'no_host') && $checkdefauth) {
846: if (defined(&domain($udom,'primary'))) {
847: $newhome=&domain($udom,'primary');
848: }
849: if ($newhome ne '') {
850: $uhome = $newhome;
851: }
852: }
853: if ((!$uhome) || ($uhome eq 'no_host')) {
854: &logthis("User $uname at $udom is unknown in authenticate");
855: return 'no_host';
856: }
857: }
858: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
859: if ($answer eq 'authorized') {
860: if ($newhome) {
861: &logthis("User $uname at $udom authorized by $uhome, but needs account");
862: return 'no_account_on_host';
863: } else {
864: &logthis("User $uname at $udom authorized by $uhome");
865: return $uhome;
866: }
867: }
868: if ($answer eq 'non_authorized') {
869: &logthis("User $uname at $udom rejected by $uhome");
870: return 'no_host';
871: }
872: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
873: return 'no_host';
874: }
875:
876: # ---------------------- Find the homebase for a user from domain's lib servers
877:
878: my %homecache;
879: sub homeserver {
880: my ($uname,$udom,$ignoreBadCache)=@_;
881: my $index="$uname:$udom";
882:
883: if (exists($homecache{$index})) { return $homecache{$index}; }
884:
885: my %servers = &get_servers($udom,'library');
886: foreach my $tryserver (keys(%servers)) {
887: next if ($ignoreBadCache ne 'true' &&
888: exists($badServerCache{$tryserver}));
889:
890: my $answer=reply("home:$udom:$uname",$tryserver);
891: if ($answer eq 'found') {
892: delete($badServerCache{$tryserver});
893: return $homecache{$index}=$tryserver;
894: } elsif ($answer eq 'no_host') {
895: $badServerCache{$tryserver}=1;
896: }
897: }
898: return 'no_host';
899: }
900:
901: # ------------------------------------- Find the usernames behind a list of IDs
902:
903: sub idget {
904: my ($udom,@ids)=@_;
905: my %returnhash=();
906:
907: my %servers = &get_servers($udom,'library');
908: foreach my $tryserver (keys(%servers)) {
909: my $idlist=join('&',@ids);
910: $idlist=~tr/A-Z/a-z/;
911: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
912: my @answer=();
913: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
914: @answer=split(/\&/,$reply);
915: } ;
916: my $i;
917: for ($i=0;$i<=$#ids;$i++) {
918: if ($answer[$i]) {
919: $returnhash{$ids[$i]}=$answer[$i];
920: }
921: }
922: }
923: return %returnhash;
924: }
925:
926: # ------------------------------------- Find the IDs behind a list of usernames
927:
928: sub idrget {
929: my ($udom,@unames)=@_;
930: my %returnhash=();
931: foreach my $uname (@unames) {
932: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
933: }
934: return %returnhash;
935: }
936:
937: # ------------------------------- Store away a list of names and associated IDs
938:
939: sub idput {
940: my ($udom,%ids)=@_;
941: my %servers=();
942: foreach my $uname (keys(%ids)) {
943: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
944: my $uhom=&homeserver($uname,$udom);
945: if ($uhom ne 'no_host') {
946: my $id=&escape($ids{$uname});
947: $id=~tr/A-Z/a-z/;
948: my $esc_unam=&escape($uname);
949: if ($servers{$uhom}) {
950: $servers{$uhom}.='&'.$id.'='.$esc_unam;
951: } else {
952: $servers{$uhom}=$id.'='.$esc_unam;
953: }
954: }
955: }
956: foreach my $server (keys(%servers)) {
957: &critical('idput:'.$udom.':'.$servers{$server},$server);
958: }
959: }
960:
961: # ------------------------------------------------ dump from domain db files
962:
963: sub dump_dom {
964: my ($namespace,$udom,$uhome,$regexp,$range)=@_;
965: if (!$udom) {
966: $udom=$env{'user.domain'};
967: if (defined(&domain($udom,'primary'))) {
968: $uhome=&domain($udom,'primary');
969: } else {
970: undef($uhome);
971: }
972: } else {
973: if (!$uhome) {
974: if (defined(&domain($udom,'primary'))) {
975: $uhome=&domain($udom,'primary');
976: }
977: }
978: }
979: my %returnhash;
980: if ($udom && $uhome && ($uhome ne 'no_host')) {
981: if ($regexp) {
982: $regexp=&escape($regexp);
983: } else {
984: $regexp='.';
985: }
986: my $rep=&reply("dumpdom:$udom:$namespace:$regexp:$range",$uhome);
987: my @pairs=split(/\&/,$rep);
988: foreach my $item (@pairs) {
989: my ($key,$value)=split(/=/,$item,2);
990: $key = &unescape($key);
991: next if ($key =~ /^error: 2 /);
992: $returnhash{$key}=&thaw_unescape($value);
993: }
994: }
995: return %returnhash;
996: }
997:
998: # ------------------------------------------- get items from domain db files
999:
1000: sub get_dom {
1001: my ($namespace,$storearr,$udom,$uhome)=@_;
1002: my $items='';
1003: foreach my $item (@$storearr) {
1004: $items.=&escape($item).'&';
1005: }
1006: $items=~s/\&$//;
1007: if (!$udom) {
1008: $udom=$env{'user.domain'};
1009: if (defined(&domain($udom,'primary'))) {
1010: $uhome=&domain($udom,'primary');
1011: } else {
1012: undef($uhome);
1013: }
1014: } else {
1015: if (!$uhome) {
1016: if (defined(&domain($udom,'primary'))) {
1017: $uhome=&domain($udom,'primary');
1018: }
1019: }
1020: }
1021: if ($udom && $uhome && ($uhome ne 'no_host')) {
1022: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1023: my %returnhash;
1024: if ($rep eq '' || $rep =~ /^error: 2 /) {
1025: return %returnhash;
1026: }
1027: my @pairs=split(/\&/,$rep);
1028: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1029: return @pairs;
1030: }
1031: my $i=0;
1032: foreach my $item (@$storearr) {
1033: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1034: $i++;
1035: }
1036: return %returnhash;
1037: } else {
1038: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1039: }
1040: }
1041:
1042: # -------------------------------------------- put items in domain db files
1043:
1044: sub put_dom {
1045: my ($namespace,$storehash,$udom,$uhome)=@_;
1046: if (!$udom) {
1047: $udom=$env{'user.domain'};
1048: if (defined(&domain($udom,'primary'))) {
1049: $uhome=&domain($udom,'primary');
1050: } else {
1051: undef($uhome);
1052: }
1053: } else {
1054: if (!$uhome) {
1055: if (defined(&domain($udom,'primary'))) {
1056: $uhome=&domain($udom,'primary');
1057: }
1058: }
1059: }
1060: if ($udom && $uhome && ($uhome ne 'no_host')) {
1061: my $items='';
1062: foreach my $item (keys(%$storehash)) {
1063: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1064: }
1065: $items=~s/\&$//;
1066: return &reply("putdom:$udom:$namespace:$items",$uhome);
1067: } else {
1068: &logthis("put_dom failed - no homeserver and/or domain");
1069: }
1070: }
1071:
1072: # -------------------------------------- newput for items in domain db files
1073:
1074: sub newput_dom {
1075: my ($namespace,$storehash,$udom,$uhome) = @_;
1076: my $result;
1077: if (!$udom) {
1078: $udom=$env{'user.domain'};
1079: if (defined(&domain($udom,'primary'))) {
1080: $uhome=&domain($udom,'primary');
1081: } else {
1082: undef($uhome);
1083: }
1084: } else {
1085: if (!$uhome) {
1086: if (defined(&domain($udom,'primary'))) {
1087: $uhome=&domain($udom,'primary');
1088: }
1089: }
1090: }
1091: if ($udom && $uhome && ($uhome ne 'no_host')) {
1092: my $items='';
1093: if (ref($storehash) eq 'HASH') {
1094: foreach my $key (keys(%$storehash)) {
1095: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1096: }
1097: $items=~s/\&$//;
1098: $result = &reply("newputdom:$udom:$namespace:$items",$uhome);
1099: }
1100: } else {
1101: &logthis("put_dom failed - no homeserver and/or domain");
1102: }
1103: return $result;
1104: }
1105:
1106: sub del_dom {
1107: my ($namespace,$storearr,$udom,$uhome)=@_;
1108: if (ref($storearr) eq 'ARRAY') {
1109: my $items='';
1110: foreach my $item (@$storearr) {
1111: $items.=&escape($item).'&';
1112: }
1113: $items=~s/\&$//;
1114: if (!$udom) {
1115: $udom=$env{'user.domain'};
1116: if (defined(&domain($udom,'primary'))) {
1117: $uhome=&domain($udom,'primary');
1118: } else {
1119: undef($uhome);
1120: }
1121: } else {
1122: if (!$uhome) {
1123: if (defined(&domain($udom,'primary'))) {
1124: $uhome=&domain($udom,'primary');
1125: }
1126: }
1127: }
1128: if ($udom && $uhome && ($uhome ne 'no_host')) {
1129: return &reply("deldom:$udom:$namespace:$items",$uhome);
1130: } else {
1131: &logthis("del_dom failed - no homeserver and/or domain");
1132: }
1133: }
1134: }
1135:
1136: sub retrieve_inst_usertypes {
1137: my ($udom) = @_;
1138: my (%returnhash,@order);
1139: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1140: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1141: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1142: %returnhash = %{$domdefs{'inststatustypes'}};
1143: @order = @{$domdefs{'inststatusorder'}};
1144: } else {
1145: if (defined(&domain($udom,'primary'))) {
1146: my $uhome=&domain($udom,'primary');
1147: my $rep=&reply("inst_usertypes:$udom",$uhome);
1148: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1149: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1150: return (\%returnhash,\@order);
1151: }
1152: my ($hashitems,$orderitems) = split(/:/,$rep);
1153: my @pairs=split(/\&/,$hashitems);
1154: foreach my $item (@pairs) {
1155: my ($key,$value)=split(/=/,$item,2);
1156: $key = &unescape($key);
1157: next if ($key =~ /^error: 2 /);
1158: $returnhash{$key}=&thaw_unescape($value);
1159: }
1160: my @esc_order = split(/\&/,$orderitems);
1161: foreach my $item (@esc_order) {
1162: push(@order,&unescape($item));
1163: }
1164: } else {
1165: &logthis("get_dom failed - no primary domain server for $udom");
1166: }
1167: }
1168: return (\%returnhash,\@order);
1169: }
1170:
1171: sub is_domainimage {
1172: my ($url) = @_;
1173: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1174: if (&domain($1) ne '') {
1175: return '1';
1176: }
1177: }
1178: return;
1179: }
1180:
1181: sub inst_directory_query {
1182: my ($srch) = @_;
1183: my $udom = $srch->{'srchdomain'};
1184: my %results;
1185: my $homeserver = &domain($udom,'primary');
1186: my $outcome;
1187: if ($homeserver ne '') {
1188: my $queryid=&reply("querysend:instdirsearch:".
1189: &escape($srch->{'srchby'}).':'.
1190: &escape($srch->{'srchterm'}).':'.
1191: &escape($srch->{'srchtype'}),$homeserver);
1192: my $host=&hostname($homeserver);
1193: if ($queryid !~/^\Q$host\E\_/) {
1194: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1195: return;
1196: }
1197: my $response = &get_query_reply($queryid);
1198: my $maxtries = 5;
1199: my $tries = 1;
1200: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1201: $response = &get_query_reply($queryid);
1202: $tries ++;
1203: }
1204:
1205: if (!&error($response) && $response ne 'refused') {
1206: if ($response eq 'unavailable') {
1207: $outcome = $response;
1208: } else {
1209: $outcome = 'ok';
1210: my @matches = split(/\n/,$response);
1211: foreach my $match (@matches) {
1212: my ($key,$value) = split(/=/,$match);
1213: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1214: }
1215: }
1216: }
1217: }
1218: return ($outcome,%results);
1219: }
1220:
1221: sub usersearch {
1222: my ($srch) = @_;
1223: my $dom = $srch->{'srchdomain'};
1224: my %results;
1225: my %libserv = &all_library();
1226: my $query = 'usersearch';
1227: foreach my $tryserver (keys(%libserv)) {
1228: if (&host_domain($tryserver) eq $dom) {
1229: my $host=&hostname($tryserver);
1230: my $queryid=
1231: &reply("querysend:".&escape($query).':'.
1232: &escape($srch->{'srchby'}).':'.
1233: &escape($srch->{'srchtype'}).':'.
1234: &escape($srch->{'srchterm'}),$tryserver);
1235: if ($queryid !~/^\Q$host\E\_/) {
1236: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1237: next;
1238: }
1239: my $reply = &get_query_reply($queryid);
1240: my $maxtries = 1;
1241: my $tries = 1;
1242: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1243: $reply = &get_query_reply($queryid);
1244: $tries ++;
1245: }
1246: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1247: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1248: } else {
1249: my @matches;
1250: if ($reply =~ /\n/) {
1251: @matches = split(/\n/,$reply);
1252: } else {
1253: @matches = split(/\&/,$reply);
1254: }
1255: foreach my $match (@matches) {
1256: my ($uname,$udom,%userhash);
1257: foreach my $entry (split(/:/,$match)) {
1258: my ($key,$value) =
1259: map {&unescape($_);} split(/=/,$entry);
1260: $userhash{$key} = $value;
1261: if ($key eq 'username') {
1262: $uname = $value;
1263: } elsif ($key eq 'domain') {
1264: $udom = $value;
1265: }
1266: }
1267: $results{$uname.':'.$udom} = \%userhash;
1268: }
1269: }
1270: }
1271: }
1272: return %results;
1273: }
1274:
1275: sub get_instuser {
1276: my ($udom,$uname,$id) = @_;
1277: my $homeserver = &domain($udom,'primary');
1278: my ($outcome,%results);
1279: if ($homeserver ne '') {
1280: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1281: &escape($id).':'.&escape($udom),$homeserver);
1282: my $host=&hostname($homeserver);
1283: if ($queryid !~/^\Q$host\E\_/) {
1284: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1285: return;
1286: }
1287: my $response = &get_query_reply($queryid);
1288: my $maxtries = 5;
1289: my $tries = 1;
1290: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1291: $response = &get_query_reply($queryid);
1292: $tries ++;
1293: }
1294: if (!&error($response) && $response ne 'refused') {
1295: if ($response eq 'unavailable') {
1296: $outcome = $response;
1297: } else {
1298: $outcome = 'ok';
1299: my @matches = split(/\n/,$response);
1300: foreach my $match (@matches) {
1301: my ($key,$value) = split(/=/,$match);
1302: $results{&unescape($key)} = &thaw_unescape($value);
1303: }
1304: }
1305: }
1306: }
1307: my %userinfo;
1308: if (ref($results{$uname}) eq 'HASH') {
1309: %userinfo = %{$results{$uname}};
1310: }
1311: return ($outcome,%userinfo);
1312: }
1313:
1314: sub inst_rulecheck {
1315: my ($udom,$uname,$id,$item,$rules) = @_;
1316: my %returnhash;
1317: if ($udom ne '') {
1318: if (ref($rules) eq 'ARRAY') {
1319: @{$rules} = map {&escape($_);} (@{$rules});
1320: my $rulestr = join(':',@{$rules});
1321: my $homeserver=&domain($udom,'primary');
1322: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1323: my $response;
1324: if ($item eq 'username') {
1325: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1326: ':'.&escape($uname).':'.$rulestr,
1327: $homeserver));
1328: } elsif ($item eq 'id') {
1329: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1330: ':'.&escape($id).':'.$rulestr,
1331: $homeserver));
1332: } elsif ($item eq 'selfcreate') {
1333: $response=&unescape(&reply('instselfcreatecheck:'.
1334: &escape($udom).':'.&escape($uname).
1335: ':'.$rulestr,$homeserver));
1336: }
1337: if ($response ne 'refused') {
1338: my @pairs=split(/\&/,$response);
1339: foreach my $item (@pairs) {
1340: my ($key,$value)=split(/=/,$item,2);
1341: $key = &unescape($key);
1342: next if ($key =~ /^error: 2 /);
1343: $returnhash{$key}=&thaw_unescape($value);
1344: }
1345: }
1346: }
1347: }
1348: }
1349: return %returnhash;
1350: }
1351:
1352: sub inst_userrules {
1353: my ($udom,$check) = @_;
1354: my (%ruleshash,@ruleorder);
1355: if ($udom ne '') {
1356: my $homeserver=&domain($udom,'primary');
1357: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1358: my $response;
1359: if ($check eq 'id') {
1360: $response=&reply('instidrules:'.&escape($udom),
1361: $homeserver);
1362: } elsif ($check eq 'email') {
1363: $response=&reply('instemailrules:'.&escape($udom),
1364: $homeserver);
1365: } else {
1366: $response=&reply('instuserrules:'.&escape($udom),
1367: $homeserver);
1368: }
1369: if (($response ne 'refused') && ($response ne 'error') &&
1370: ($response ne 'unknown_cmd') &&
1371: ($response ne 'no_such_host')) {
1372: my ($hashitems,$orderitems) = split(/:/,$response);
1373: my @pairs=split(/\&/,$hashitems);
1374: foreach my $item (@pairs) {
1375: my ($key,$value)=split(/=/,$item,2);
1376: $key = &unescape($key);
1377: next if ($key =~ /^error: 2 /);
1378: $ruleshash{$key}=&thaw_unescape($value);
1379: }
1380: my @esc_order = split(/\&/,$orderitems);
1381: foreach my $item (@esc_order) {
1382: push(@ruleorder,&unescape($item));
1383: }
1384: }
1385: }
1386: }
1387: return (\%ruleshash,\@ruleorder);
1388: }
1389:
1390: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1391:
1392: sub get_domain_defaults {
1393: my ($domain) = @_;
1394: my $cachetime = 60*60*24;
1395: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1396: if (defined($cached)) {
1397: if (ref($result) eq 'HASH') {
1398: return %{$result};
1399: }
1400: }
1401: my %domdefaults;
1402: my %domconfig =
1403: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1404: 'requestcourses','inststatus'],$domain);
1405: if (ref($domconfig{'defaults'}) eq 'HASH') {
1406: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1407: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1408: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1409: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1410: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1411: } else {
1412: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1413: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1414: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1415: }
1416: if (ref($domconfig{'quotas'}) eq 'HASH') {
1417: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1418: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1419: } else {
1420: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1421: }
1422: my @usertools = ('aboutme','blog','portfolio');
1423: foreach my $item (@usertools) {
1424: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1425: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1426: }
1427: }
1428: }
1429: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1430: foreach my $item ('official','unofficial','community') {
1431: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1432: }
1433: }
1434: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1435: foreach my $item ('inststatustypes','inststatusorder') {
1436: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1437: }
1438: }
1439: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1440: $cachetime);
1441: return %domdefaults;
1442: }
1443:
1444: # --------------------------------------------------- Assign a key to a student
1445:
1446: sub assign_access_key {
1447: #
1448: # a valid key looks like uname:udom#comments
1449: # comments are being appended
1450: #
1451: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1452: $kdom=
1453: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1454: $knum=
1455: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1456: $cdom=
1457: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1458: $cnum=
1459: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1460: $udom=$env{'user.name'} unless (defined($udom));
1461: $uname=$env{'user.domain'} unless (defined($uname));
1462: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1463: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1464: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1465: # assigned to this person
1466: # - this should not happen,
1467: # unless something went wrong
1468: # the first time around
1469: # ready to assign
1470: $logentry=$1.'; '.$logentry;
1471: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1472: $kdom,$knum) eq 'ok') {
1473: # key now belongs to user
1474: my $envkey='key.'.$cdom.'_'.$cnum;
1475: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1476: &appenv({'environment.'.$envkey => $ckey});
1477: return 'ok';
1478: } else {
1479: return
1480: 'error: Count not permanently assign key, will need to be re-entered later.';
1481: }
1482: } else {
1483: return 'error: Could not assign key, try again later.';
1484: }
1485: } elsif (!$existing{$ckey}) {
1486: # the key does not exist
1487: return 'error: The key does not exist';
1488: } else {
1489: # the key is somebody else's
1490: return 'error: The key is already in use';
1491: }
1492: }
1493:
1494: # ------------------------------------------ put an additional comment on a key
1495:
1496: sub comment_access_key {
1497: #
1498: # a valid key looks like uname:udom#comments
1499: # comments are being appended
1500: #
1501: my ($ckey,$cdom,$cnum,$logentry)=@_;
1502: $cdom=
1503: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1504: $cnum=
1505: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1506: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1507: if ($existing{$ckey}) {
1508: $existing{$ckey}.='; '.$logentry;
1509: # ready to assign
1510: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1511: $cdom,$cnum) eq 'ok') {
1512: return 'ok';
1513: } else {
1514: return 'error: Count not store comment.';
1515: }
1516: } else {
1517: # the key does not exist
1518: return 'error: The key does not exist';
1519: }
1520: }
1521:
1522: # ------------------------------------------------------ Generate a set of keys
1523:
1524: sub generate_access_keys {
1525: my ($number,$cdom,$cnum,$logentry)=@_;
1526: $cdom=
1527: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1528: $cnum=
1529: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1530: unless (&allowed('mky',$cdom)) { return 0; }
1531: unless (($cdom) && ($cnum)) { return 0; }
1532: if ($number>10000) { return 0; }
1533: sleep(2); # make sure don't get same seed twice
1534: srand(time()^($$+($$<<15))); # from "Programming Perl"
1535: my $total=0;
1536: for (my $i=1;$i<=$number;$i++) {
1537: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1538: sprintf("%lx",int(100000*rand)).'-'.
1539: sprintf("%lx",int(100000*rand));
1540: $newkey=~s/1/g/g; # folks mix up 1 and l
1541: $newkey=~s/0/h/g; # and also 0 and O
1542: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1543: if ($existing{$newkey}) {
1544: $i--;
1545: } else {
1546: if (&put('accesskeys',
1547: { $newkey => '# generated '.localtime().
1548: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1549: '; '.$logentry },
1550: $cdom,$cnum) eq 'ok') {
1551: $total++;
1552: }
1553: }
1554: }
1555: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1556: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1557: return $total;
1558: }
1559:
1560: # ------------------------------------------------------- Validate an accesskey
1561:
1562: sub validate_access_key {
1563: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1564: $cdom=
1565: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1566: $cnum=
1567: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1568: $udom=$env{'user.domain'} unless (defined($udom));
1569: $uname=$env{'user.name'} unless (defined($uname));
1570: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1571: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1572: }
1573:
1574: # ------------------------------------- Find the section of student in a course
1575: sub devalidate_getsection_cache {
1576: my ($udom,$unam,$courseid)=@_;
1577: my $hashid="$udom:$unam:$courseid";
1578: &devalidate_cache_new('getsection',$hashid);
1579: }
1580:
1581: sub courseid_to_courseurl {
1582: my ($courseid) = @_;
1583: #already url style courseid
1584: return $courseid if ($courseid =~ m{^/});
1585:
1586: if (exists($env{'course.'.$courseid.'.num'})) {
1587: my $cnum = $env{'course.'.$courseid.'.num'};
1588: my $cdom = $env{'course.'.$courseid.'.domain'};
1589: return "/$cdom/$cnum";
1590: }
1591:
1592: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1593: if (exists($courseinfo{'num'})) {
1594: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1595: }
1596:
1597: return undef;
1598: }
1599:
1600: sub getsection {
1601: my ($udom,$unam,$courseid)=@_;
1602: my $cachetime=1800;
1603:
1604: my $hashid="$udom:$unam:$courseid";
1605: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1606: if (defined($cached)) { return $result; }
1607:
1608: my %Pending;
1609: my %Expired;
1610: #
1611: # Each role can either have not started yet (pending), be active,
1612: # or have expired.
1613: #
1614: # If there is an active role, we are done.
1615: #
1616: # If there is more than one role which has not started yet,
1617: # choose the one which will start sooner
1618: # If there is one role which has not started yet, return it.
1619: #
1620: # If there is more than one expired role, choose the one which ended last.
1621: # If there is a role which has expired, return it.
1622: #
1623: $courseid = &courseid_to_courseurl($courseid);
1624: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1625: foreach my $key (keys(%roleshash)) {
1626: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1627: my $section=$1;
1628: if ($key eq $courseid.'_st') { $section=''; }
1629: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1630: my $now=time;
1631: if (defined($end) && $end && ($now > $end)) {
1632: $Expired{$end}=$section;
1633: next;
1634: }
1635: if (defined($start) && $start && ($now < $start)) {
1636: $Pending{$start}=$section;
1637: next;
1638: }
1639: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1640: }
1641: #
1642: # Presumedly there will be few matching roles from the above
1643: # loop and the sorting time will be negligible.
1644: if (scalar(keys(%Pending))) {
1645: my ($time) = sort {$a <=> $b} keys(%Pending);
1646: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1647: }
1648: if (scalar(keys(%Expired))) {
1649: my @sorted = sort {$a <=> $b} keys(%Expired);
1650: my $time = pop(@sorted);
1651: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1652: }
1653: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1654: }
1655:
1656: sub save_cache {
1657: &purge_remembered();
1658: #&Apache::loncommon::validate_page();
1659: undef(%env);
1660: undef($env_loaded);
1661: }
1662:
1663: my $to_remember=-1;
1664: my %remembered;
1665: my %accessed;
1666: my $kicks=0;
1667: my $hits=0;
1668: sub make_key {
1669: my ($name,$id) = @_;
1670: if (length($id) > 65
1671: && length(&escape($id)) > 200) {
1672: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1673: }
1674: return &escape($name.':'.$id);
1675: }
1676:
1677: sub devalidate_cache_new {
1678: my ($name,$id,$debug) = @_;
1679: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1680: $id=&make_key($name,$id);
1681: $memcache->delete($id);
1682: delete($remembered{$id});
1683: delete($accessed{$id});
1684: }
1685:
1686: sub is_cached_new {
1687: my ($name,$id,$debug) = @_;
1688: $id=&make_key($name,$id);
1689: if (exists($remembered{$id})) {
1690: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1691: $accessed{$id}=[&gettimeofday()];
1692: $hits++;
1693: return ($remembered{$id},1);
1694: }
1695: my $value = $memcache->get($id);
1696: if (!(defined($value))) {
1697: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1698: return (undef,undef);
1699: }
1700: if ($value eq '__undef__') {
1701: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1702: $value=undef;
1703: }
1704: &make_room($id,$value,$debug);
1705: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1706: return ($value,1);
1707: }
1708:
1709: sub do_cache_new {
1710: my ($name,$id,$value,$time,$debug) = @_;
1711: $id=&make_key($name,$id);
1712: my $setvalue=$value;
1713: if (!defined($setvalue)) {
1714: $setvalue='__undef__';
1715: }
1716: if (!defined($time) ) {
1717: $time=600;
1718: }
1719: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1720: my $result = $memcache->set($id,$setvalue,$time);
1721: if (! $result) {
1722: &logthis("caching of id -> $id failed");
1723: $memcache->disconnect_all();
1724: }
1725: # need to make a copy of $value
1726: &make_room($id,$value,$debug);
1727: return $value;
1728: }
1729:
1730: sub make_room {
1731: my ($id,$value,$debug)=@_;
1732:
1733: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1734: : $value;
1735: if ($to_remember<0) { return; }
1736: $accessed{$id}=[&gettimeofday()];
1737: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1738: my $to_kick;
1739: my $max_time=0;
1740: foreach my $other (keys(%accessed)) {
1741: if (&tv_interval($accessed{$other}) > $max_time) {
1742: $to_kick=$other;
1743: $max_time=&tv_interval($accessed{$other});
1744: }
1745: }
1746: delete($remembered{$to_kick});
1747: delete($accessed{$to_kick});
1748: $kicks++;
1749: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1750: return;
1751: }
1752:
1753: sub purge_remembered {
1754: #&logthis("Tossing ".scalar(keys(%remembered)));
1755: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1756: undef(%remembered);
1757: undef(%accessed);
1758: }
1759: # ------------------------------------- Read an entry from a user's environment
1760:
1761: sub userenvironment {
1762: my ($udom,$unam,@what)=@_;
1763: my $items;
1764: foreach my $item (@what) {
1765: $items.=&escape($item).'&';
1766: }
1767: $items=~s/\&$//;
1768: my %returnhash=();
1769: my $uhome = &homeserver($unam,$udom);
1770: unless ($uhome eq 'no_host') {
1771: my @answer=split(/\&/,
1772: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1773: my $i;
1774: for ($i=0;$i<=$#what;$i++) {
1775: $returnhash{$what[$i]}=&unescape($answer[$i]);
1776: }
1777: }
1778: return %returnhash;
1779: }
1780:
1781: # ---------------------------------------------------------- Get a studentphoto
1782: sub studentphoto {
1783: my ($udom,$unam,$ext) = @_;
1784: my $home=&Apache::lonnet::homeserver($unam,$udom);
1785: if (defined($env{'request.course.id'})) {
1786: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1787: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1788: return(&retrievestudentphoto($udom,$unam,$ext));
1789: } else {
1790: my ($result,$perm_reqd)=
1791: &Apache::lonnet::auto_photo_permission($unam,$udom);
1792: if ($result eq 'ok') {
1793: if (!($perm_reqd eq 'yes')) {
1794: return(&retrievestudentphoto($udom,$unam,$ext));
1795: }
1796: }
1797: }
1798: }
1799: } else {
1800: my ($result,$perm_reqd) =
1801: &Apache::lonnet::auto_photo_permission($unam,$udom);
1802: if ($result eq 'ok') {
1803: if (!($perm_reqd eq 'yes')) {
1804: return(&retrievestudentphoto($udom,$unam,$ext));
1805: }
1806: }
1807: }
1808: return '/adm/lonKaputt/lonlogo_broken.gif';
1809: }
1810:
1811: sub retrievestudentphoto {
1812: my ($udom,$unam,$ext,$type) = @_;
1813: my $home=&Apache::lonnet::homeserver($unam,$udom);
1814: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1815: if ($ret eq 'ok') {
1816: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1817: if ($type eq 'thumbnail') {
1818: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1819: }
1820: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1821: return $tokenurl;
1822: } else {
1823: if ($type eq 'thumbnail') {
1824: return '/adm/lonKaputt/genericstudent_tn.gif';
1825: } else {
1826: return '/adm/lonKaputt/lonlogo_broken.gif';
1827: }
1828: }
1829: }
1830:
1831: # -------------------------------------------------------------------- New chat
1832:
1833: sub chatsend {
1834: my ($newentry,$anon,$group)=@_;
1835: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1836: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1837: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1838: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1839: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1840: &escape($newentry)).':'.$group,$chome);
1841: }
1842:
1843: # ------------------------------------------ Find current version of a resource
1844:
1845: sub getversion {
1846: my $fname=&clutter(shift);
1847: unless ($fname=~/^\/res\//) { return -1; }
1848: return ¤tversion(&filelocation('',$fname));
1849: }
1850:
1851: sub currentversion {
1852: my $fname=shift;
1853: my ($result,$cached)=&is_cached_new('resversion',$fname);
1854: if (defined($cached)) { return $result; }
1855: my $author=$fname;
1856: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1857: my ($udom,$uname)=split(/\//,$author);
1858: my $home=homeserver($uname,$udom);
1859: if ($home eq 'no_host') {
1860: return -1;
1861: }
1862: my $answer=reply("currentversion:$fname",$home);
1863: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1864: return -1;
1865: }
1866: return &do_cache_new('resversion',$fname,$answer,600);
1867: }
1868:
1869: # ----------------------------- Subscribe to a resource, return URL if possible
1870:
1871: sub subscribe {
1872: my $fname=shift;
1873: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1874: $fname=~s/[\n\r]//g;
1875: my $author=$fname;
1876: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1877: my ($udom,$uname)=split(/\//,$author);
1878: my $home=homeserver($uname,$udom);
1879: if ($home eq 'no_host') {
1880: return 'not_found';
1881: }
1882: my $answer=reply("sub:$fname",$home);
1883: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1884: $answer.=' by '.$home;
1885: }
1886: return $answer;
1887: }
1888:
1889: # -------------------------------------------------------------- Replicate file
1890:
1891: sub repcopy {
1892: my $filename=shift;
1893: $filename=~s/\/+/\//g;
1894: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1895: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1896: if ($filename=~m|^/home/httpd/html/userfiles/| or
1897: $filename=~m -^/*(uploaded|editupload)/-) {
1898: return &repcopy_userfile($filename);
1899: }
1900: $filename=~s/[\n\r]//g;
1901: my $transname="$filename.in.transfer";
1902: # FIXME: this should flock
1903: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1904: my $remoteurl=subscribe($filename);
1905: if ($remoteurl =~ /^con_lost by/) {
1906: &logthis("Subscribe returned $remoteurl: $filename");
1907: return 'unavailable';
1908: } elsif ($remoteurl eq 'not_found') {
1909: #&logthis("Subscribe returned not_found: $filename");
1910: return 'not_found';
1911: } elsif ($remoteurl =~ /^rejected by/) {
1912: &logthis("Subscribe returned $remoteurl: $filename");
1913: return 'forbidden';
1914: } elsif ($remoteurl eq 'directory') {
1915: return 'ok';
1916: } else {
1917: my $author=$filename;
1918: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1919: my ($udom,$uname)=split(/\//,$author);
1920: my $home=homeserver($uname,$udom);
1921: unless ($home eq $perlvar{'lonHostID'}) {
1922: my @parts=split(/\//,$filename);
1923: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1924: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1925: &logthis("Malconfiguration for replication: $filename");
1926: return 'bad_request';
1927: }
1928: my $count;
1929: for ($count=5;$count<$#parts;$count++) {
1930: $path.="/$parts[$count]";
1931: if ((-e $path)!=1) {
1932: mkdir($path,0777);
1933: }
1934: }
1935: my $ua=new LWP::UserAgent;
1936: my $request=new HTTP::Request('GET',"$remoteurl");
1937: my $response=$ua->request($request,$transname);
1938: if ($response->is_error()) {
1939: unlink($transname);
1940: my $message=$response->status_line;
1941: &logthis("<font color=\"blue\">WARNING:"
1942: ." LWP get: $message: $filename</font>");
1943: return 'unavailable';
1944: } else {
1945: if ($remoteurl!~/\.meta$/) {
1946: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1947: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1948: if ($mresponse->is_error()) {
1949: unlink($filename.'.meta');
1950: &logthis(
1951: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1952: }
1953: }
1954: rename($transname,$filename);
1955: return 'ok';
1956: }
1957: }
1958: }
1959: }
1960:
1961: # ------------------------------------------------ Get server side include body
1962: sub ssi_body {
1963: my ($filelink,%form)=@_;
1964: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1965: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1966: }
1967: my $output='';
1968: my $response;
1969: if ($filelink=~/^https?\:/) {
1970: ($output,$response)=&externalssi($filelink);
1971: } else {
1972: $filelink .= $filelink=~/\?/ ? '&' : '?';
1973: $filelink .= 'inhibitmenu=yes';
1974: ($output,$response)=&ssi($filelink,%form);
1975: }
1976: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1977: $output=~s/^.*?\<body[^\>]*\>//si;
1978: $output=~s/\<\/body\s*\>.*?$//si;
1979: if (wantarray) {
1980: return ($output, $response);
1981: } else {
1982: return $output;
1983: }
1984: }
1985:
1986: # --------------------------------------------------------- Server Side Include
1987:
1988: sub absolute_url {
1989: my ($host_name) = @_;
1990: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1991: if ($host_name eq '') {
1992: $host_name = $ENV{'SERVER_NAME'};
1993: }
1994: return $protocol.$host_name;
1995: }
1996:
1997: #
1998: # Server side include.
1999: # Parameters:
2000: # fn Possibly encrypted resource name/id.
2001: # form Hash that describes how the rendering should be done
2002: # and other things.
2003: # Returns:
2004: # Scalar context: The content of the response.
2005: # Array context: 2 element list of the content and the full response object.
2006: #
2007: sub ssi {
2008:
2009: my ($fn,%form)=@_;
2010: my $ua=new LWP::UserAgent;
2011: my $request;
2012:
2013: $form{'no_update_last_known'}=1;
2014: &Apache::lonenc::check_encrypt(\$fn);
2015: if (%form) {
2016: $request=new HTTP::Request('POST',&absolute_url().$fn);
2017: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
2018: } else {
2019: $request=new HTTP::Request('GET',&absolute_url().$fn);
2020: }
2021:
2022: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2023: my $response=$ua->request($request);
2024:
2025: if (wantarray) {
2026: return ($response->content, $response);
2027: } else {
2028: return $response->content;
2029: }
2030: }
2031:
2032: sub externalssi {
2033: my ($url)=@_;
2034: my $ua=new LWP::UserAgent;
2035: my $request=new HTTP::Request('GET',$url);
2036: my $response=$ua->request($request);
2037: if (wantarray) {
2038: return ($response->content, $response);
2039: } else {
2040: return $response->content;
2041: }
2042: }
2043:
2044: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2045:
2046: sub allowuploaded {
2047: my ($srcurl,$url)=@_;
2048: $url=&clutter(&declutter($url));
2049: my $dir=$url;
2050: $dir=~s/\/[^\/]+$//;
2051: my %httpref=();
2052: my $httpurl=&hreflocation('',$url);
2053: $httpref{'httpref.'.$httpurl}=$srcurl;
2054: &Apache::lonnet::appenv(\%httpref);
2055: }
2056:
2057: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2058: # input: action, courseID, current domain, intended
2059: # path to file, source of file, instruction to parse file for objects,
2060: # ref to hash for embedded objects,
2061: # ref to hash for codebase of java objects.
2062: #
2063: # output: url to file (if action was uploaddoc),
2064: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2065: #
2066: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2067: # course.
2068: #
2069: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2070: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2071: # course's home server.
2072: #
2073: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2074: # be copied from $source (current location) to
2075: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2076: # and will then be copied to
2077: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2078: # course's home server.
2079: #
2080: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2081: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2082: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2083: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2084: # in course's home server.
2085: #
2086:
2087: sub process_coursefile {
2088: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
2089: my $fetchresult;
2090: my $home=&homeserver($docuname,$docudom);
2091: if ($action eq 'propagate') {
2092: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2093: $home);
2094: } else {
2095: my $fpath = '';
2096: my $fname = $file;
2097: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2098: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2099: my $filepath = &build_filepath($fpath);
2100: if ($action eq 'copy') {
2101: if ($source eq '') {
2102: $fetchresult = 'no source file';
2103: return $fetchresult;
2104: } else {
2105: my $destination = $filepath.'/'.$fname;
2106: rename($source,$destination);
2107: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2108: $home);
2109: }
2110: } elsif ($action eq 'uploaddoc') {
2111: open(my $fh,'>'.$filepath.'/'.$fname);
2112: print $fh $env{'form.'.$source};
2113: close($fh);
2114: if ($parser eq 'parse') {
2115: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2116: unless ($parse_result eq 'ok') {
2117: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2118: }
2119: }
2120: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2121: $home);
2122: if ($fetchresult eq 'ok') {
2123: return '/uploaded/'.$fpath.'/'.$fname;
2124: } else {
2125: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2126: ' to host '.$home.': '.$fetchresult);
2127: return '/adm/notfound.html';
2128: }
2129: }
2130: }
2131: unless ( $fetchresult eq 'ok') {
2132: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2133: ' to host '.$home.': '.$fetchresult);
2134: }
2135: return $fetchresult;
2136: }
2137:
2138: sub build_filepath {
2139: my ($fpath) = @_;
2140: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2141: unless ($fpath eq '') {
2142: my @parts=split('/',$fpath);
2143: foreach my $part (@parts) {
2144: $filepath.= '/'.$part;
2145: if ((-e $filepath)!=1) {
2146: mkdir($filepath,0777);
2147: }
2148: }
2149: }
2150: return $filepath;
2151: }
2152:
2153: sub store_edited_file {
2154: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2155: my $file = $primary_url;
2156: $file =~ s#^/uploaded/$docudom/$docuname/##;
2157: my $fpath = '';
2158: my $fname = $file;
2159: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2160: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2161: my $filepath = &build_filepath($fpath);
2162: open(my $fh,'>'.$filepath.'/'.$fname);
2163: print $fh $content;
2164: close($fh);
2165: my $home=&homeserver($docuname,$docudom);
2166: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2167: $home);
2168: if ($$fetchresult eq 'ok') {
2169: return '/uploaded/'.$fpath.'/'.$fname;
2170: } else {
2171: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2172: ' to host '.$home.': '.$$fetchresult);
2173: return '/adm/notfound.html';
2174: }
2175: }
2176:
2177: sub clean_filename {
2178: my ($fname,$args)=@_;
2179: # Replace Windows backslashes by forward slashes
2180: $fname=~s/\\/\//g;
2181: if (!$args->{'keep_path'}) {
2182: # Get rid of everything but the actual filename
2183: $fname=~s/^.*\/([^\/]+)$/$1/;
2184: }
2185: # Replace spaces by underscores
2186: $fname=~s/\s+/\_/g;
2187: # Replace all other weird characters by nothing
2188: $fname=~s{[^/\w\.\-]}{}g;
2189: # Replace all .\d. sequences with _\d. so they no longer look like version
2190: # numbers
2191: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2192: return $fname;
2193: }
2194: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2195: sub resizeImage {
2196: my($img_url) = @_;
2197: my $ima = Image::Magick->new;
2198: $ima->Read($img_url);
2199: if($ima->Get('width') > 400)
2200: {
2201: my $factor = $ima->Get('width')/400;
2202: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2203: }
2204: if($ima->Get('height') > 500)
2205: {
2206: my $factor = $ima->Get('height')/500;
2207: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2208: }
2209:
2210: $ima->Write($img_url);
2211: }
2212:
2213: #Wrapper function for userphotoupload
2214: sub userphotoupload
2215: {
2216: my($formname,$subdir) = @_;
2217: $upload_photo_form = 1;
2218: return &userfileupload($formname,undef,$subdir);
2219: }
2220:
2221: # --------------- Take an uploaded file and put it into the userfiles directory
2222: # input: $formname - the contents of the file are in $env{"form.$formname"}
2223: # the desired filenam is in $env{"form.$formname.filename"}
2224: # $coursedoc - if true up to the current course
2225: # if false
2226: # $subdir - directory in userfile to store the file into
2227: # $parser - instruction to parse file for objects ($parser = parse)
2228: # $allfiles - reference to hash for embedded objects
2229: # $codebase - reference to hash for codebase of java objects
2230: # $desuname - username for permanent storage of uploaded file
2231: # $dsetudom - domain for permanaent storage of uploaded file
2232: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2233: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2234: #
2235: # output: url of file in userspace, or error: <message>
2236: # or /adm/notfound.html if failure to upload occurse
2237:
2238:
2239: sub userfileupload {
2240: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2241: $destudom,$thumbwidth,$thumbheight)=@_;
2242: if (!defined($subdir)) { $subdir='unknown'; }
2243: my $fname=$env{'form.'.$formname.'.filename'};
2244: $fname=&clean_filename($fname);
2245: # See if there is anything left
2246: unless ($fname) { return 'error: no uploaded file'; }
2247: chop($env{'form.'.$formname});
2248: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2249: my $now = time;
2250: my $filepath = 'tmp/helprequests/'.$now;
2251: my @parts=split(/\//,$filepath);
2252: my $fullpath = $perlvar{'lonDaemons'};
2253: for (my $i=0;$i<@parts;$i++) {
2254: $fullpath .= '/'.$parts[$i];
2255: if ((-e $fullpath)!=1) {
2256: mkdir($fullpath,0777);
2257: }
2258: }
2259: open(my $fh,'>'.$fullpath.'/'.$fname);
2260: print $fh $env{'form.'.$formname};
2261: close($fh);
2262: return $fullpath.'/'.$fname;
2263: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2264: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2265: '_'.$env{'user.domain'}.'/pending';
2266: my @parts=split(/\//,$filepath);
2267: my $fullpath = $perlvar{'lonDaemons'};
2268: for (my $i=0;$i<@parts;$i++) {
2269: $fullpath .= '/'.$parts[$i];
2270: if ((-e $fullpath)!=1) {
2271: mkdir($fullpath,0777);
2272: }
2273: }
2274: open(my $fh,'>'.$fullpath.'/'.$fname);
2275: print $fh $env{'form.'.$formname};
2276: close($fh);
2277: return $fullpath.'/'.$fname;
2278: }
2279: if ($subdir eq 'scantron') {
2280: $fname = 'scantron_orig_'.$fname;
2281: } else {
2282: # Create the directory if not present
2283: $fname="$subdir/$fname";
2284: }
2285: if ($coursedoc) {
2286: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2287: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2288: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2289: return &finishuserfileupload($docuname,$docudom,
2290: $formname,$fname,$parser,$allfiles,
2291: $codebase,$thumbwidth,$thumbheight);
2292: } else {
2293: $fname=$env{'form.folder'}.'/'.$fname;
2294: return &process_coursefile('uploaddoc',$docuname,$docudom,
2295: $fname,$formname,$parser,
2296: $allfiles,$codebase);
2297: }
2298: } elsif (defined($destuname)) {
2299: my $docuname=$destuname;
2300: my $docudom=$destudom;
2301: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2302: $parser,$allfiles,$codebase,
2303: $thumbwidth,$thumbheight);
2304:
2305: } else {
2306: my $docuname=$env{'user.name'};
2307: my $docudom=$env{'user.domain'};
2308: if (exists($env{'form.group'})) {
2309: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2310: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2311: }
2312: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2313: $parser,$allfiles,$codebase,
2314: $thumbwidth,$thumbheight);
2315: }
2316: }
2317:
2318: sub finishuserfileupload {
2319: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2320: $thumbwidth,$thumbheight) = @_;
2321: my $path=$docudom.'/'.$docuname.'/';
2322: my $filepath=$perlvar{'lonDocRoot'};
2323:
2324: my ($fnamepath,$file,$fetchthumb);
2325: $file=$fname;
2326: if ($fname=~m|/|) {
2327: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2328: $path.=$fnamepath.'/';
2329: }
2330: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2331: my $count;
2332: for ($count=4;$count<=$#parts;$count++) {
2333: $filepath.="/$parts[$count]";
2334: if ((-e $filepath)!=1) {
2335: mkdir($filepath,0777);
2336: }
2337: }
2338:
2339: # Save the file
2340: {
2341: if (!open(FH,'>'.$filepath.'/'.$file)) {
2342: &logthis('Failed to create '.$filepath.'/'.$file);
2343: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2344: return '/adm/notfound.html';
2345: }
2346: if (!print FH ($env{'form.'.$formname})) {
2347: &logthis('Failed to write to '.$filepath.'/'.$file);
2348: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2349: return '/adm/notfound.html';
2350: }
2351: close(FH);
2352: if($upload_photo_form==1)
2353: {
2354: resizeImage($filepath.'/'.$file);
2355: $upload_photo_form = 0;
2356: }
2357: }
2358: if ($parser eq 'parse') {
2359: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
2360: $codebase);
2361: unless ($parse_result eq 'ok') {
2362: &logthis('Failed to parse '.$filepath.$file.
2363: ' for embedded media: '.$parse_result);
2364: }
2365: }
2366: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2367: my $input = $filepath.'/'.$file;
2368: my $output = $filepath.'/'.'tn-'.$file;
2369: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2370: system("convert -sample $thumbsize $input $output");
2371: if (-e $filepath.'/'.'tn-'.$file) {
2372: $fetchthumb = 1;
2373: }
2374: }
2375:
2376: # Notify homeserver to grep it
2377: #
2378: my $docuhome=&homeserver($docuname,$docudom);
2379: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2380: if ($fetchresult eq 'ok') {
2381: if ($fetchthumb) {
2382: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2383: if ($thumbresult ne 'ok') {
2384: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2385: $docuhome.': '.$thumbresult);
2386: }
2387: }
2388: #
2389: # Return the URL to it
2390: return '/uploaded/'.$path.$file;
2391: } else {
2392: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2393: ': '.$fetchresult);
2394: return '/adm/notfound.html';
2395: }
2396: }
2397:
2398: sub extract_embedded_items {
2399: my ($fullpath,$allfiles,$codebase,$content) = @_;
2400: my @state = ();
2401: my %javafiles = (
2402: codebase => '',
2403: code => '',
2404: archive => ''
2405: );
2406: my %mediafiles = (
2407: src => '',
2408: movie => '',
2409: );
2410: my $p;
2411: if ($content) {
2412: $p = HTML::LCParser->new($content);
2413: } else {
2414: $p = HTML::LCParser->new($fullpath);
2415: }
2416: while (my $t=$p->get_token()) {
2417: if ($t->[0] eq 'S') {
2418: my ($tagname, $attr) = ($t->[1],$t->[2]);
2419: push(@state, $tagname);
2420: if (lc($tagname) eq 'allow') {
2421: &add_filetype($allfiles,$attr->{'src'},'src');
2422: }
2423: if (lc($tagname) eq 'img') {
2424: &add_filetype($allfiles,$attr->{'src'},'src');
2425: }
2426: if (lc($tagname) eq 'a') {
2427: &add_filetype($allfiles,$attr->{'href'},'href');
2428: }
2429: if (lc($tagname) eq 'script') {
2430: if ($attr->{'archive'} =~ /\.jar$/i) {
2431: &add_filetype($allfiles,$attr->{'archive'},'archive');
2432: } else {
2433: &add_filetype($allfiles,$attr->{'src'},'src');
2434: }
2435: }
2436: if (lc($tagname) eq 'link') {
2437: if (lc($attr->{'rel'}) eq 'stylesheet') {
2438: &add_filetype($allfiles,$attr->{'href'},'href');
2439: }
2440: }
2441: if (lc($tagname) eq 'object' ||
2442: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2443: foreach my $item (keys(%javafiles)) {
2444: $javafiles{$item} = '';
2445: }
2446: }
2447: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2448: my $name = lc($attr->{'name'});
2449: foreach my $item (keys(%javafiles)) {
2450: if ($name eq $item) {
2451: $javafiles{$item} = $attr->{'value'};
2452: last;
2453: }
2454: }
2455: foreach my $item (keys(%mediafiles)) {
2456: if ($name eq $item) {
2457: &add_filetype($allfiles, $attr->{'value'}, 'value');
2458: last;
2459: }
2460: }
2461: }
2462: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2463: foreach my $item (keys(%javafiles)) {
2464: if ($attr->{$item}) {
2465: $javafiles{$item} = $attr->{$item};
2466: last;
2467: }
2468: }
2469: foreach my $item (keys(%mediafiles)) {
2470: if ($attr->{$item}) {
2471: &add_filetype($allfiles,$attr->{$item},$item);
2472: last;
2473: }
2474: }
2475: }
2476: } elsif ($t->[0] eq 'E') {
2477: my ($tagname) = ($t->[1]);
2478: if ($javafiles{'codebase'} ne '') {
2479: $javafiles{'codebase'} .= '/';
2480: }
2481: if (lc($tagname) eq 'applet' ||
2482: lc($tagname) eq 'object' ||
2483: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2484: ) {
2485: foreach my $item (keys(%javafiles)) {
2486: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2487: my $file=$javafiles{'codebase'}.$javafiles{$item};
2488: &add_filetype($allfiles,$file,$item);
2489: }
2490: }
2491: }
2492: pop @state;
2493: }
2494: }
2495: return 'ok';
2496: }
2497:
2498: sub add_filetype {
2499: my ($allfiles,$file,$type)=@_;
2500: if (exists($allfiles->{$file})) {
2501: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2502: push(@{$allfiles->{$file}}, &escape($type));
2503: }
2504: } else {
2505: @{$allfiles->{$file}} = (&escape($type));
2506: }
2507: }
2508:
2509: sub removeuploadedurl {
2510: my ($url)=@_;
2511: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
2512: return &removeuserfile($uname,$udom,$fname);
2513: }
2514:
2515: sub removeuserfile {
2516: my ($docuname,$docudom,$fname)=@_;
2517: my $home=&homeserver($docuname,$docudom);
2518: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2519: if ($result eq 'ok') {
2520: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2521: my $metafile = $fname.'.meta';
2522: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
2523: my $url = "/uploaded/$docudom/$docuname/$fname";
2524: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2525: my $sqlresult =
2526: &update_portfolio_table($docuname,$docudom,$file,
2527: 'portfolio_metadata',$group,
2528: 'delete');
2529: }
2530: }
2531: return $result;
2532: }
2533:
2534: sub mkdiruserfile {
2535: my ($docuname,$docudom,$dir)=@_;
2536: my $home=&homeserver($docuname,$docudom);
2537: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2538: }
2539:
2540: sub renameuserfile {
2541: my ($docuname,$docudom,$old,$new)=@_;
2542: my $home=&homeserver($docuname,$docudom);
2543: my $result = &reply("renameuserfile:$docudom:$docuname:".
2544: &escape("$old").':'.&escape("$new"),$home);
2545: if ($result eq 'ok') {
2546: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2547: my $oldmeta = $old.'.meta';
2548: my $newmeta = $new.'.meta';
2549: my $metaresult =
2550: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
2551: my $url = "/uploaded/$docudom/$docuname/$old";
2552: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2553: my $sqlresult =
2554: &update_portfolio_table($docuname,$docudom,$file,
2555: 'portfolio_metadata',$group,
2556: 'delete');
2557: }
2558: }
2559: return $result;
2560: }
2561:
2562: # ------------------------------------------------------------------------- Log
2563:
2564: sub log {
2565: my ($dom,$nam,$hom,$what)=@_;
2566: return critical("log:$dom:$nam:$what",$hom);
2567: }
2568:
2569: # ------------------------------------------------------------------ Course Log
2570: #
2571: # This routine flushes several buffers of non-mission-critical nature
2572: #
2573:
2574: sub flushcourselogs {
2575: &logthis('Flushing log buffers');
2576: #
2577: # course logs
2578: # This is a log of all transactions in a course, which can be used
2579: # for data mining purposes
2580: #
2581: # It also collects the courseid database, which lists last transaction
2582: # times and course titles for all courseids
2583: #
2584: my %courseidbuffer=();
2585: foreach my $crsid (keys(%courselogs)) {
2586: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
2587: &escape($courselogs{$crsid}),
2588: $coursehombuf{$crsid}) eq 'ok') {
2589: delete $courselogs{$crsid};
2590: } else {
2591: &logthis('Failed to flush log buffer for '.$crsid);
2592: if (length($courselogs{$crsid})>40000) {
2593: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
2594: " exceeded maximum size, deleting.</font>");
2595: delete $courselogs{$crsid};
2596: }
2597: }
2598: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
2599: 'description' => $coursedescrbuf{$crsid},
2600: 'inst_code' => $courseinstcodebuf{$crsid},
2601: 'type' => $coursetypebuf{$crsid},
2602: 'owner' => $courseownerbuf{$crsid},
2603: };
2604: }
2605: #
2606: # Write course id database (reverse lookup) to homeserver of courses
2607: # Is used in pickcourse
2608: #
2609: foreach my $crs_home (keys(%courseidbuffer)) {
2610: my $response = &courseidput(&host_domain($crs_home),
2611: $courseidbuffer{$crs_home},
2612: $crs_home,'timeonly');
2613: }
2614: #
2615: # File accesses
2616: # Writes to the dynamic metadata of resources to get hit counts, etc.
2617: #
2618: foreach my $entry (keys(%accesshash)) {
2619: if ($entry =~ /___count$/) {
2620: my ($dom,$name);
2621: ($dom,$name,undef)=
2622: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
2623: if (! defined($dom) || $dom eq '' ||
2624: ! defined($name) || $name eq '') {
2625: my $cid = $env{'request.course.id'};
2626: $dom = $env{'request.'.$cid.'.domain'};
2627: $name = $env{'request.'.$cid.'.num'};
2628: }
2629: my $value = $accesshash{$entry};
2630: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2631: my %temphash=($url => $value);
2632: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2633: if ($result eq 'ok') {
2634: delete $accesshash{$entry};
2635: } elsif ($result eq 'unknown_cmd') {
2636: # Target server has old code running on it.
2637: my %temphash=($entry => $value);
2638: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2639: delete $accesshash{$entry};
2640: }
2641: }
2642: } else {
2643: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
2644: my %temphash=($entry => $accesshash{$entry});
2645: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2646: delete $accesshash{$entry};
2647: }
2648: }
2649: }
2650: #
2651: # Roles
2652: # Reverse lookup of user roles for course faculty/staff and co-authorship
2653: #
2654: foreach my $entry (keys(%userrolehash)) {
2655: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
2656: split(/\:/,$entry);
2657: if (&Apache::lonnet::put('nohist_userroles',
2658: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
2659: $rudom,$runame) eq 'ok') {
2660: delete $userrolehash{$entry};
2661: }
2662: }
2663: #
2664: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2665: #
2666: my %domrolebuffer = ();
2667: foreach my $entry (keys(%domainrolehash)) {
2668: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
2669: if ($domrolebuffer{$rudom}) {
2670: $domrolebuffer{$rudom}.='&'.&escape($entry).
2671: '='.&escape($domainrolehash{$entry});
2672: } else {
2673: $domrolebuffer{$rudom}.=&escape($entry).
2674: '='.&escape($domainrolehash{$entry});
2675: }
2676: delete $domainrolehash{$entry};
2677: }
2678: foreach my $dom (keys(%domrolebuffer)) {
2679: my %servers = &get_servers($dom,'library');
2680: foreach my $tryserver (keys(%servers)) {
2681: unless (&reply('domroleput:'.$dom.':'.
2682: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2683: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2684: }
2685: }
2686: }
2687: $dumpcount++;
2688: }
2689:
2690: sub courselog {
2691: my $what=shift;
2692: $what=time.':'.$what;
2693: unless ($env{'request.course.id'}) { return ''; }
2694: $coursedombuf{$env{'request.course.id'}}=
2695: $env{'course.'.$env{'request.course.id'}.'.domain'};
2696: $coursenumbuf{$env{'request.course.id'}}=
2697: $env{'course.'.$env{'request.course.id'}.'.num'};
2698: $coursehombuf{$env{'request.course.id'}}=
2699: $env{'course.'.$env{'request.course.id'}.'.home'};
2700: $coursedescrbuf{$env{'request.course.id'}}=
2701: $env{'course.'.$env{'request.course.id'}.'.description'};
2702: $courseinstcodebuf{$env{'request.course.id'}}=
2703: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2704: $courseownerbuf{$env{'request.course.id'}}=
2705: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
2706: $coursetypebuf{$env{'request.course.id'}}=
2707: $env{'course.'.$env{'request.course.id'}.'.type'};
2708: if (defined $courselogs{$env{'request.course.id'}}) {
2709: $courselogs{$env{'request.course.id'}}.='&'.$what;
2710: } else {
2711: $courselogs{$env{'request.course.id'}}.=$what;
2712: }
2713: if (length($courselogs{$env{'request.course.id'}})>4048) {
2714: &flushcourselogs();
2715: }
2716: }
2717:
2718: sub courseacclog {
2719: my $fnsymb=shift;
2720: unless ($env{'request.course.id'}) { return ''; }
2721: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2722: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2723: $what.=':POST';
2724: # FIXME: Probably ought to escape things....
2725: foreach my $key (keys(%env)) {
2726: if ($key=~/^form\.(.*)/) {
2727: my $formitem = $1;
2728: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2729: $what.=':'.$formitem.'='.$env{$key};
2730: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2731: $what.=':'.$formitem.'='.$env{$key};
2732: }
2733: }
2734: }
2735: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2736: # FIXME: We should not be depending on a form parameter that someone
2737: # editing lonsearchcat.pm might change in the future.
2738: if ($env{'form.phase'} eq 'course_search') {
2739: $what.= ':POST';
2740: # FIXME: Probably ought to escape things....
2741: foreach my $element ('courseexp','crsfulltext','crsrelated',
2742: 'crsdiscuss') {
2743: $what.=':'.$element.'='.$env{'form.'.$element};
2744: }
2745: }
2746: }
2747: &courselog($what);
2748: }
2749:
2750: sub countacc {
2751: my $url=&declutter(shift);
2752: return if (! defined($url) || $url eq '');
2753: unless ($env{'request.course.id'}) { return ''; }
2754: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2755: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2756: $accesshash{$key}++;
2757: }
2758:
2759: sub linklog {
2760: my ($from,$to)=@_;
2761: $from=&declutter($from);
2762: $to=&declutter($to);
2763: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2764: $accesshash{$to.'___'.$from.'___goto'}=1;
2765: }
2766:
2767: sub userrolelog {
2768: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2769: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2770: ($trole=~/^in/) || ($trole=~/^cc/) ||
2771: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2772: ($trole=~/^ta/)) {
2773: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2774: $userrolehash
2775: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2776: =$tend.':'.$tstart;
2777: }
2778: if (($env{'request.role'} =~ /dc\./) &&
2779: (($trole=~/^au/) || ($trole=~/^in/) ||
2780: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2781: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2782: $userrolehash
2783: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2784: =$tend.':'.$tstart;
2785: }
2786: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2787: ($trole=~/^li/) || ($trole=~/^li/) ||
2788: ($trole=~/^au/) || ($trole=~/^dg/) ||
2789: ($trole=~/^sc/)) {
2790: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2791: $domainrolehash
2792: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2793: = $tend.':'.$tstart;
2794: }
2795: }
2796:
2797: sub courserolelog {
2798: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2799: if (($trole eq 'cc') || ($trole eq 'in') ||
2800: ($trole eq 'ep') || ($trole eq 'ad') ||
2801: ($trole eq 'ta') || ($trole eq 'st') ||
2802: ($trole=~/^cr/) || ($trole eq 'gr')) {
2803: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2804: my $cdom = $1;
2805: my $cnum = $2;
2806: my $sec = $3;
2807: my $namespace = 'rolelog';
2808: my %storehash = (
2809: role => $trole,
2810: start => $tstart,
2811: end => $tend,
2812: selfenroll => $selfenroll,
2813: context => $context,
2814: );
2815: if ($trole eq 'gr') {
2816: $namespace = 'groupslog';
2817: $storehash{'group'} = $sec;
2818: } else {
2819: $storehash{'section'} = $sec;
2820: }
2821: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2822: if (($trole ne 'st') || ($sec ne '')) {
2823: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2824: }
2825: }
2826: }
2827: return;
2828: }
2829:
2830: sub get_course_adv_roles {
2831: my ($cid,$codes) = @_;
2832: $cid=$env{'request.course.id'} unless (defined($cid));
2833: my %coursehash=&coursedescription($cid);
2834: my $crstype = &Apache::loncommon::course_type($cid);
2835: my %nothide=();
2836: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2837: if ($user !~ /:/) {
2838: $nothide{join(':',split(/[\@]/,$user))}=1;
2839: } else {
2840: $nothide{$user}=1;
2841: }
2842: }
2843: my %returnhash=();
2844: my %dumphash=
2845: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2846: my $now=time;
2847: my %privileged;
2848: foreach my $entry (keys(%dumphash)) {
2849: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2850: if (($tstart) && ($tstart<0)) { next; }
2851: if (($tend) && ($tend<$now)) { next; }
2852: if (($tstart) && ($now<$tstart)) { next; }
2853: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2854: if ($username eq '' || $domain eq '') { next; }
2855: unless (ref($privileged{$domain}) eq 'HASH') {
2856: my %dompersonnel =
2857: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2858: $privileged{$domain} = {};
2859: foreach my $server (keys(%dompersonnel)) {
2860: if (ref($dompersonnel{$server}) eq 'HASH') {
2861: foreach my $user (keys(%{$dompersonnel{$server}})) {
2862: my ($trole,$uname,$udom) = split(/:/,$user);
2863: $privileged{$udom}{$uname} = 1;
2864: }
2865: }
2866: }
2867: }
2868: if ((exists($privileged{$domain}{$username})) &&
2869: (!$nothide{$username.':'.$domain})) { next; }
2870: if ($role eq 'cr') { next; }
2871: if ($codes) {
2872: if ($section) { $role .= ':'.$section; }
2873: if ($returnhash{$role}) {
2874: $returnhash{$role}.=','.$username.':'.$domain;
2875: } else {
2876: $returnhash{$role}=$username.':'.$domain;
2877: }
2878: } else {
2879: my $key=&plaintext($role,$crstype);
2880: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
2881: if ($returnhash{$key}) {
2882: $returnhash{$key}.=','.$username.':'.$domain;
2883: } else {
2884: $returnhash{$key}=$username.':'.$domain;
2885: }
2886: }
2887: }
2888: return %returnhash;
2889: }
2890:
2891: sub get_my_roles {
2892: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
2893: unless (defined($uname)) { $uname=$env{'user.name'}; }
2894: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2895: my (%dumphash,%nothide);
2896: if ($context eq 'userroles') {
2897: %dumphash = &dump('roles',$udom,$uname);
2898: } else {
2899: %dumphash=
2900: &dump('nohist_userroles',$udom,$uname);
2901: if ($hidepriv) {
2902: my %coursehash=&coursedescription($udom.'_'.$uname);
2903: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2904: if ($user !~ /:/) {
2905: $nothide{join(':',split(/[\@]/,$user))} = 1;
2906: } else {
2907: $nothide{$user} = 1;
2908: }
2909: }
2910: }
2911: }
2912: my %returnhash=();
2913: my $now=time;
2914: my %privileged;
2915: foreach my $entry (keys(%dumphash)) {
2916: my ($role,$tend,$tstart);
2917: if ($context eq 'userroles') {
2918: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2919: } else {
2920: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2921: }
2922: if (($tstart) && ($tstart<0)) { next; }
2923: my $status = 'active';
2924: if (($tend) && ($tend<=$now)) {
2925: $status = 'previous';
2926: }
2927: if (($tstart) && ($now<$tstart)) {
2928: $status = 'future';
2929: }
2930: if (ref($types) eq 'ARRAY') {
2931: if (!grep(/^\Q$status\E$/,@{$types})) {
2932: next;
2933: }
2934: } else {
2935: if ($status ne 'active') {
2936: next;
2937: }
2938: }
2939: my ($rolecode,$username,$domain,$section,$area);
2940: if ($context eq 'userroles') {
2941: ($area,$rolecode) = split(/_/,$entry);
2942: (undef,$domain,$username,$section) = split(/\//,$area);
2943: } else {
2944: ($role,$username,$domain,$section) = split(/\:/,$entry);
2945: }
2946: if (ref($roledoms) eq 'ARRAY') {
2947: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2948: next;
2949: }
2950: }
2951: if (ref($roles) eq 'ARRAY') {
2952: if (!grep(/^\Q$role\E$/,@{$roles})) {
2953: if ($role =~ /^cr\//) {
2954: if (!grep(/^cr$/,@{$roles})) {
2955: next;
2956: }
2957: } else {
2958: next;
2959: }
2960: }
2961: }
2962: if ($hidepriv) {
2963: if ($context eq 'userroles') {
2964: if ((&privileged($username,$domain)) &&
2965: (!$nothide{$username.':'.$domain})) {
2966: next;
2967: }
2968: } else {
2969: unless (ref($privileged{$domain}) eq 'HASH') {
2970: my %dompersonnel =
2971: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2972: $privileged{$domain} = {};
2973: if (keys(%dompersonnel)) {
2974: foreach my $server (keys(%dompersonnel)) {
2975: if (ref($dompersonnel{$server}) eq 'HASH') {
2976: foreach my $user (keys(%{$dompersonnel{$server}})) {
2977: my ($trole,$uname,$udom) = split(/:/,$user);
2978: $privileged{$udom}{$uname} = $trole;
2979: }
2980: }
2981: }
2982: }
2983: }
2984: if (exists($privileged{$domain}{$username})) {
2985: if (!$nothide{$username.':'.$domain}) {
2986: next;
2987: }
2988: }
2989: }
2990: }
2991: if ($withsec) {
2992: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2993: $tstart.':'.$tend;
2994: } else {
2995: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2996: }
2997: }
2998: return %returnhash;
2999: }
3000:
3001: # ----------------------------------------------------- Frontpage Announcements
3002: #
3003: #
3004:
3005: sub postannounce {
3006: my ($server,$text)=@_;
3007: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
3008: unless ($text=~/\w/) { $text=''; }
3009: return &reply('setannounce:'.&escape($text),$server);
3010: }
3011:
3012: sub getannounce {
3013:
3014: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
3015: my $announcement='';
3016: while (my $line = <$fh>) { $announcement .= $line; }
3017: close($fh);
3018: if ($announcement=~/\w/) {
3019: return
3020: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
3021: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
3022: } else {
3023: return '';
3024: }
3025: } else {
3026: return '';
3027: }
3028: }
3029:
3030: # ---------------------------------------------------------- Course ID routines
3031: # Deal with domain's nohist_courseid.db files
3032: #
3033:
3034: sub courseidput {
3035: my ($domain,$storehash,$coursehome,$caller) = @_;
3036: my $outcome;
3037: if ($caller eq 'timeonly') {
3038: my $cids = '';
3039: foreach my $item (keys(%$storehash)) {
3040: $cids.=&escape($item).'&';
3041: }
3042: $cids=~s/\&$//;
3043: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3044: $coursehome);
3045: } else {
3046: my $items = '';
3047: foreach my $item (keys(%$storehash)) {
3048: $items.= &escape($item).'='.
3049: &freeze_escape($$storehash{$item}).'&';
3050: }
3051: $items=~s/\&$//;
3052: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3053: $coursehome);
3054: }
3055: if ($outcome eq 'unknown_cmd') {
3056: my $what;
3057: foreach my $cid (keys(%$storehash)) {
3058: $what .= &escape($cid).'=';
3059: foreach my $item ('description','inst_code','owner','type') {
3060: $what .= &escape($storehash->{$cid}{$item}).':';
3061: }
3062: $what =~ s/\:$/&/;
3063: }
3064: $what =~ s/\&$//;
3065: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3066: } else {
3067: return $outcome;
3068: }
3069: }
3070:
3071: sub courseiddump {
3072: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3073: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3074: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,$cloneonly)=@_;
3075: my $as_hash = 1;
3076: my %returnhash;
3077: if (!$domfilter) { $domfilter=''; }
3078: my %libserv = &all_library();
3079: foreach my $tryserver (keys(%libserv)) {
3080: if ( ( $hostidflag == 1
3081: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3082: || (!defined($hostidflag)) ) {
3083:
3084: if (($domfilter eq '') ||
3085: (&host_domain($tryserver) eq $domfilter)) {
3086: my $rep =
3087: &reply('courseiddump:'.&host_domain($tryserver).':'.
3088: $sincefilter.':'.&escape($descfilter).':'.
3089: &escape($instcodefilter).':'.&escape($ownerfilter).
3090: ':'.&escape($coursefilter).':'.&escape($typefilter).
3091: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3092: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3093: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3094: &escape($cc_clone).':'.$cloneonly,$tryserver);
3095: my @pairs=split(/\&/,$rep);
3096: foreach my $item (@pairs) {
3097: my ($key,$value)=split(/\=/,$item,2);
3098: $key = &unescape($key);
3099: next if ($key =~ /^error: 2 /);
3100: my $result = &thaw_unescape($value);
3101: if (ref($result) eq 'HASH') {
3102: $returnhash{$key}=$result;
3103: } else {
3104: my @responses = split(/:/,$value);
3105: my @items = ('description','inst_code','owner','type');
3106: for (my $i=0; $i<@responses; $i++) {
3107: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3108: }
3109: }
3110: }
3111: }
3112: }
3113: }
3114: return %returnhash;
3115: }
3116:
3117: # ---------------------------------------------------------- DC e-mail
3118:
3119: sub dcmailput {
3120: my ($domain,$msgid,$message,$server)=@_;
3121: my $status = &Apache::lonnet::critical(
3122: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3123: &escape($message),$server);
3124: return $status;
3125: }
3126:
3127: sub dcmaildump {
3128: my ($dom,$startdate,$enddate,$senders) = @_;
3129: my %returnhash=();
3130:
3131: if (defined(&domain($dom,'primary'))) {
3132: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3133: &escape($enddate).':';
3134: my @esc_senders=map { &escape($_)} @$senders;
3135: $cmd.=&escape(join('&',@esc_senders));
3136: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3137: my ($key,$value) = split(/\=/,$line,2);
3138: if (($key) && ($value)) {
3139: $returnhash{&unescape($key)} = &unescape($value);
3140: }
3141: }
3142: }
3143: return %returnhash;
3144: }
3145: # ---------------------------------------------------------- Domain roles
3146:
3147: sub get_domain_roles {
3148: my ($dom,$roles,$startdate,$enddate)=@_;
3149: if ((!defined($startdate)) || ($startdate eq '')) {
3150: $startdate = '.';
3151: }
3152: if ((!defined($enddate)) || ($enddate eq '')) {
3153: $enddate = '.';
3154: }
3155: my $rolelist;
3156: if (ref($roles) eq 'ARRAY') {
3157: $rolelist = join(':',@{$roles});
3158: }
3159: my %personnel = ();
3160:
3161: my %servers = &get_servers($dom,'library');
3162: foreach my $tryserver (keys(%servers)) {
3163: %{$personnel{$tryserver}}=();
3164: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3165: &escape($startdate).':'.
3166: &escape($enddate).':'.
3167: &escape($rolelist), $tryserver))) {
3168: my ($key,$value) = split(/\=/,$line,2);
3169: if (($key) && ($value)) {
3170: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3171: }
3172: }
3173: }
3174: return %personnel;
3175: }
3176:
3177: # ----------------------------------------------------------- Check out an item
3178:
3179: sub get_first_access {
3180: my ($type,$argsymb)=@_;
3181: my ($symb,$courseid,$udom,$uname)=&whichuser();
3182: if ($argsymb) { $symb=$argsymb; }
3183: my ($map,$id,$res)=&decode_symb($symb);
3184: if ($type eq 'course') {
3185: $res='course';
3186: } elsif ($type eq 'map') {
3187: $res=&symbread($map);
3188: } else {
3189: $res=$symb;
3190: }
3191: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3192: return $times{"$courseid\0$res"};
3193: }
3194:
3195: sub set_first_access {
3196: my ($type)=@_;
3197: my ($symb,$courseid,$udom,$uname)=&whichuser();
3198: my ($map,$id,$res)=&decode_symb($symb);
3199: if ($type eq 'course') {
3200: $res='course';
3201: } elsif ($type eq 'map') {
3202: $res=&symbread($map);
3203: } else {
3204: $res=$symb;
3205: }
3206: my $firstaccess=&get_first_access($type,$symb);
3207: if (!$firstaccess) {
3208: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3209: }
3210: return 'already_set';
3211: }
3212:
3213: sub checkout {
3214: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3215: my $now=time;
3216: my $lonhost=$perlvar{'lonHostID'};
3217: my $infostr=&escape(
3218: 'CHECKOUTTOKEN&'.
3219: $tuname.'&'.
3220: $tudom.'&'.
3221: $tcrsid.'&'.
3222: $symb.'&'.
3223: $now.'&'.$ENV{'REMOTE_ADDR'});
3224: my $token=&reply('tmpput:'.$infostr,$lonhost);
3225: if ($token=~/^error\:/) {
3226: &logthis("<font color=\"blue\">WARNING: ".
3227: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3228: "</font>");
3229: return '';
3230: }
3231:
3232: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3233: $token=~tr/a-z/A-Z/;
3234:
3235: my %infohash=('resource.0.outtoken' => $token,
3236: 'resource.0.checkouttime' => $now,
3237: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
3238:
3239: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3240: return '';
3241: } else {
3242: &logthis("<font color=\"blue\">WARNING: ".
3243: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3244: "</font>");
3245: }
3246:
3247: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3248: &escape('Checkout '.$infostr.' - '.
3249: $token)) ne 'ok') {
3250: return '';
3251: } else {
3252: &logthis("<font color=\"blue\">WARNING: ".
3253: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3254: "</font>");
3255: }
3256: return $token;
3257: }
3258:
3259: # ------------------------------------------------------------ Check in an item
3260:
3261: sub checkin {
3262: my $token=shift;
3263: my $now=time;
3264: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3265: $lonhost=~tr/A-Z/a-z/;
3266: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
3267: $dtoken=~s/\W/\_/g;
3268: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
3269: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3270:
3271: unless (($tuname) && ($tudom)) {
3272: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3273: return '';
3274: }
3275:
3276: unless (&allowed('mgr',$tcrsid)) {
3277: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
3278: $env{'user.name'}.' - '.$env{'user.domain'});
3279: return '';
3280: }
3281:
3282: my %infohash=('resource.0.intoken' => $token,
3283: 'resource.0.checkintime' => $now,
3284: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
3285:
3286: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3287: return '';
3288: }
3289:
3290: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3291: &escape('Checkin - '.$token)) ne 'ok') {
3292: return '';
3293: }
3294:
3295: return ($symb,$tuname,$tudom,$tcrsid);
3296: }
3297:
3298: # --------------------------------------------- Set Expire Date for Spreadsheet
3299:
3300: sub expirespread {
3301: my ($uname,$udom,$stype,$usymb)=@_;
3302: my $cid=$env{'request.course.id'};
3303: if ($cid) {
3304: my $now=time;
3305: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3306: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3307: $env{'course.'.$cid.'.num'}.
3308: ':nohist_expirationdates:'.
3309: &escape($key).'='.$now,
3310: $env{'course.'.$cid.'.home'})
3311: }
3312: return 'ok';
3313: }
3314:
3315: # ----------------------------------------------------- Devalidate Spreadsheets
3316:
3317: sub devalidate {
3318: my ($symb,$uname,$udom)=@_;
3319: my $cid=$env{'request.course.id'};
3320: if ($cid) {
3321: # delete the stored spreadsheets for
3322: # - the student level sheet of this user in course's homespace
3323: # - the assessment level sheet for this resource
3324: # for this user in user's homespace
3325: # - current conditional state info
3326: my $key=$uname.':'.$udom.':';
3327: my $status=
3328: &del('nohist_calculatedsheets',
3329: [$key.'studentcalc:'],
3330: $env{'course.'.$cid.'.domain'},
3331: $env{'course.'.$cid.'.num'})
3332: .' '.
3333: &del('nohist_calculatedsheets_'.$cid,
3334: [$key.'assesscalc:'.$symb],$udom,$uname);
3335: unless ($status eq 'ok ok') {
3336: &logthis('Could not devalidate spreadsheet '.
3337: $uname.' at '.$udom.' for '.
3338: $symb.': '.$status);
3339: }
3340: &delenv('user.state.'.$cid);
3341: }
3342: }
3343:
3344: sub get_scalar {
3345: my ($string,$end) = @_;
3346: my $value;
3347: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3348: $value = $1;
3349: } elsif ($$string =~ s/^([^&]*?)&//) {
3350: $value = $1;
3351: }
3352: return &unescape($value);
3353: }
3354:
3355: sub array2str {
3356: my (@array) = @_;
3357: my $result=&arrayref2str(\@array);
3358: $result=~s/^__ARRAY_REF__//;
3359: $result=~s/__END_ARRAY_REF__$//;
3360: return $result;
3361: }
3362:
3363: sub arrayref2str {
3364: my ($arrayref) = @_;
3365: my $result='__ARRAY_REF__';
3366: foreach my $elem (@$arrayref) {
3367: if(ref($elem) eq 'ARRAY') {
3368: $result.=&arrayref2str($elem).'&';
3369: } elsif(ref($elem) eq 'HASH') {
3370: $result.=&hashref2str($elem).'&';
3371: } elsif(ref($elem)) {
3372: #print("Got a ref of ".(ref($elem))." skipping.");
3373: } else {
3374: $result.=&escape($elem).'&';
3375: }
3376: }
3377: $result=~s/\&$//;
3378: $result .= '__END_ARRAY_REF__';
3379: return $result;
3380: }
3381:
3382: sub hash2str {
3383: my (%hash) = @_;
3384: my $result=&hashref2str(\%hash);
3385: $result=~s/^__HASH_REF__//;
3386: $result=~s/__END_HASH_REF__$//;
3387: return $result;
3388: }
3389:
3390: sub hashref2str {
3391: my ($hashref)=@_;
3392: my $result='__HASH_REF__';
3393: foreach my $key (sort(keys(%$hashref))) {
3394: if (ref($key) eq 'ARRAY') {
3395: $result.=&arrayref2str($key).'=';
3396: } elsif (ref($key) eq 'HASH') {
3397: $result.=&hashref2str($key).'=';
3398: } elsif (ref($key)) {
3399: $result.='=';
3400: #print("Got a ref of ".(ref($key))." skipping.");
3401: } else {
3402: if ($key) {$result.=&escape($key).'=';} else { last; }
3403: }
3404:
3405: if(ref($hashref->{$key}) eq 'ARRAY') {
3406: $result.=&arrayref2str($hashref->{$key}).'&';
3407: } elsif(ref($hashref->{$key}) eq 'HASH') {
3408: $result.=&hashref2str($hashref->{$key}).'&';
3409: } elsif(ref($hashref->{$key})) {
3410: $result.='&';
3411: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3412: } else {
3413: $result.=&escape($hashref->{$key}).'&';
3414: }
3415: }
3416: $result=~s/\&$//;
3417: $result .= '__END_HASH_REF__';
3418: return $result;
3419: }
3420:
3421: sub str2hash {
3422: my ($string)=@_;
3423: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3424: return %$hash;
3425: }
3426:
3427: sub str2hashref {
3428: my ($string) = @_;
3429:
3430: my %hash;
3431:
3432: if($string !~ /^__HASH_REF__/) {
3433: if (! ($string eq '' || !defined($string))) {
3434: $hash{'error'}='Not hash reference';
3435: }
3436: return (\%hash, $string);
3437: }
3438:
3439: $string =~ s/^__HASH_REF__//;
3440:
3441: while($string !~ /^__END_HASH_REF__/) {
3442: #key
3443: my $key='';
3444: if($string =~ /^__HASH_REF__/) {
3445: ($key, $string)=&str2hashref($string);
3446: if(defined($key->{'error'})) {
3447: $hash{'error'}='Bad data';
3448: return (\%hash, $string);
3449: }
3450: } elsif($string =~ /^__ARRAY_REF__/) {
3451: ($key, $string)=&str2arrayref($string);
3452: if($key->[0] eq 'Array reference error') {
3453: $hash{'error'}='Bad data';
3454: return (\%hash, $string);
3455: }
3456: } else {
3457: $string =~ s/^(.*?)=//;
3458: $key=&unescape($1);
3459: }
3460: $string =~ s/^=//;
3461:
3462: #value
3463: my $value='';
3464: if($string =~ /^__HASH_REF__/) {
3465: ($value, $string)=&str2hashref($string);
3466: if(defined($value->{'error'})) {
3467: $hash{'error'}='Bad data';
3468: return (\%hash, $string);
3469: }
3470: } elsif($string =~ /^__ARRAY_REF__/) {
3471: ($value, $string)=&str2arrayref($string);
3472: if($value->[0] eq 'Array reference error') {
3473: $hash{'error'}='Bad data';
3474: return (\%hash, $string);
3475: }
3476: } else {
3477: $value=&get_scalar(\$string,'__END_HASH_REF__');
3478: }
3479: $string =~ s/^&//;
3480:
3481: $hash{$key}=$value;
3482: }
3483:
3484: $string =~ s/^__END_HASH_REF__//;
3485:
3486: return (\%hash, $string);
3487: }
3488:
3489: sub str2array {
3490: my ($string)=@_;
3491: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3492: return @$array;
3493: }
3494:
3495: sub str2arrayref {
3496: my ($string) = @_;
3497: my @array;
3498:
3499: if($string !~ /^__ARRAY_REF__/) {
3500: if (! ($string eq '' || !defined($string))) {
3501: $array[0]='Array reference error';
3502: }
3503: return (\@array, $string);
3504: }
3505:
3506: $string =~ s/^__ARRAY_REF__//;
3507:
3508: while($string !~ /^__END_ARRAY_REF__/) {
3509: my $value='';
3510: if($string =~ /^__HASH_REF__/) {
3511: ($value, $string)=&str2hashref($string);
3512: if(defined($value->{'error'})) {
3513: $array[0] ='Array reference error';
3514: return (\@array, $string);
3515: }
3516: } elsif($string =~ /^__ARRAY_REF__/) {
3517: ($value, $string)=&str2arrayref($string);
3518: if($value->[0] eq 'Array reference error') {
3519: $array[0] ='Array reference error';
3520: return (\@array, $string);
3521: }
3522: } else {
3523: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3524: }
3525: $string =~ s/^&//;
3526:
3527: push(@array, $value);
3528: }
3529:
3530: $string =~ s/^__END_ARRAY_REF__//;
3531:
3532: return (\@array, $string);
3533: }
3534:
3535: # -------------------------------------------------------------------Temp Store
3536:
3537: sub tmpreset {
3538: my ($symb,$namespace,$domain,$stuname) = @_;
3539: if (!$symb) {
3540: $symb=&symbread();
3541: if (!$symb) { $symb= $env{'request.url'}; }
3542: }
3543: $symb=escape($symb);
3544:
3545: if (!$namespace) { $namespace=$env{'request.state'}; }
3546: $namespace=~s/\//\_/g;
3547: $namespace=~s/\W//g;
3548:
3549: if (!$domain) { $domain=$env{'user.domain'}; }
3550: if (!$stuname) { $stuname=$env{'user.name'}; }
3551: if ($domain eq 'public' && $stuname eq 'public') {
3552: $stuname=$ENV{'REMOTE_ADDR'};
3553: }
3554: my $path=$perlvar{'lonDaemons'}.'/tmp';
3555: my %hash;
3556: if (tie(%hash,'GDBM_File',
3557: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3558: &GDBM_WRCREAT(),0640)) {
3559: foreach my $key (keys(%hash)) {
3560: if ($key=~ /:$symb/) {
3561: delete($hash{$key});
3562: }
3563: }
3564: }
3565: }
3566:
3567: sub tmpstore {
3568: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3569:
3570: if (!$symb) {
3571: $symb=&symbread();
3572: if (!$symb) { $symb= $env{'request.url'}; }
3573: }
3574: $symb=escape($symb);
3575:
3576: if (!$namespace) {
3577: # I don't think we would ever want to store this for a course.
3578: # it seems this will only be used if we don't have a course.
3579: #$namespace=$env{'request.course.id'};
3580: #if (!$namespace) {
3581: $namespace=$env{'request.state'};
3582: #}
3583: }
3584: $namespace=~s/\//\_/g;
3585: $namespace=~s/\W//g;
3586: if (!$domain) { $domain=$env{'user.domain'}; }
3587: if (!$stuname) { $stuname=$env{'user.name'}; }
3588: if ($domain eq 'public' && $stuname eq 'public') {
3589: $stuname=$ENV{'REMOTE_ADDR'};
3590: }
3591: my $now=time;
3592: my %hash;
3593: my $path=$perlvar{'lonDaemons'}.'/tmp';
3594: if (tie(%hash,'GDBM_File',
3595: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3596: &GDBM_WRCREAT(),0640)) {
3597: $hash{"version:$symb"}++;
3598: my $version=$hash{"version:$symb"};
3599: my $allkeys='';
3600: foreach my $key (keys(%$storehash)) {
3601: $allkeys.=$key.':';
3602: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
3603: }
3604: $hash{"$version:$symb:timestamp"}=$now;
3605: $allkeys.='timestamp';
3606: $hash{"$version:keys:$symb"}=$allkeys;
3607: if (untie(%hash)) {
3608: return 'ok';
3609: } else {
3610: return "error:$!";
3611: }
3612: } else {
3613: return "error:$!";
3614: }
3615: }
3616:
3617: # -----------------------------------------------------------------Temp Restore
3618:
3619: sub tmprestore {
3620: my ($symb,$namespace,$domain,$stuname) = @_;
3621:
3622: if (!$symb) {
3623: $symb=&symbread();
3624: if (!$symb) { $symb= $env{'request.url'}; }
3625: }
3626: $symb=escape($symb);
3627:
3628: if (!$namespace) { $namespace=$env{'request.state'}; }
3629:
3630: if (!$domain) { $domain=$env{'user.domain'}; }
3631: if (!$stuname) { $stuname=$env{'user.name'}; }
3632: if ($domain eq 'public' && $stuname eq 'public') {
3633: $stuname=$ENV{'REMOTE_ADDR'};
3634: }
3635: my %returnhash;
3636: $namespace=~s/\//\_/g;
3637: $namespace=~s/\W//g;
3638: my %hash;
3639: my $path=$perlvar{'lonDaemons'}.'/tmp';
3640: if (tie(%hash,'GDBM_File',
3641: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3642: &GDBM_READER(),0640)) {
3643: my $version=$hash{"version:$symb"};
3644: $returnhash{'version'}=$version;
3645: my $scope;
3646: for ($scope=1;$scope<=$version;$scope++) {
3647: my $vkeys=$hash{"$scope:keys:$symb"};
3648: my @keys=split(/:/,$vkeys);
3649: my $key;
3650: $returnhash{"$scope:keys"}=$vkeys;
3651: foreach $key (@keys) {
3652: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3653: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3654: }
3655: }
3656: if (!(untie(%hash))) {
3657: return "error:$!";
3658: }
3659: } else {
3660: return "error:$!";
3661: }
3662: return %returnhash;
3663: }
3664:
3665: # ----------------------------------------------------------------------- Store
3666:
3667: sub store {
3668: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3669: my $home='';
3670:
3671: if ($stuname) { $home=&homeserver($stuname,$domain); }
3672:
3673: $symb=&symbclean($symb);
3674: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3675:
3676: if (!$domain) { $domain=$env{'user.domain'}; }
3677: if (!$stuname) { $stuname=$env{'user.name'}; }
3678:
3679: &devalidate($symb,$stuname,$domain);
3680:
3681: $symb=escape($symb);
3682: if (!$namespace) {
3683: unless ($namespace=$env{'request.course.id'}) {
3684: return '';
3685: }
3686: }
3687: if (!$home) { $home=$env{'user.home'}; }
3688:
3689: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3690: $$storehash{'host'}=$perlvar{'lonHostID'};
3691:
3692: my $namevalue='';
3693: foreach my $key (keys(%$storehash)) {
3694: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3695: }
3696: $namevalue=~s/\&$//;
3697: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
3698: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3699: }
3700:
3701: # -------------------------------------------------------------- Critical Store
3702:
3703: sub cstore {
3704: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3705: my $home='';
3706:
3707: if ($stuname) { $home=&homeserver($stuname,$domain); }
3708:
3709: $symb=&symbclean($symb);
3710: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3711:
3712: if (!$domain) { $domain=$env{'user.domain'}; }
3713: if (!$stuname) { $stuname=$env{'user.name'}; }
3714:
3715: &devalidate($symb,$stuname,$domain);
3716:
3717: $symb=escape($symb);
3718: if (!$namespace) {
3719: unless ($namespace=$env{'request.course.id'}) {
3720: return '';
3721: }
3722: }
3723: if (!$home) { $home=$env{'user.home'}; }
3724:
3725: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3726: $$storehash{'host'}=$perlvar{'lonHostID'};
3727:
3728: my $namevalue='';
3729: foreach my $key (keys(%$storehash)) {
3730: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3731: }
3732: $namevalue=~s/\&$//;
3733: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
3734: return critical
3735: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3736: }
3737:
3738: # --------------------------------------------------------------------- Restore
3739:
3740: sub restore {
3741: my ($symb,$namespace,$domain,$stuname) = @_;
3742: my $home='';
3743:
3744: if ($stuname) { $home=&homeserver($stuname,$domain); }
3745:
3746: if (!$symb) {
3747: unless ($symb=escape(&symbread())) { return ''; }
3748: } else {
3749: $symb=&escape(&symbclean($symb));
3750: }
3751: if (!$namespace) {
3752: unless ($namespace=$env{'request.course.id'}) {
3753: return '';
3754: }
3755: }
3756: if (!$domain) { $domain=$env{'user.domain'}; }
3757: if (!$stuname) { $stuname=$env{'user.name'}; }
3758: if (!$home) { $home=$env{'user.home'}; }
3759: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3760:
3761: my %returnhash=();
3762: foreach my $line (split(/\&/,$answer)) {
3763: my ($name,$value)=split(/\=/,$line);
3764: $returnhash{&unescape($name)}=&thaw_unescape($value);
3765: }
3766: my $version;
3767: for ($version=1;$version<=$returnhash{'version'};$version++) {
3768: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3769: $returnhash{$item}=$returnhash{$version.':'.$item};
3770: }
3771: }
3772: return %returnhash;
3773: }
3774:
3775: # ---------------------------------------------------------- Course Description
3776:
3777: sub coursedescription {
3778: my ($courseid,$args)=@_;
3779: $courseid=~s/^\///;
3780: $courseid=~s/\_/\//g;
3781: my ($cdomain,$cnum)=split(/\//,$courseid);
3782: my $chome=&homeserver($cnum,$cdomain);
3783: my $normalid=$cdomain.'_'.$cnum;
3784: # need to always cache even if we get errors otherwise we keep
3785: # trying and trying and trying to get the course description.
3786: my %envhash=();
3787: my %returnhash=();
3788:
3789: my $expiretime=600;
3790: if ($env{'request.course.id'} eq $normalid) {
3791: $expiretime=120;
3792: }
3793:
3794: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3795: if (!$args->{'freshen_cache'}
3796: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3797: foreach my $key (keys(%env)) {
3798: next if ($key !~ /^\Q$prefix\E(.*)/);
3799: my ($setting) = $1;
3800: $returnhash{$setting} = $env{$key};
3801: }
3802: return %returnhash;
3803: }
3804:
3805: # get the data agin
3806: if (!$args->{'one_time'}) {
3807: $envhash{'course.'.$normalid.'.last_cache'}=time;
3808: }
3809:
3810: if ($chome ne 'no_host') {
3811: %returnhash=&dump('environment',$cdomain,$cnum);
3812: if (!exists($returnhash{'con_lost'})) {
3813: $returnhash{'home'}= $chome;
3814: $returnhash{'domain'} = $cdomain;
3815: $returnhash{'num'} = $cnum;
3816: if (!defined($returnhash{'type'})) {
3817: $returnhash{'type'} = 'Course';
3818: }
3819: while (my ($name,$value) = each %returnhash) {
3820: $envhash{'course.'.$normalid.'.'.$name}=$value;
3821: }
3822: $returnhash{'url'}=&clutter($returnhash{'url'});
3823: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
3824: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
3825: $envhash{'course.'.$normalid.'.home'}=$chome;
3826: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3827: $envhash{'course.'.$normalid.'.num'}=$cnum;
3828: }
3829: }
3830: if (!$args->{'one_time'}) {
3831: &appenv(\%envhash);
3832: }
3833: return %returnhash;
3834: }
3835:
3836: # -------------------------------------------------See if a user is privileged
3837:
3838: sub privileged {
3839: my ($username,$domain)=@_;
3840: my $rolesdump=&reply("dump:$domain:$username:roles",
3841: &homeserver($username,$domain));
3842: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3843: my $now=time;
3844: if ($rolesdump ne '') {
3845: foreach my $entry (split(/&/,$rolesdump)) {
3846: if ($entry!~/^rolesdef_/) {
3847: my ($area,$role)=split(/=/,$entry);
3848: $area=~s/\_\w\w$//;
3849: my ($trole,$tend,$tstart)=split(/_/,$role);
3850: if (($trole eq 'dc') || ($trole eq 'su')) {
3851: my $active=1;
3852: if ($tend) {
3853: if ($tend<$now) { $active=0; }
3854: }
3855: if ($tstart) {
3856: if ($tstart>$now) { $active=0; }
3857: }
3858: if ($active) { return 1; }
3859: }
3860: }
3861: }
3862: }
3863: return 0;
3864: }
3865:
3866: # -------------------------------------------------------- Get user privileges
3867:
3868: sub rolesinit {
3869: my ($domain,$username,$authhost)=@_;
3870: my %userroles;
3871: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
3872: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
3873: my %allroles=();
3874: my %allgroups=();
3875: my $now=time;
3876: %userroles = ('user.login.time' => $now);
3877: my $group_privs;
3878:
3879: if ($rolesdump ne '') {
3880: foreach my $entry (split(/&/,$rolesdump)) {
3881: if ($entry!~/^rolesdef_/) {
3882: my ($area,$role)=split(/=/,$entry);
3883: $area=~s/\_\w\w$//;
3884: my ($trole,$tend,$tstart,$group_privs);
3885: if ($role=~/^cr/) {
3886: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3887: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
3888: ($tend,$tstart)=split('_',$trest);
3889: } else {
3890: $trole=$role;
3891: }
3892: } elsif ($role =~ m|^gr/|) {
3893: ($trole,$tend,$tstart) = split(/_/,$role);
3894: ($trole,$group_privs) = split(/\//,$trole);
3895: $group_privs = &unescape($group_privs);
3896: } else {
3897: ($trole,$tend,$tstart)=split(/_/,$role);
3898: }
3899: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3900: $username);
3901: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
3902: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3903: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
3904: if (($area ne '') && ($trole ne '')) {
3905: my $spec=$trole.'.'.$area;
3906: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3907: if ($trole =~ /^cr\//) {
3908: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
3909: } elsif ($trole eq 'gr') {
3910: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
3911: } else {
3912: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
3913: }
3914: }
3915: }
3916: }
3917: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3918: $userroles{'user.adv'} = $adv;
3919: $userroles{'user.author'} = $author;
3920: $env{'user.adv'}=$adv;
3921: }
3922: return \%userroles;
3923: }
3924:
3925: sub set_arearole {
3926: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3927: # log the associated role with the area
3928: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
3929: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
3930: }
3931:
3932: sub custom_roleprivs {
3933: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3934: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3935: my $homsvr=homeserver($rauthor,$rdomain);
3936: if (&hostname($homsvr) ne '') {
3937: my ($rdummy,$roledef)=
3938: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3939: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3940: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3941: if (defined($syspriv)) {
3942: $$allroles{'cm./'}.=':'.$syspriv;
3943: $$allroles{$spec.'./'}.=':'.$syspriv;
3944: }
3945: if ($tdomain ne '') {
3946: if (defined($dompriv)) {
3947: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3948: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3949: }
3950: if (($trest ne '') && (defined($coursepriv))) {
3951: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3952: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3953: }
3954: }
3955: }
3956: }
3957: }
3958:
3959: sub group_roleprivs {
3960: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3961: my $access = 1;
3962: my $now = time;
3963: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3964: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3965: if ($access) {
3966: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3967: $$allgroups{$course}{$group} .=':'.$group_privs;
3968: }
3969: }
3970:
3971: sub standard_roleprivs {
3972: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3973: if (defined($pr{$trole.':s'})) {
3974: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3975: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3976: }
3977: if ($tdomain ne '') {
3978: if (defined($pr{$trole.':d'})) {
3979: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3980: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3981: }
3982: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3983: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3984: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3985: }
3986: }
3987: }
3988:
3989: sub set_userprivs {
3990: my ($userroles,$allroles,$allgroups) = @_;
3991: my $author=0;
3992: my $adv=0;
3993: my %grouproles = ();
3994: if (keys(%{$allgroups}) > 0) {
3995: foreach my $role (keys(%{$allroles})) {
3996: my ($trole,$area,$sec,$extendedarea);
3997: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
3998: $trole = $1;
3999: $area = $2;
4000: $sec = $3;
4001: $extendedarea = $area.$sec;
4002: if (exists($$allgroups{$area})) {
4003: foreach my $group (keys(%{$$allgroups{$area}})) {
4004: my $spec = $trole.'.'.$extendedarea;
4005: $grouproles{$spec.'.'.$area.'/'.$group} =
4006: $$allgroups{$area}{$group};
4007: }
4008: }
4009: }
4010: }
4011: }
4012: foreach my $group (keys(%grouproles)) {
4013: $$allroles{$group} = $grouproles{$group};
4014: }
4015: foreach my $role (keys(%{$allroles})) {
4016: my %thesepriv;
4017: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
4018: foreach my $item (split(/:/,$$allroles{$role})) {
4019: if ($item ne '') {
4020: my ($privilege,$restrictions)=split(/&/,$item);
4021: if ($restrictions eq '') {
4022: $thesepriv{$privilege}='F';
4023: } elsif ($thesepriv{$privilege} ne 'F') {
4024: $thesepriv{$privilege}.=$restrictions;
4025: }
4026: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4027: }
4028: }
4029: my $thesestr='';
4030: foreach my $priv (keys(%thesepriv)) {
4031: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4032: }
4033: $userroles->{'user.priv.'.$role} = $thesestr;
4034: }
4035: return ($author,$adv);
4036: }
4037:
4038: sub role_status {
4039: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4040: my @pwhere = ();
4041: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4042: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4043: unless (!defined($$role) || $$role eq '') {
4044: $$where=join('.',@pwhere);
4045: $$trolecode=$$role.'.'.$$where;
4046: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4047: $$tstatus='is';
4048: if ($$tstart && $$tstart>$then) {
4049: $$tstatus='future';
4050: if ($$tstart && $$tstart>$refresh) {
4051: if ($$tstart<$now) {
4052: if (($$where ne '') && ($$role ne '')) {
4053: my (%allroles,%allgroups,$group_privs);
4054: my %userroles = (
4055: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4056: );
4057: my $spec=$$role.'.'.$$where;
4058: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4059: if ($$role eq 'gr') {
4060: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4061: $env{'user.name'})=@_;
4062: my ($trole) = split('_',$role,1);
4063: (undef,my $group_privs) = split(/\//,$trole);
4064: $group_privs = &unescape($group_privs);
4065: }
4066: if ($$role =~ /^cr\//) {
4067: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4068: } elsif ($$role eq 'gr') {
4069: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4070: $env{'user.name'});
4071: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
4072: (undef,my $group_privs) = split(/\//,$trole);
4073: $group_privs = &unescape($group_privs);
4074: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4075: } else {
4076: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4077: }
4078: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
4079: &appenv(\%userroles,[$$role,'cm']);
4080: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4081: $$tstatus = 'is';
4082: }
4083: }
4084: }
4085: }
4086: if ($$tend) {
4087: if ($$tend<$then) {
4088: $$tstatus='expired';
4089: } elsif ($$tend<$now) {
4090: $$tstatus='will_not';
4091: }
4092: }
4093: }
4094: }
4095: }
4096:
4097: sub check_adhoc_privs {
4098: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
4099: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4100: if ($env{$cckey}) {
4101: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4102: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4103: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4104: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4105: }
4106: } else {
4107: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4108: }
4109: }
4110:
4111: sub set_adhoc_privileges {
4112: # role can be cc or ca
4113: my ($dcdom,$pickedcourse,$role) = @_;
4114: my $area = '/'.$dcdom.'/'.$pickedcourse;
4115: my $spec = $role.'.'.$area;
4116: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4117: $env{'user.name'});
4118: my %ccrole = ();
4119: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4120: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4121: &appenv(\%userroles,[$role,'cm']);
4122: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4123: &appenv( {'request.role' => $spec,
4124: 'request.role.domain' => $dcdom,
4125: 'request.course.sec' => ''
4126: }
4127: );
4128: my $tadv=0;
4129: if (&allowed('adv') eq 'F') { $tadv=1; }
4130: &appenv({'request.role.adv' => $tadv});
4131: }
4132:
4133: # --------------------------------------------------------------- get interface
4134:
4135: sub get {
4136: my ($namespace,$storearr,$udomain,$uname)=@_;
4137: my $items='';
4138: foreach my $item (@$storearr) {
4139: $items.=&escape($item).'&';
4140: }
4141: $items=~s/\&$//;
4142: if (!$udomain) { $udomain=$env{'user.domain'}; }
4143: if (!$uname) { $uname=$env{'user.name'}; }
4144: my $uhome=&homeserver($uname,$udomain);
4145:
4146: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4147: my @pairs=split(/\&/,$rep);
4148: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4149: return @pairs;
4150: }
4151: my %returnhash=();
4152: my $i=0;
4153: foreach my $item (@$storearr) {
4154: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4155: $i++;
4156: }
4157: return %returnhash;
4158: }
4159:
4160: # --------------------------------------------------------------- del interface
4161:
4162: sub del {
4163: my ($namespace,$storearr,$udomain,$uname)=@_;
4164: my $items='';
4165: foreach my $item (@$storearr) {
4166: $items.=&escape($item).'&';
4167: }
4168:
4169: $items=~s/\&$//;
4170: if (!$udomain) { $udomain=$env{'user.domain'}; }
4171: if (!$uname) { $uname=$env{'user.name'}; }
4172: my $uhome=&homeserver($uname,$udomain);
4173: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4174: }
4175:
4176: # -------------------------------------------------------------- dump interface
4177:
4178: sub dump {
4179: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4180: if (!$udomain) { $udomain=$env{'user.domain'}; }
4181: if (!$uname) { $uname=$env{'user.name'}; }
4182: my $uhome=&homeserver($uname,$udomain);
4183: if ($regexp) {
4184: $regexp=&escape($regexp);
4185: } else {
4186: $regexp='.';
4187: }
4188: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4189: my @pairs=split(/\&/,$rep);
4190: my %returnhash=();
4191: foreach my $item (@pairs) {
4192: my ($key,$value)=split(/=/,$item,2);
4193: $key = &unescape($key);
4194: next if ($key =~ /^error: 2 /);
4195: $returnhash{$key}=&thaw_unescape($value);
4196: }
4197: return %returnhash;
4198: }
4199:
4200: # --------------------------------------------------------- dumpstore interface
4201:
4202: sub dumpstore {
4203: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4204: if (!$udomain) { $udomain=$env{'user.domain'}; }
4205: if (!$uname) { $uname=$env{'user.name'}; }
4206: my $uhome=&homeserver($uname,$udomain);
4207: if ($regexp) {
4208: $regexp=&escape($regexp);
4209: } else {
4210: $regexp='.';
4211: }
4212: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4213: my @pairs=split(/\&/,$rep);
4214: my %returnhash=();
4215: foreach my $item (@pairs) {
4216: my ($key,$value)=split(/=/,$item,2);
4217: next if ($key =~ /^error: 2 /);
4218: $returnhash{$key}=&thaw_unescape($value);
4219: }
4220: return %returnhash;
4221: }
4222:
4223: # -------------------------------------------------------------- keys interface
4224:
4225: sub getkeys {
4226: my ($namespace,$udomain,$uname)=@_;
4227: if (!$udomain) { $udomain=$env{'user.domain'}; }
4228: if (!$uname) { $uname=$env{'user.name'}; }
4229: my $uhome=&homeserver($uname,$udomain);
4230: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4231: my @keyarray=();
4232: foreach my $key (split(/\&/,$rep)) {
4233: next if ($key =~ /^error: 2 /);
4234: push(@keyarray,&unescape($key));
4235: }
4236: return @keyarray;
4237: }
4238:
4239: # --------------------------------------------------------------- currentdump
4240: sub currentdump {
4241: my ($courseid,$sdom,$sname)=@_;
4242: $courseid = $env{'request.course.id'} if (! defined($courseid));
4243: $sdom = $env{'user.domain'} if (! defined($sdom));
4244: $sname = $env{'user.name'} if (! defined($sname));
4245: my $uhome = &homeserver($sname,$sdom);
4246: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4247: return if ($rep =~ /^(error:|no_such_host)/);
4248: #
4249: my %returnhash=();
4250: #
4251: if ($rep eq "unknown_cmd") {
4252: # an old lond will not know currentdump
4253: # Do a dump and make it look like a currentdump
4254: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4255: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4256: my %hash = @tmp;
4257: @tmp=();
4258: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4259: } else {
4260: my @pairs=split(/\&/,$rep);
4261: foreach my $pair (@pairs) {
4262: my ($key,$value)=split(/=/,$pair,2);
4263: my ($symb,$param) = split(/:/,$key);
4264: $returnhash{&unescape($symb)}->{&unescape($param)} =
4265: &thaw_unescape($value);
4266: }
4267: }
4268: return %returnhash;
4269: }
4270:
4271: sub convert_dump_to_currentdump{
4272: my %hash = %{shift()};
4273: my %returnhash;
4274: # Code ripped from lond, essentially. The only difference
4275: # here is the unescaping done by lonnet::dump(). Conceivably
4276: # we might run in to problems with parameter names =~ /^v\./
4277: while (my ($key,$value) = each(%hash)) {
4278: my ($v,$symb,$param) = split(/:/,$key);
4279: $symb = &unescape($symb);
4280: $param = &unescape($param);
4281: next if ($v eq 'version' || $symb eq 'keys');
4282: next if (exists($returnhash{$symb}) &&
4283: exists($returnhash{$symb}->{$param}) &&
4284: $returnhash{$symb}->{'v.'.$param} > $v);
4285: $returnhash{$symb}->{$param}=$value;
4286: $returnhash{$symb}->{'v.'.$param}=$v;
4287: }
4288: #
4289: # Remove all of the keys in the hashes which keep track of
4290: # the version of the parameter.
4291: while (my ($symb,$param_hash) = each(%returnhash)) {
4292: # use a foreach because we are going to delete from the hash.
4293: foreach my $key (keys(%$param_hash)) {
4294: delete($param_hash->{$key}) if ($key =~ /^v\./);
4295: }
4296: }
4297: return \%returnhash;
4298: }
4299:
4300: # ------------------------------------------------------ critical inc interface
4301:
4302: sub cinc {
4303: return &inc(@_,'critical');
4304: }
4305:
4306: # --------------------------------------------------------------- inc interface
4307:
4308: sub inc {
4309: my ($namespace,$store,$udomain,$uname,$critical) = @_;
4310: if (!$udomain) { $udomain=$env{'user.domain'}; }
4311: if (!$uname) { $uname=$env{'user.name'}; }
4312: my $uhome=&homeserver($uname,$udomain);
4313: my $items='';
4314: if (! ref($store)) {
4315: # got a single value, so use that instead
4316: $items = &escape($store).'=&';
4317: } elsif (ref($store) eq 'SCALAR') {
4318: $items = &escape($$store).'=&';
4319: } elsif (ref($store) eq 'ARRAY') {
4320: $items = join('=&',map {&escape($_);} @{$store});
4321: } elsif (ref($store) eq 'HASH') {
4322: while (my($key,$value) = each(%{$store})) {
4323: $items.= &escape($key).'='.&escape($value).'&';
4324: }
4325: }
4326: $items=~s/\&$//;
4327: if ($critical) {
4328: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4329: } else {
4330: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4331: }
4332: }
4333:
4334: # --------------------------------------------------------------- put interface
4335:
4336: sub put {
4337: my ($namespace,$storehash,$udomain,$uname)=@_;
4338: if (!$udomain) { $udomain=$env{'user.domain'}; }
4339: if (!$uname) { $uname=$env{'user.name'}; }
4340: my $uhome=&homeserver($uname,$udomain);
4341: my $items='';
4342: foreach my $item (keys(%$storehash)) {
4343: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4344: }
4345: $items=~s/\&$//;
4346: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4347: }
4348:
4349: # ------------------------------------------------------------ newput interface
4350:
4351: sub newput {
4352: my ($namespace,$storehash,$udomain,$uname)=@_;
4353: if (!$udomain) { $udomain=$env{'user.domain'}; }
4354: if (!$uname) { $uname=$env{'user.name'}; }
4355: my $uhome=&homeserver($uname,$udomain);
4356: my $items='';
4357: foreach my $key (keys(%$storehash)) {
4358: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4359: }
4360: $items=~s/\&$//;
4361: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4362: }
4363:
4364: # --------------------------------------------------------- putstore interface
4365:
4366: sub putstore {
4367: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4368: if (!$udomain) { $udomain=$env{'user.domain'}; }
4369: if (!$uname) { $uname=$env{'user.name'}; }
4370: my $uhome=&homeserver($uname,$udomain);
4371: my $items='';
4372: foreach my $key (keys(%$storehash)) {
4373: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
4374: }
4375: $items=~s/\&$//;
4376: my $esc_symb=&escape($symb);
4377: my $esc_v=&escape($version);
4378: my $reply =
4379: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
4380: $uhome);
4381: if ($reply eq 'unknown_cmd') {
4382: # gfall back to way things use to be done
4383: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4384: $uname);
4385: }
4386: return $reply;
4387: }
4388:
4389: sub old_putstore {
4390: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4391: if (!$udomain) { $udomain=$env{'user.domain'}; }
4392: if (!$uname) { $uname=$env{'user.name'}; }
4393: my $uhome=&homeserver($uname,$udomain);
4394: my %newstorehash;
4395: foreach my $item (keys(%$storehash)) {
4396: my $key = $version.':'.&escape($symb).':'.$item;
4397: $newstorehash{$key} = $storehash->{$item};
4398: }
4399: my $items='';
4400: my %allitems = ();
4401: foreach my $item (keys(%newstorehash)) {
4402: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
4403: my $key = $1.':keys:'.$2;
4404: $allitems{$key} .= $3.':';
4405: }
4406: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
4407: }
4408: foreach my $item (keys(%allitems)) {
4409: $allitems{$item} =~ s/\:$//;
4410: $items.= $item.'='.$allitems{$item}.'&';
4411: }
4412: $items=~s/\&$//;
4413: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4414: }
4415:
4416: # ------------------------------------------------------ critical put interface
4417:
4418: sub cput {
4419: my ($namespace,$storehash,$udomain,$uname)=@_;
4420: if (!$udomain) { $udomain=$env{'user.domain'}; }
4421: if (!$uname) { $uname=$env{'user.name'}; }
4422: my $uhome=&homeserver($uname,$udomain);
4423: my $items='';
4424: foreach my $item (keys(%$storehash)) {
4425: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4426: }
4427: $items=~s/\&$//;
4428: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
4429: }
4430:
4431: # -------------------------------------------------------------- eget interface
4432:
4433: sub eget {
4434: my ($namespace,$storearr,$udomain,$uname)=@_;
4435: my $items='';
4436: foreach my $item (@$storearr) {
4437: $items.=&escape($item).'&';
4438: }
4439: $items=~s/\&$//;
4440: if (!$udomain) { $udomain=$env{'user.domain'}; }
4441: if (!$uname) { $uname=$env{'user.name'}; }
4442: my $uhome=&homeserver($uname,$udomain);
4443: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
4444: my @pairs=split(/\&/,$rep);
4445: my %returnhash=();
4446: my $i=0;
4447: foreach my $item (@$storearr) {
4448: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4449: $i++;
4450: }
4451: return %returnhash;
4452: }
4453:
4454: # ------------------------------------------------------------ tmpput interface
4455: sub tmpput {
4456: my ($storehash,$server,$context)=@_;
4457: my $items='';
4458: foreach my $item (keys(%$storehash)) {
4459: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4460: }
4461: $items=~s/\&$//;
4462: if (defined($context)) {
4463: $items .= ':'.&escape($context);
4464: }
4465: return &reply("tmpput:$items",$server);
4466: }
4467:
4468: # ------------------------------------------------------------ tmpget interface
4469: sub tmpget {
4470: my ($token,$server)=@_;
4471: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4472: my $rep=&reply("tmpget:$token",$server);
4473: my %returnhash;
4474: foreach my $item (split(/\&/,$rep)) {
4475: my ($key,$value)=split(/=/,$item);
4476: next if ($key =~ /^error: 2 /);
4477: $returnhash{&unescape($key)}=&thaw_unescape($value);
4478: }
4479: return %returnhash;
4480: }
4481:
4482: # ------------------------------------------------------------ tmpget interface
4483: sub tmpdel {
4484: my ($token,$server)=@_;
4485: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4486: return &reply("tmpdel:$token",$server);
4487: }
4488:
4489: # -------------------------------------------------- portfolio access checking
4490:
4491: sub portfolio_access {
4492: my ($requrl) = @_;
4493: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4494: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
4495: if ($result) {
4496: my %setters;
4497: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4498: my ($startblock,$endblock) =
4499: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4500: if ($startblock && $endblock) {
4501: return 'B';
4502: }
4503: } else {
4504: my ($startblock,$endblock) =
4505: &Apache::loncommon::blockcheck(\%setters,'port');
4506: if ($startblock && $endblock) {
4507: return 'B';
4508: }
4509: }
4510: }
4511: if ($result eq 'ok') {
4512: return 'F';
4513: } elsif ($result =~ /^[^:]+:guest_/) {
4514: return 'A';
4515: }
4516: return '';
4517: }
4518:
4519: sub get_portfolio_access {
4520: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4521:
4522: if (!ref($access_hash)) {
4523: my $current_perms = &get_portfile_permissions($udom,$unum);
4524: my %access_controls = &get_access_controls($current_perms,$group,
4525: $file_name);
4526: $access_hash = $access_controls{$file_name};
4527: }
4528:
4529: my ($public,$guest,@domains,@users,@courses,@groups);
4530: my $now = time;
4531: if (ref($access_hash) eq 'HASH') {
4532: foreach my $key (keys(%{$access_hash})) {
4533: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4534: if ($start > $now) {
4535: next;
4536: }
4537: if ($end && $end<$now) {
4538: next;
4539: }
4540: if ($scope eq 'public') {
4541: $public = $key;
4542: last;
4543: } elsif ($scope eq 'guest') {
4544: $guest = $key;
4545: } elsif ($scope eq 'domains') {
4546: push(@domains,$key);
4547: } elsif ($scope eq 'users') {
4548: push(@users,$key);
4549: } elsif ($scope eq 'course') {
4550: push(@courses,$key);
4551: } elsif ($scope eq 'group') {
4552: push(@groups,$key);
4553: }
4554: }
4555: if ($public) {
4556: return 'ok';
4557: }
4558: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4559: if ($guest) {
4560: return $guest;
4561: }
4562: } else {
4563: if (@domains > 0) {
4564: foreach my $domkey (@domains) {
4565: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4566: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4567: return 'ok';
4568: }
4569: }
4570: }
4571: }
4572: if (@users > 0) {
4573: foreach my $userkey (@users) {
4574: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4575: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4576: if (ref($item) eq 'HASH') {
4577: if (($item->{'uname'} eq $env{'user.name'}) &&
4578: ($item->{'udom'} eq $env{'user.domain'})) {
4579: return 'ok';
4580: }
4581: }
4582: }
4583: }
4584: }
4585: }
4586: my %roleshash;
4587: my @courses_and_groups = @courses;
4588: push(@courses_and_groups,@groups);
4589: if (@courses_and_groups > 0) {
4590: my (%allgroups,%allroles);
4591: my ($start,$end,$role,$sec,$group);
4592: foreach my $envkey (%env) {
4593: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
4594: my $cid = $2.'_'.$3;
4595: if ($1 eq 'gr') {
4596: $group = $4;
4597: $allgroups{$cid}{$group} = $env{$envkey};
4598: } else {
4599: if ($4 eq '') {
4600: $sec = 'none';
4601: } else {
4602: $sec = $4;
4603: }
4604: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4605: }
4606: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
4607: my $cid = $2.'_'.$3;
4608: if ($4 eq '') {
4609: $sec = 'none';
4610: } else {
4611: $sec = $4;
4612: }
4613: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4614: }
4615: }
4616: if (keys(%allroles) == 0) {
4617: return;
4618: }
4619: foreach my $key (@courses_and_groups) {
4620: my %content = %{$$access_hash{$key}};
4621: my $cnum = $content{'number'};
4622: my $cdom = $content{'domain'};
4623: my $cid = $cdom.'_'.$cnum;
4624: if (!exists($allroles{$cid})) {
4625: next;
4626: }
4627: foreach my $role_id (keys(%{$content{'roles'}})) {
4628: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4629: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4630: my @status = @{$content{'roles'}{$role_id}{'access'}};
4631: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4632: foreach my $role (keys(%{$allroles{$cid}})) {
4633: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4634: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4635: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4636: if (grep/^all$/,@sections) {
4637: return 'ok';
4638: } else {
4639: if (grep/^$sec$/,@sections) {
4640: return 'ok';
4641: }
4642: }
4643: }
4644: }
4645: if (keys(%{$allgroups{$cid}}) == 0) {
4646: if (grep/^none$/,@groups) {
4647: return 'ok';
4648: }
4649: } else {
4650: if (grep/^all$/,@groups) {
4651: return 'ok';
4652: }
4653: foreach my $group (keys(%{$allgroups{$cid}})) {
4654: if (grep/^$group$/,@groups) {
4655: return 'ok';
4656: }
4657: }
4658: }
4659: }
4660: }
4661: }
4662: }
4663: }
4664: if ($guest) {
4665: return $guest;
4666: }
4667: }
4668: }
4669: return;
4670: }
4671:
4672: sub course_group_datechecker {
4673: my ($dates,$now,$status) = @_;
4674: my ($start,$end) = split(/\./,$dates);
4675: if (!$start && !$end) {
4676: return 'ok';
4677: }
4678: if (grep/^active$/,@{$status}) {
4679: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4680: return 'ok';
4681: }
4682: }
4683: if (grep/^previous$/,@{$status}) {
4684: if ($end > $now ) {
4685: return 'ok';
4686: }
4687: }
4688: if (grep/^future$/,@{$status}) {
4689: if ($start > $now) {
4690: return 'ok';
4691: }
4692: }
4693: return;
4694: }
4695:
4696: sub parse_portfolio_url {
4697: my ($url) = @_;
4698:
4699: my ($type,$udom,$unum,$group,$file_name);
4700:
4701: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
4702: $type = 1;
4703: $udom = $1;
4704: $unum = $2;
4705: $file_name = $3;
4706: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
4707: $type = 2;
4708: $udom = $1;
4709: $unum = $2;
4710: $group = $3;
4711: $file_name = $3.'/'.$4;
4712: }
4713: if (wantarray) {
4714: return ($type,$udom,$unum,$file_name,$group);
4715: }
4716: return $type;
4717: }
4718:
4719: sub is_portfolio_url {
4720: my ($url) = @_;
4721: return scalar(&parse_portfolio_url($url));
4722: }
4723:
4724: sub is_portfolio_file {
4725: my ($file) = @_;
4726: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
4727: return 1;
4728: }
4729: return;
4730: }
4731:
4732: sub usertools_access {
4733: my ($uname,$udom,$tool,$action,$context) = @_;
4734: my ($access,%tools);
4735: if ($context eq '') {
4736: $context = 'tools';
4737: }
4738: if ($context eq 'requestcourses') {
4739: %tools = (
4740: official => 1,
4741: unofficial => 1,
4742: community => 1,
4743: );
4744: } else {
4745: %tools = (
4746: aboutme => 1,
4747: blog => 1,
4748: portfolio => 1,
4749: );
4750: }
4751: return if (!defined($tools{$tool}));
4752:
4753: if ((!defined($udom)) || (!defined($uname))) {
4754: $udom = $env{'user.domain'};
4755: $uname = $env{'user.name'};
4756: }
4757:
4758: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4759: if ($action ne 'reload') {
4760: if ($context eq 'requestcourses') {
4761: return $env{'environment.canrequest.'.$tool};
4762: } else {
4763: return $env{'environment.availabletools.'.$tool};
4764: }
4765: }
4766: }
4767:
4768: my ($toolstatus,$inststatus);
4769:
4770: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4771: ($action ne 'reload')) {
4772: $toolstatus = $env{'environment.'.$context.'.'.$tool};
4773: $inststatus = $env{'environment.inststatus'};
4774: } else {
4775: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool);
4776: $toolstatus = $userenv{$context.'.'.$tool};
4777: $inststatus = $userenv{'inststatus'};
4778: }
4779:
4780: if ($toolstatus ne '') {
4781: if ($toolstatus) {
4782: $access = 1;
4783: } else {
4784: $access = 0;
4785: }
4786: return $access;
4787: }
4788:
4789: my $is_adv = &is_advanced_user($udom,$uname);
4790: my %domdef = &get_domain_defaults($udom);
4791: if (ref($domdef{$tool}) eq 'HASH') {
4792: if ($is_adv) {
4793: if ($domdef{$tool}{'_LC_adv'} ne '') {
4794: if ($domdef{$tool}{'_LC_adv'}) {
4795: $access = 1;
4796: } else {
4797: $access = 0;
4798: }
4799: return $access;
4800: }
4801: }
4802: if ($inststatus ne '') {
4803: my ($hasaccess,$hasnoaccess);
4804: foreach my $affiliation (split(/:/,$inststatus)) {
4805: if ($domdef{$tool}{$affiliation} ne '') {
4806: if ($domdef{$tool}{$affiliation}) {
4807: $hasaccess = 1;
4808: } else {
4809: $hasnoaccess = 1;
4810: }
4811: }
4812: }
4813: if ($hasaccess || $hasnoaccess) {
4814: if ($hasaccess) {
4815: $access = 1;
4816: } elsif ($hasnoaccess) {
4817: $access = 0;
4818: }
4819: return $access;
4820: }
4821: } else {
4822: if ($domdef{$tool}{'default'} ne '') {
4823: if ($domdef{$tool}{'default'}) {
4824: $access = 1;
4825: } elsif ($domdef{$tool}{'default'} == 0) {
4826: $access = 0;
4827: }
4828: return $access;
4829: }
4830: }
4831: } else {
4832: if ($context eq 'tools') {
4833: $access = 1;
4834: } else {
4835: $access = 0;
4836: }
4837: return $access;
4838: }
4839: }
4840:
4841: sub is_advanced_user {
4842: my ($udom,$uname) = @_;
4843: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4844: my %allroles;
4845: my $is_adv;
4846: foreach my $role (keys(%roleshash)) {
4847: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4848: my $area = '/'.$tdomain.'/'.$trest;
4849: if ($sec ne '') {
4850: $area .= '/'.$sec;
4851: }
4852: if (($area ne '') && ($trole ne '')) {
4853: my $spec=$trole.'.'.$area;
4854: if ($trole =~ /^cr\//) {
4855: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4856: } elsif ($trole ne 'gr') {
4857: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4858: }
4859: }
4860: }
4861: foreach my $role (keys(%allroles)) {
4862: last if ($is_adv);
4863: foreach my $item (split(/:/,$allroles{$role})) {
4864: if ($item ne '') {
4865: my ($privilege,$restrictions)=split(/&/,$item);
4866: if ($privilege eq 'adv') {
4867: $is_adv = 1;
4868: last;
4869: }
4870: }
4871: }
4872: }
4873: return $is_adv;
4874: }
4875:
4876: # ---------------------------------------------- Custom access rule evaluation
4877:
4878: sub customaccess {
4879: my ($priv,$uri)=@_;
4880: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
4881: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
4882: $udom = &LONCAPA::clean_domain($udom);
4883: $ucrs = &LONCAPA::clean_username($ucrs);
4884: my $access=0;
4885: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
4886: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4887: if ($type eq 'user') {
4888: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4889: my ($tdom,$tuname)=split(m{/},$scope);
4890: if ($tdom) {
4891: if ($tdom ne $env{'user.domain'}) { next; }
4892: }
4893: if ($tuname) {
4894: if ($tuname ne $env{'user.name'}) { next; }
4895: }
4896: $access=($effect eq 'allow');
4897: last;
4898: }
4899: } else {
4900: if ($role) {
4901: if ($role ne $urole) { next; }
4902: }
4903: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4904: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4905: if ($tdom) {
4906: if ($tdom ne $udom) { next; }
4907: }
4908: if ($tcrs) {
4909: if ($tcrs ne $ucrs) { next; }
4910: }
4911: if ($tsec) {
4912: if ($tsec ne $usec) { next; }
4913: }
4914: $access=($effect eq 'allow');
4915: last;
4916: }
4917: if ($realm eq '' && $role eq '') {
4918: $access=($effect eq 'allow');
4919: }
4920: }
4921: }
4922: return $access;
4923: }
4924:
4925: # ------------------------------------------------- Check for a user privilege
4926:
4927: sub allowed {
4928: my ($priv,$uri,$symb,$role)=@_;
4929: my $ver_orguri=$uri;
4930: $uri=&deversion($uri);
4931: my $orguri=$uri;
4932: $uri=&declutter($uri);
4933:
4934: if ($priv eq 'evb') {
4935: # Evade communication block restrictions for specified role in a course
4936: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4937: return $1;
4938: } else {
4939: return;
4940: }
4941: }
4942:
4943: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
4944: # Free bre access to adm and meta resources
4945: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
4946: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4947: && ($priv eq 'bre')) {
4948: return 'F';
4949: }
4950:
4951: # Free bre access to user's own portfolio contents
4952: my ($space,$domain,$name,@dir)=split('/',$uri);
4953: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
4954: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
4955: my %setters;
4956: my ($startblock,$endblock) =
4957: &Apache::loncommon::blockcheck(\%setters,'port');
4958: if ($startblock && $endblock) {
4959: return 'B';
4960: } else {
4961: return 'F';
4962: }
4963: }
4964:
4965: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
4966: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4967: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4968: if (exists($env{'request.course.id'})) {
4969: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4970: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4971: if (($domain eq $cdom) && ($name eq $cnum)) {
4972: my $courseprivid=$env{'request.course.id'};
4973: $courseprivid=~s/\_/\//;
4974: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4975: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4976: return $1;
4977: } else {
4978: if ($env{'request.course.sec'}) {
4979: $courseprivid.='/'.$env{'request.course.sec'};
4980: }
4981: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4982: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4983: return $2;
4984: }
4985: }
4986: }
4987: }
4988: }
4989:
4990: # Free bre to public access
4991:
4992: if ($priv eq 'bre') {
4993: my $copyright=&metadata($uri,'copyright');
4994: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
4995: return 'F';
4996: }
4997: if ($copyright eq 'priv') {
4998: $uri=~/([^\/]+)\/([^\/]+)\//;
4999: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
5000: return '';
5001: }
5002: }
5003: if ($copyright eq 'domain') {
5004: $uri=~/([^\/]+)\/([^\/]+)\//;
5005: unless (($env{'user.domain'} eq $1) ||
5006: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
5007: return '';
5008: }
5009: }
5010: if ($env{'request.role'}=~ /li\.\//) {
5011: # Library role, so allow browsing of resources in this domain.
5012: return 'F';
5013: }
5014: if ($copyright eq 'custom') {
5015: unless (&customaccess($priv,$uri)) { return ''; }
5016: }
5017: }
5018: # Domain coordinator is trying to create a course
5019: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
5020: # uri is the requested domain in this case.
5021: # comparison to 'request.role.domain' shows if the user has selected
5022: # a role of dc for the domain in question.
5023: return 'F' if ($uri eq $env{'request.role.domain'});
5024: }
5025:
5026: my $thisallowed='';
5027: my $statecond=0;
5028: my $courseprivid='';
5029:
5030: # Course
5031:
5032: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5033: $thisallowed.=$1;
5034: }
5035:
5036: # Domain
5037:
5038: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5039: =~/\Q$priv\E\&([^\:]*)/) {
5040: $thisallowed.=$1;
5041: }
5042:
5043: # Course: uri itself is a course
5044: my $courseuri=$uri;
5045: $courseuri=~s/\_(\d)/\/$1/;
5046: $courseuri=~s/^([^\/])/\/$1/;
5047:
5048: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5049: =~/\Q$priv\E\&([^\:]*)/) {
5050: $thisallowed.=$1;
5051: }
5052:
5053: # URI is an uploaded document for this course, default permissions don't matter
5054: # not allowing 'edit' access (editupload) to uploaded course docs
5055: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5056: $thisallowed='';
5057: my ($match)=&is_on_map($uri);
5058: if ($match) {
5059: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5060: =~/\Q$priv\E\&([^\:]*)/) {
5061: $thisallowed.=$1;
5062: }
5063: } else {
5064: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5065: if ($refuri) {
5066: if ($refuri =~ m|^/adm/|) {
5067: $thisallowed='F';
5068: } else {
5069: $refuri=&declutter($refuri);
5070: my ($match) = &is_on_map($refuri);
5071: if ($match) {
5072: $thisallowed='F';
5073: }
5074: }
5075: }
5076: }
5077: }
5078:
5079: if ($priv eq 'bre'
5080: && $thisallowed ne 'F'
5081: && $thisallowed ne '2'
5082: && &is_portfolio_url($uri)) {
5083: $thisallowed = &portfolio_access($uri);
5084: }
5085:
5086: # Full access at system, domain or course-wide level? Exit.
5087: if ($thisallowed=~/F/) {
5088: return 'F';
5089: }
5090:
5091: # If this is generating or modifying users, exit with special codes
5092:
5093: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5094: if (($priv eq 'cca') || ($priv eq 'caa')) {
5095: my ($audom,$auname)=split('/',$uri);
5096: # no author name given, so this just checks on the general right to make a co-author in this domain
5097: unless ($auname) { return $thisallowed; }
5098: # an author name is given, so we are about to actually make a co-author for a certain account
5099: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5100: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5101: ($audom ne $env{'request.role.domain'}))) { return ''; }
5102: }
5103: return $thisallowed;
5104: }
5105: #
5106: # Gathered so far: system, domain and course wide privileges
5107: #
5108: # Course: See if uri or referer is an individual resource that is part of
5109: # the course
5110:
5111: if ($env{'request.course.id'}) {
5112:
5113: $courseprivid=$env{'request.course.id'};
5114: if ($env{'request.course.sec'}) {
5115: $courseprivid.='/'.$env{'request.course.sec'};
5116: }
5117: $courseprivid=~s/\_/\//;
5118: my $checkreferer=1;
5119: my ($match,$cond)=&is_on_map($uri);
5120: if ($match) {
5121: $statecond=$cond;
5122: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5123: =~/\Q$priv\E\&([^\:]*)/) {
5124: $thisallowed.=$1;
5125: $checkreferer=0;
5126: }
5127: }
5128:
5129: if ($checkreferer) {
5130: my $refuri=$env{'httpref.'.$orguri};
5131: unless ($refuri) {
5132: foreach my $key (keys(%env)) {
5133: if ($key=~/^httpref\..*\*/) {
5134: my $pattern=$key;
5135: $pattern=~s/^httpref\.\/res\///;
5136: $pattern=~s/\*/\[\^\/\]\+/g;
5137: $pattern=~s/\//\\\//g;
5138: if ($orguri=~/$pattern/) {
5139: $refuri=$env{$key};
5140: }
5141: }
5142: }
5143: }
5144:
5145: if ($refuri) {
5146: $refuri=&declutter($refuri);
5147: my ($match,$cond)=&is_on_map($refuri);
5148: if ($match) {
5149: my $refstatecond=$cond;
5150: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5151: =~/\Q$priv\E\&([^\:]*)/) {
5152: $thisallowed.=$1;
5153: $uri=$refuri;
5154: $statecond=$refstatecond;
5155: }
5156: }
5157: }
5158: }
5159: }
5160:
5161: #
5162: # Gathered now: all privileges that could apply, and condition number
5163: #
5164: #
5165: # Full or no access?
5166: #
5167:
5168: if ($thisallowed=~/F/) {
5169: return 'F';
5170: }
5171:
5172: unless ($thisallowed) {
5173: return '';
5174: }
5175:
5176: # Restrictions exist, deal with them
5177: #
5178: # C:according to course preferences
5179: # R:according to resource settings
5180: # L:unless locked
5181: # X:according to user session state
5182: #
5183:
5184: # Possibly locked functionality, check all courses
5185: # Locks might take effect only after 10 minutes cache expiration for other
5186: # courses, and 2 minutes for current course
5187:
5188: my $envkey;
5189: if ($thisallowed=~/L/) {
5190: foreach $envkey (keys(%env)) {
5191: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5192: my $courseid=$2;
5193: my $roleid=$1.'.'.$2;
5194: $courseid=~s/^\///;
5195: my $expiretime=600;
5196: if ($env{'request.role'} eq $roleid) {
5197: $expiretime=120;
5198: }
5199: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5200: my $prefix='course.'.$cdom.'_'.$cnum.'.';
5201: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
5202: &coursedescription($courseid,{'freshen_cache' => 1});
5203: }
5204: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5205: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5206: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5207: &log($env{'user.domain'},$env{'user.name'},
5208: $env{'user.home'},
5209: 'Locked by res: '.$priv.' for '.$uri.' due to '.
5210: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5211: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5212: return '';
5213: }
5214: }
5215: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5216: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5217: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5218: &log($env{'user.domain'},$env{'user.name'},
5219: $env{'user.home'},
5220: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
5221: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5222: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5223: return '';
5224: }
5225: }
5226: }
5227: }
5228: }
5229:
5230: #
5231: # Rest of the restrictions depend on selected course
5232: #
5233:
5234: unless ($env{'request.course.id'}) {
5235: if ($thisallowed eq 'A') {
5236: return 'A';
5237: } elsif ($thisallowed eq 'B') {
5238: return 'B';
5239: } else {
5240: return '1';
5241: }
5242: }
5243:
5244: #
5245: # Now user is definitely in a course
5246: #
5247:
5248:
5249: # Course preferences
5250:
5251: if ($thisallowed=~/C/) {
5252: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5253: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5254: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
5255: =~/\Q$rolecode\E/) {
5256: if ($priv ne 'pch') {
5257: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5258: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5259: $env{'request.course.id'});
5260: }
5261: return '';
5262: }
5263:
5264: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
5265: =~/\Q$unamedom\E/) {
5266: if ($priv ne 'pch') {
5267: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5268: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5269: $env{'request.course.id'});
5270: }
5271: return '';
5272: }
5273: }
5274:
5275: # Resource preferences
5276:
5277: if ($thisallowed=~/R/) {
5278: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5279: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
5280: if ($priv ne 'pch') {
5281: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5282: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5283: }
5284: return '';
5285: }
5286: }
5287:
5288: # Restricted by state or randomout?
5289:
5290: if ($thisallowed=~/X/) {
5291: if ($env{'acc.randomout'}) {
5292: if (!$symb) { $symb=&symbread($uri,1); }
5293: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
5294: return '';
5295: }
5296: }
5297: if (&condval($statecond)) {
5298: return '2';
5299: } else {
5300: return '';
5301: }
5302: }
5303:
5304: if ($thisallowed eq 'A') {
5305: return 'A';
5306: } elsif ($thisallowed eq 'B') {
5307: return 'B';
5308: }
5309: return 'F';
5310: }
5311:
5312: sub split_uri_for_cond {
5313: my $uri=&deversion(&declutter(shift));
5314: my @uriparts=split(/\//,$uri);
5315: my $filename=pop(@uriparts);
5316: my $pathname=join('/',@uriparts);
5317: return ($pathname,$filename);
5318: }
5319: # --------------------------------------------------- Is a resource on the map?
5320:
5321: sub is_on_map {
5322: my ($pathname,$filename) = &split_uri_for_cond(shift);
5323: #Trying to find the conditional for the file
5324: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
5325: /\&\Q$filename\E\:([\d\|]+)\&/);
5326: if ($match) {
5327: return (1,$1);
5328: } else {
5329: return (0,0);
5330: }
5331: }
5332:
5333: # --------------------------------------------------------- Get symb from alias
5334:
5335: sub get_symb_from_alias {
5336: my $symb=shift;
5337: my ($map,$resid,$url)=&decode_symb($symb);
5338: # Already is a symb
5339: if ($url) { return $symb; }
5340: # Must be an alias
5341: my $aliassymb='';
5342: my %bighash;
5343: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5344: &GDBM_READER(),0640)) {
5345: my $rid=$bighash{'mapalias_'.$symb};
5346: if ($rid) {
5347: my ($mapid,$resid)=split(/\./,$rid);
5348: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5349: $resid,$bighash{'src_'.$rid});
5350: }
5351: untie %bighash;
5352: }
5353: return $aliassymb;
5354: }
5355:
5356: # ----------------------------------------------------------------- Define Role
5357:
5358: sub definerole {
5359: if (allowed('mcr','/')) {
5360: my ($rolename,$sysrole,$domrole,$courole)=@_;
5361: foreach my $role (split(':',$sysrole)) {
5362: my ($crole,$cqual)=split(/\&/,$role);
5363: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5364: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5365: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5366: return "refused:s:$crole&$cqual";
5367: }
5368: }
5369: }
5370: foreach my $role (split(':',$domrole)) {
5371: my ($crole,$cqual)=split(/\&/,$role);
5372: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5373: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5374: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
5375: return "refused:d:$crole&$cqual";
5376: }
5377: }
5378: }
5379: foreach my $role (split(':',$courole)) {
5380: my ($crole,$cqual)=split(/\&/,$role);
5381: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5382: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5383: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5384: return "refused:c:$crole&$cqual";
5385: }
5386: }
5387: }
5388: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5389: "$env{'user.domain'}:$env{'user.name'}:".
5390: "rolesdef_$rolename=".
5391: escape($sysrole.'_'.$domrole.'_'.$courole);
5392: return reply($command,$env{'user.home'});
5393: } else {
5394: return 'refused';
5395: }
5396: }
5397:
5398: # ---------------- Make a metadata query against the network of library servers
5399:
5400: sub metadata_query {
5401: my ($query,$custom,$customshow,$server_array)=@_;
5402: my %rhash;
5403: my %libserv = &all_library();
5404: my @server_list = (defined($server_array) ? @$server_array
5405: : keys(%libserv) );
5406: for my $server (@server_list) {
5407: unless ($custom or $customshow) {
5408: my $reply=&reply("querysend:".&escape($query),$server);
5409: $rhash{$server}=$reply;
5410: }
5411: else {
5412: my $reply=&reply("querysend:".&escape($query).':'.
5413: &escape($custom).':'.&escape($customshow),
5414: $server);
5415: $rhash{$server}=$reply;
5416: }
5417: }
5418: return \%rhash;
5419: }
5420:
5421: # ----------------------------------------- Send log queries and wait for reply
5422:
5423: sub log_query {
5424: my ($uname,$udom,$query,%filters)=@_;
5425: my $uhome=&homeserver($uname,$udom);
5426: if ($uhome eq 'no_host') { return 'error: no_host'; }
5427: my $uhost=&hostname($uhome);
5428: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
5429: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5430: $uhome);
5431: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
5432: return get_query_reply($queryid);
5433: }
5434:
5435: # -------------------------- Update MySQL table for portfolio file
5436:
5437: sub update_portfolio_table {
5438: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
5439: if ($group ne '') {
5440: $file_name =~s /^\Q$group\E//;
5441: }
5442: my $homeserver = &homeserver($uname,$udom);
5443: my $queryid=
5444: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5445: ':'.&escape($file_name).':'.$action,$homeserver);
5446: my $reply = &get_query_reply($queryid);
5447: return $reply;
5448: }
5449:
5450: # -------------------------- Update MySQL allusers table
5451:
5452: sub update_allusers_table {
5453: my ($uname,$udom,$names) = @_;
5454: my $homeserver = &homeserver($uname,$udom);
5455: my $queryid=
5456: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5457: 'lastname='.&escape($names->{'lastname'}).'%%'.
5458: 'firstname='.&escape($names->{'firstname'}).'%%'.
5459: 'middlename='.&escape($names->{'middlename'}).'%%'.
5460: 'generation='.&escape($names->{'generation'}).'%%'.
5461: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5462: 'id='.&escape($names->{'id'}),$homeserver);
5463: my $reply = &get_query_reply($queryid);
5464: return $reply;
5465: }
5466:
5467: # ------- Request retrieval of institutional classlists for course(s)
5468:
5469: sub fetch_enrollment_query {
5470: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
5471: my $homeserver;
5472: my $maxtries = 1;
5473: if ($context eq 'automated') {
5474: $homeserver = $perlvar{'lonHostID'};
5475: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
5476: } else {
5477: $homeserver = &homeserver($cnum,$dom);
5478: }
5479: my $host=&hostname($homeserver);
5480: my $cmd = '';
5481: foreach my $affiliate (keys(%{$affiliatesref})) {
5482: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5483: }
5484: $cmd =~ s/%%$//;
5485: $cmd = &escape($cmd);
5486: my $query = 'fetchenrollment';
5487: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
5488: unless ($queryid=~/^\Q$host\E\_/) {
5489: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5490: return 'error: '.$queryid;
5491: }
5492: my $reply = &get_query_reply($queryid);
5493: my $tries = 1;
5494: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5495: $reply = &get_query_reply($queryid);
5496: $tries ++;
5497: }
5498: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5499: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5500: } else {
5501: my @responses = split(/:/,$reply);
5502: if ($homeserver eq $perlvar{'lonHostID'}) {
5503: foreach my $line (@responses) {
5504: my ($key,$value) = split(/=/,$line,2);
5505: $$replyref{$key} = $value;
5506: }
5507: } else {
5508: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
5509: foreach my $line (@responses) {
5510: my ($key,$value) = split(/=/,$line);
5511: $$replyref{$key} = $value;
5512: if ($value > 0) {
5513: foreach my $item (@{$$affiliatesref{$key}}) {
5514: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
5515: my $destname = $pathname.'/'.$filename;
5516: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
5517: if ($xml_classlist =~ /^error/) {
5518: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5519: } else {
5520: if ( open(FILE,">$destname") ) {
5521: print FILE &unescape($xml_classlist);
5522: close(FILE);
5523: } else {
5524: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
5525: }
5526: }
5527: }
5528: }
5529: }
5530: }
5531: return 'ok';
5532: }
5533: return 'error';
5534: }
5535:
5536: sub get_query_reply {
5537: my $queryid=shift;
5538: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5539: my $reply='';
5540: for (1..100) {
5541: sleep 2;
5542: if (-e $replyfile.'.end') {
5543: if (open(my $fh,$replyfile)) {
5544: $reply = join('',<$fh>);
5545: close($fh);
5546: } else { return 'error: reply_file_error'; }
5547: return &unescape($reply);
5548: }
5549: }
5550: return 'timeout:'.$queryid;
5551: }
5552:
5553: sub courselog_query {
5554: #
5555: # possible filters:
5556: # url: url or symb
5557: # username
5558: # domain
5559: # action: view, submit, grade
5560: # start: timestamp
5561: # end: timestamp
5562: #
5563: my (%filters)=@_;
5564: unless ($env{'request.course.id'}) { return 'no_course'; }
5565: if ($filters{'url'}) {
5566: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5567: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5568: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5569: }
5570: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5571: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5572: return &log_query($cname,$cdom,'courselog',%filters);
5573: }
5574:
5575: sub userlog_query {
5576: #
5577: # possible filters:
5578: # action: log check role
5579: # start: timestamp
5580: # end: timestamp
5581: #
5582: my ($uname,$udom,%filters)=@_;
5583: return &log_query($uname,$udom,'userlog',%filters);
5584: }
5585:
5586: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5587:
5588: sub auto_run {
5589: my ($cnum,$cdom) = @_;
5590: my $response = 0;
5591: my $settings;
5592: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5593: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5594: $settings = $domconfig{'autoenroll'};
5595: if ($settings->{'run'} eq '1') {
5596: $response = 1;
5597: }
5598: } else {
5599: my $homeserver;
5600: if (&is_course($cdom,$cnum)) {
5601: $homeserver = &homeserver($cnum,$cdom);
5602: } else {
5603: $homeserver = &domain($cdom,'primary');
5604: }
5605: if ($homeserver ne 'no_host') {
5606: $response = &reply('autorun:'.$cdom,$homeserver);
5607: }
5608: }
5609: return $response;
5610: }
5611:
5612: sub auto_get_sections {
5613: my ($cnum,$cdom,$inst_coursecode) = @_;
5614: my $homeserver;
5615: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5616: $homeserver = &homeserver($cnum,$cdom);
5617: }
5618: if (!defined($homeserver)) {
5619: if ($cdom =~ /^$match_domain$/) {
5620: $homeserver = &domain($cdom,'primary');
5621: }
5622: }
5623: my @secs;
5624: if (defined($homeserver)) {
5625: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5626: unless ($response eq 'refused') {
5627: @secs = split(/:/,$response);
5628: }
5629: }
5630: return @secs;
5631: }
5632:
5633: sub auto_new_course {
5634: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5635: my $homeserver = &homeserver($cnum,$cdom);
5636: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
5637: return $response;
5638: }
5639:
5640: sub auto_validate_courseID {
5641: my ($cnum,$cdom,$inst_course_id) = @_;
5642: my $homeserver = &homeserver($cnum,$cdom);
5643: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
5644: return $response;
5645: }
5646:
5647: sub auto_validate_instcode {
5648: my ($cnum,$cdom,$instcode,$owner) = @_;
5649: my ($homeserver,$response);
5650: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5651: $homeserver = &homeserver($cnum,$cdom);
5652: }
5653: if (!defined($homeserver)) {
5654: if ($cdom =~ /^$match_domain$/) {
5655: $homeserver = &domain($cdom,'primary');
5656: }
5657: }
5658: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5659: &escape($instcode).':'.&escape($owner),$homeserver));
5660: return $response;
5661: }
5662:
5663: sub auto_create_password {
5664: my ($cnum,$cdom,$authparam,$udom) = @_;
5665: my ($homeserver,$response);
5666: my $create_passwd = 0;
5667: my $authchk = '';
5668: if ($udom =~ /^$match_domain$/) {
5669: $homeserver = &domain($udom,'primary');
5670: }
5671: if ($homeserver eq '') {
5672: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5673: $homeserver = &homeserver($cnum,$cdom);
5674: }
5675: }
5676: if ($homeserver eq '') {
5677: $authchk = 'nodomain';
5678: } else {
5679: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5680: if ($response eq 'refused') {
5681: $authchk = 'refused';
5682: } else {
5683: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
5684: }
5685: }
5686: return ($authparam,$create_passwd,$authchk);
5687: }
5688:
5689: sub auto_photo_permission {
5690: my ($cnum,$cdom,$students) = @_;
5691: my $homeserver = &homeserver($cnum,$cdom);
5692: my ($outcome,$perm_reqd,$conditions) =
5693: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
5694: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5695: return (undef,undef);
5696: }
5697: return ($outcome,$perm_reqd,$conditions);
5698: }
5699:
5700: sub auto_checkphotos {
5701: my ($uname,$udom,$pid) = @_;
5702: my $homeserver = &homeserver($uname,$udom);
5703: my ($result,$resulttype);
5704: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
5705: &escape($uname).':'.&escape($pid),
5706: $homeserver));
5707: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5708: return (undef,undef);
5709: }
5710: if ($outcome) {
5711: ($result,$resulttype) = split(/:/,$outcome);
5712: }
5713: return ($result,$resulttype);
5714: }
5715:
5716: sub auto_photochoice {
5717: my ($cnum,$cdom) = @_;
5718: my $homeserver = &homeserver($cnum,$cdom);
5719: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
5720: &escape($cdom),
5721: $homeserver)));
5722: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5723: return (undef,undef);
5724: }
5725: return ($update,$comment);
5726: }
5727:
5728: sub auto_photoupdate {
5729: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5730: my $homeserver = &homeserver($cnum,$dom);
5731: my $host=&hostname($homeserver);
5732: my $cmd = '';
5733: my $maxtries = 1;
5734: foreach my $affiliate (keys(%{$affiliatesref})) {
5735: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5736: }
5737: $cmd =~ s/%%$//;
5738: $cmd = &escape($cmd);
5739: my $query = 'institutionalphotos';
5740: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5741: unless ($queryid=~/^\Q$host\E\_/) {
5742: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5743: return 'error: '.$queryid;
5744: }
5745: my $reply = &get_query_reply($queryid);
5746: my $tries = 1;
5747: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5748: $reply = &get_query_reply($queryid);
5749: $tries ++;
5750: }
5751: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5752: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5753: } else {
5754: my @responses = split(/:/,$reply);
5755: my $outcome = shift(@responses);
5756: foreach my $item (@responses) {
5757: my ($key,$value) = split(/=/,$item);
5758: $$photo{$key} = $value;
5759: }
5760: return $outcome;
5761: }
5762: return 'error';
5763: }
5764:
5765: sub auto_instcode_format {
5766: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5767: $cat_order) = @_;
5768: my $courses = '';
5769: my @homeservers;
5770: if ($caller eq 'global') {
5771: my %servers = &get_servers($codedom,'library');
5772: foreach my $tryserver (keys(%servers)) {
5773: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5774: push(@homeservers,$tryserver);
5775: }
5776: }
5777: } elsif ($caller eq 'requests') {
5778: if ($codedom =~ /^$match_domain$/) {
5779: my $chome = &domain($codedom,'primary');
5780: unless ($chome eq 'no_host') {
5781: push(@homeservers,$chome);
5782: }
5783: }
5784: } else {
5785: push(@homeservers,&homeserver($caller,$codedom));
5786: }
5787: foreach my $code (keys(%{$instcodes})) {
5788: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
5789: }
5790: chop($courses);
5791: my $ok_response = 0;
5792: my $response;
5793: while (@homeservers > 0 && $ok_response == 0) {
5794: my $server = shift(@homeservers);
5795: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5796: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5797: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
5798: split(/:/,$response);
5799: %{$codes} = (%{$codes},&str2hash($codes_str));
5800: push(@{$codetitles},&str2array($codetitles_str));
5801: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5802: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5803: $ok_response = 1;
5804: }
5805: }
5806: if ($ok_response) {
5807: return 'ok';
5808: } else {
5809: return $response;
5810: }
5811: }
5812:
5813: sub auto_instcode_defaults {
5814: my ($domain,$returnhash,$code_order) = @_;
5815: my @homeservers;
5816:
5817: my %servers = &get_servers($domain,'library');
5818: foreach my $tryserver (keys(%servers)) {
5819: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5820: push(@homeservers,$tryserver);
5821: }
5822: }
5823:
5824: my $response;
5825: foreach my $server (@homeservers) {
5826: $response=&reply('autoinstcodedefaults:'.$domain,$server);
5827: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5828:
5829: foreach my $pair (split(/\&/,$response)) {
5830: my ($name,$value)=split(/\=/,$pair);
5831: if ($name eq 'code_order') {
5832: @{$code_order} = split(/\&/,&unescape($value));
5833: } else {
5834: $returnhash->{&unescape($name)}=&unescape($value);
5835: }
5836: }
5837: return 'ok';
5838: }
5839:
5840: return $response;
5841: }
5842:
5843: sub auto_possible_instcodes {
5844: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5845: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5846: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5847: return;
5848: }
5849: my (@homeservers,$uhome);
5850: if (defined(&domain($domain,'primary'))) {
5851: $uhome=&domain($domain,'primary');
5852: push(@homeservers,&domain($domain,'primary'));
5853: } else {
5854: my %servers = &get_servers($domain,'library');
5855: foreach my $tryserver (keys(%servers)) {
5856: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5857: push(@homeservers,$tryserver);
5858: }
5859: }
5860: }
5861: my $response;
5862: foreach my $server (@homeservers) {
5863: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5864: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5865: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5866: split(':',$response);
5867: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5868: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
5869: foreach my $item (split('&',$cat_title)) {
5870: my ($name,$value)=split('=',$item);
5871: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
5872: }
5873: foreach my $item (split('&',$cat_order)) {
5874: my ($name,$value)=split('=',$item);
5875: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
5876: }
5877: return 'ok';
5878: }
5879: return $response;
5880: }
5881:
5882: sub auto_courserequest_checks {
5883: my ($dom) = @_;
5884: my ($homeserver,%validations);
5885: if ($dom =~ /^$match_domain$/) {
5886: $homeserver = &domain($dom,'primary');
5887: }
5888: unless ($homeserver eq 'no_host') {
5889: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5890: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5891: my @items = split(/&/,$response);
5892: foreach my $item (@items) {
5893: my ($key,$value) = split('=',$item);
5894: $validations{&unescape($key)} = &thaw_unescape($value);
5895: }
5896: }
5897: }
5898: return %validations;
5899: }
5900:
5901: sub auto_courserequest_validation {
5902: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5903: my ($homeserver,$response);
5904: if ($dom =~ /^$match_domain$/) {
5905: $homeserver = &domain($dom,'primary');
5906: }
5907: unless ($homeserver eq 'no_host') {
5908:
5909: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
5910: ':'.&escape($crstype).':'.&escape($inststatuslist).
5911: ':'.&escape($instcode).':'.&escape($instseclist),
5912: $homeserver));
5913: }
5914: return $response;
5915: }
5916:
5917: sub auto_validate_class_sec {
5918: my ($cdom,$cnum,$owners,$inst_class) = @_;
5919: my $homeserver = &homeserver($cnum,$cdom);
5920: my $ownerlist;
5921: if (ref($owners) eq 'ARRAY') {
5922: $ownerlist = join(',',@{$owners});
5923: } else {
5924: $ownerlist = $owners;
5925: }
5926: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
5927: &escape($ownerlist).':'.$cdom,$homeserver);
5928: return $response;
5929: }
5930:
5931: # ------------------------------------------------------- Course Group routines
5932:
5933: sub get_coursegroups {
5934: my ($cdom,$cnum,$group,$namespace) = @_;
5935: return(&dump($namespace,$cdom,$cnum,$group));
5936: }
5937:
5938: sub modify_coursegroup {
5939: my ($cdom,$cnum,$groupsettings) = @_;
5940: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5941: }
5942:
5943: sub toggle_coursegroup_status {
5944: my ($cdom,$cnum,$group,$action) = @_;
5945: my ($from_namespace,$to_namespace);
5946: if ($action eq 'delete') {
5947: $from_namespace = 'coursegroups';
5948: $to_namespace = 'deleted_groups';
5949: } else {
5950: $from_namespace = 'deleted_groups';
5951: $to_namespace = 'coursegroups';
5952: }
5953: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
5954: if (my $tmp = &error(%curr_group)) {
5955: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5956: return ('read error',$tmp);
5957: } else {
5958: my %savedsettings = %curr_group;
5959: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
5960: my $deloutcome;
5961: if ($result eq 'ok') {
5962: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
5963: } else {
5964: return ('write error',$result);
5965: }
5966: if ($deloutcome eq 'ok') {
5967: return 'ok';
5968: } else {
5969: return ('delete error',$deloutcome);
5970: }
5971: }
5972: }
5973:
5974: sub modify_group_roles {
5975: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
5976: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5977: my $role = 'gr/'.&escape($userprivs);
5978: my ($uname,$udom) = split(/:/,$user);
5979: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
5980: if ($result eq 'ok') {
5981: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5982: }
5983: return $result;
5984: }
5985:
5986: sub modify_coursegroup_membership {
5987: my ($cdom,$cnum,$membership) = @_;
5988: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5989: return $result;
5990: }
5991:
5992: sub get_active_groups {
5993: my ($udom,$uname,$cdom,$cnum) = @_;
5994: my $now = time;
5995: my %groups = ();
5996: foreach my $key (keys(%env)) {
5997: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
5998: my ($start,$end) = split(/\./,$env{$key});
5999: if (($end!=0) && ($end<$now)) { next; }
6000: if (($start!=0) && ($start>$now)) { next; }
6001: if ($1 eq $cdom && $2 eq $cnum) {
6002: $groups{$3} = $env{$key} ;
6003: }
6004: }
6005: }
6006: return %groups;
6007: }
6008:
6009: sub get_group_membership {
6010: my ($cdom,$cnum,$group) = @_;
6011: return(&dump('groupmembership',$cdom,$cnum,$group));
6012: }
6013:
6014: sub get_users_groups {
6015: my ($udom,$uname,$courseid) = @_;
6016: my @usersgroups;
6017: my $cachetime=1800;
6018:
6019: my $hashid="$udom:$uname:$courseid";
6020: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6021: if (defined($cached)) {
6022: @usersgroups = split(/:/,$grouplist);
6023: } else {
6024: $grouplist = '';
6025: my $courseurl = &courseid_to_courseurl($courseid);
6026: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
6027: my $access_end = $env{'course.'.$courseid.
6028: '.default_enrollment_end_date'};
6029: my $now = time;
6030: foreach my $key (keys(%roleshash)) {
6031: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6032: my $group = $1;
6033: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6034: my $start = $2;
6035: my $end = $1;
6036: if ($start == -1) { next; } # deleted from group
6037: if (($start!=0) && ($start>$now)) { next; }
6038: if (($end!=0) && ($end<$now)) {
6039: if ($access_end && $access_end < $now) {
6040: if ($access_end - $end < 86400) {
6041: push(@usersgroups,$group);
6042: }
6043: }
6044: next;
6045: }
6046: push(@usersgroups,$group);
6047: }
6048: }
6049: }
6050: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6051: $grouplist = join(':',@usersgroups);
6052: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6053: }
6054: return @usersgroups;
6055: }
6056:
6057: sub devalidate_getgroups_cache {
6058: my ($udom,$uname,$cdom,$cnum)=@_;
6059: my $courseid = $cdom.'_'.$cnum;
6060:
6061: my $hashid="$udom:$uname:$courseid";
6062: &devalidate_cache_new('getgroups',$hashid);
6063: }
6064:
6065: # ------------------------------------------------------------------ Plain Text
6066:
6067: sub plaintext {
6068: my ($short,$type,$cid,$forcedefault) = @_;
6069: if ($short =~ /^cr/) {
6070: return (split('/',$short))[-1];
6071: }
6072: if (!defined($cid)) {
6073: $cid = $env{'request.course.id'};
6074: }
6075: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
6076: unless ($forcedefault) {
6077: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6078: &Apache::lonlocal::mt_escape(\$roletext);
6079: return &Apache::lonlocal::mt($roletext);
6080: }
6081: }
6082: my %rolenames = (
6083: Course => 'std',
6084: Community => 'alt1',
6085: );
6086: if (defined($type) &&
6087: defined($rolenames{$type}) &&
6088: defined($prp{$short}{$rolenames{$type}})) {
6089: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6090: } else {
6091: return &Apache::lonlocal::mt($prp{$short}{'std'});
6092: }
6093: }
6094:
6095: # ----------------------------------------------------------------- Assign Role
6096:
6097: sub assignrole {
6098: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6099: $context)=@_;
6100: my $mrole;
6101: if ($role =~ /^cr\//) {
6102: my $cwosec=$url;
6103: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6104: unless (&allowed('ccr',$cwosec)) {
6105: &logthis('Refused custom assignrole: '.
6106: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6107: $env{'user.name'}.' at '.$env{'user.domain'});
6108: return 'refused';
6109: }
6110: $mrole='cr';
6111: } elsif ($role =~ /^gr\//) {
6112: my $cwogrp=$url;
6113: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
6114: unless (&allowed('mdg',$cwogrp)) {
6115: &logthis('Refused group assignrole: '.
6116: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6117: $env{'user.name'}.' at '.$env{'user.domain'});
6118: return 'refused';
6119: }
6120: $mrole='gr';
6121: } else {
6122: my $cwosec=$url;
6123: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6124: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6125: my $refused;
6126: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6127: if (!(&allowed('c'.$role,$url))) {
6128: $refused = 1;
6129: }
6130: } else {
6131: $refused = 1;
6132: }
6133: if ($refused) {
6134: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6135: $refused = '';
6136: } elsif ($context eq 'requestcourses') {
6137: if (($role eq 'cc') && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
6138: my ($cdom,$cnum) = ($cwosec =~ m{^/($match_domain)/($match_courseid)$});
6139: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6140: if ($crsenv{'internal.courseowner'} eq
6141: $env{'user.name'}.':'.$env{'user.domain'}) {
6142: $refused = '';
6143: }
6144: }
6145: }
6146: if ($refused) {
6147: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6148: ' '.$role.' '.$end.' '.$start.' by '.
6149: $env{'user.name'}.' at '.$env{'user.domain'});
6150: return 'refused';
6151: }
6152: }
6153: }
6154: $mrole=$role;
6155: }
6156: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6157: "$udom:$uname:$url".'_'."$mrole=$role";
6158: if ($end) { $command.='_'.$end; }
6159: if ($start) {
6160: if ($end) {
6161: $command.='_'.$start;
6162: } else {
6163: $command.='_0_'.$start;
6164: }
6165: }
6166: my $origstart = $start;
6167: my $origend = $end;
6168: my $delflag;
6169: # actually delete
6170: if ($deleteflag) {
6171: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
6172: # modify command to delete the role
6173: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
6174: "$udom:$uname:$url".'_'."$mrole";
6175: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
6176: # set start and finish to negative values for userrolelog
6177: $start=-1;
6178: $end=-1;
6179: $delflag = 1;
6180: }
6181: }
6182: # send command
6183: my $answer=&reply($command,&homeserver($uname,$udom));
6184: # log new user role if status is ok
6185: if ($answer eq 'ok') {
6186: &userrolelog($role,$uname,$udom,$url,$start,$end);
6187: # for course roles, perform group memberships changes triggered by role change.
6188: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
6189: unless ($role =~ /^gr/) {
6190: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
6191: $origstart,$selfenroll,$context);
6192: }
6193: }
6194: return $answer;
6195: }
6196:
6197: # -------------------------------------------------- Modify user authentication
6198: # Overrides without validation
6199:
6200: sub modifyuserauth {
6201: my ($udom,$uname,$umode,$upass)=@_;
6202: my $uhome=&homeserver($uname,$udom);
6203: unless (&allowed('mau',$udom)) { return 'refused'; }
6204: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
6205: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6206: ' in domain '.$env{'request.role.domain'});
6207: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6208: &escape($upass),$uhome);
6209: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
6210: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6211: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6212: &log($udom,,$uname,$uhome,
6213: 'Authentication changed by '.$env{'user.domain'}.', '.
6214: $env{'user.name'}.', '.$umode.
6215: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6216: unless ($reply eq 'ok') {
6217: &logthis('Authentication mode error: '.$reply);
6218: return 'error: '.$reply;
6219: }
6220: return 'ok';
6221: }
6222:
6223: # --------------------------------------------------------------- Modify a user
6224:
6225: sub modifyuser {
6226: my ($udom, $uname, $uid,
6227: $umode, $upass, $first,
6228: $middle, $last, $gene,
6229: $forceid, $desiredhome, $email, $inststatus)=@_;
6230: $udom= &LONCAPA::clean_domain($udom);
6231: $uname=&LONCAPA::clean_username($uname);
6232: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
6233: $umode.', '.$first.', '.$middle.', '.
6234: $last.', '.$gene.'(forceid: '.$forceid.')'.
6235: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6236: ' desiredhome not specified').
6237: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6238: ' in domain '.$env{'request.role.domain'});
6239: my $uhome=&homeserver($uname,$udom,'true');
6240: # ----------------------------------------------------------------- Create User
6241: if (($uhome eq 'no_host') &&
6242: (($umode && $upass) || ($umode eq 'localauth'))) {
6243: my $unhome='';
6244: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
6245: $unhome = $desiredhome;
6246: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6247: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
6248: } else { # load balancing routine for determining $unhome
6249: my $loadm=10000000;
6250: my %servers = &get_servers($udom,'library');
6251: foreach my $tryserver (keys(%servers)) {
6252: my $answer=reply('load',$tryserver);
6253: if (($answer=~/\d+/) && ($answer<$loadm)) {
6254: $loadm=$answer;
6255: $unhome=$tryserver;
6256: }
6257: }
6258: }
6259: if (($unhome eq '') || ($unhome eq 'no_host')) {
6260: return 'error: unable to find a home server for '.$uname.
6261: ' in domain '.$udom;
6262: }
6263: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6264: &escape($upass),$unhome);
6265: unless ($reply eq 'ok') {
6266: return 'error: '.$reply;
6267: }
6268: $uhome=&homeserver($uname,$udom,'true');
6269: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
6270: return 'error: unable verify users home machine.';
6271: }
6272: } # End of creation of new user
6273: # ---------------------------------------------------------------------- Add ID
6274: if ($uid) {
6275: $uid=~tr/A-Z/a-z/;
6276: my %uidhash=&idrget($udom,$uname);
6277: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6278: && (!$forceid)) {
6279: unless ($uid eq $uidhash{$uname}) {
6280: return 'error: user id "'.$uid.'" does not match '.
6281: 'current user id "'.$uidhash{$uname}.'".';
6282: }
6283: } else {
6284: &idput($udom,($uname => $uid));
6285: }
6286: }
6287: # -------------------------------------------------------------- Add names, etc
6288: my @tmp=&get('environment',
6289: ['firstname','middlename','lastname','generation','id',
6290: 'permanentemail','inststatus'],
6291: $udom,$uname);
6292: my %names;
6293: if ($tmp[0] =~ m/^error:.*/) {
6294: %names=();
6295: } else {
6296: %names = @tmp;
6297: }
6298: #
6299: # Make sure to not trash student environment if instructor does not bother
6300: # to supply name and email information
6301: #
6302: if ($first) { $names{'firstname'} = $first; }
6303: if (defined($middle)) { $names{'middlename'} = $middle; }
6304: if ($last) { $names{'lastname'} = $last; }
6305: if (defined($gene)) { $names{'generation'} = $gene; }
6306: if ($email) {
6307: $email=~s/[^\w\@\.\-\,]//gs;
6308: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
6309: }
6310: if ($uid) { $names{'id'} = $uid; }
6311: if (defined($inststatus)) {
6312: $names{'inststatus'} = '';
6313: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6314: if (ref($usertypes) eq 'HASH') {
6315: my @okstatuses;
6316: foreach my $item (split(/:/,$inststatus)) {
6317: if (defined($usertypes->{$item})) {
6318: push(@okstatuses,$item);
6319: }
6320: }
6321: if (@okstatuses) {
6322: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6323: }
6324: }
6325: }
6326: my $reply = &put('environment', \%names, $udom,$uname);
6327: if ($reply ne 'ok') { return 'error: '.$reply; }
6328: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6329: &devalidate_cache_new('namescache',$uname.':'.$udom);
6330: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6331: $umode.', '.$first.', '.$middle.', '.
6332: $last.', '.$gene.', '.$email.', '.$inststatus;
6333: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6334: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6335: } else {
6336: $logmsg .= ' during self creation';
6337: }
6338: &logthis($logmsg);
6339: return 'ok';
6340: }
6341:
6342: # -------------------------------------------------------------- Modify student
6343:
6344: sub modifystudent {
6345: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
6346: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
6347: $selfenroll,$context,$inststatus)=@_;
6348: if (!$cid) {
6349: unless ($cid=$env{'request.course.id'}) {
6350: return 'not_in_class';
6351: }
6352: }
6353: # --------------------------------------------------------------- Make the user
6354: my $reply=&modifyuser
6355: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
6356: $desiredhome,$email,$inststatus);
6357: unless ($reply eq 'ok') { return $reply; }
6358: # This will cause &modify_student_enrollment to get the uid from the
6359: # students environment
6360: $uid = undef if (!$forceid);
6361: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
6362: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
6363: return $reply;
6364: }
6365:
6366: sub modify_student_enrollment {
6367: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
6368: my ($cdom,$cnum,$chome);
6369: if (!$cid) {
6370: unless ($cid=$env{'request.course.id'}) {
6371: return 'not_in_class';
6372: }
6373: $cdom=$env{'course.'.$cid.'.domain'};
6374: $cnum=$env{'course.'.$cid.'.num'};
6375: } else {
6376: ($cdom,$cnum)=split(/_/,$cid);
6377: }
6378: $chome=$env{'course.'.$cid.'.home'};
6379: if (!$chome) {
6380: $chome=&homeserver($cnum,$cdom);
6381: }
6382: if (!$chome) { return 'unknown_course'; }
6383: # Make sure the user exists
6384: my $uhome=&homeserver($uname,$udom);
6385: if (($uhome eq '') || ($uhome eq 'no_host')) {
6386: return 'error: no such user';
6387: }
6388: # Get student data if we were not given enough information
6389: if (!defined($first) || $first eq '' ||
6390: !defined($last) || $last eq '' ||
6391: !defined($uid) || $uid eq '' ||
6392: !defined($middle) || $middle eq '' ||
6393: !defined($gene) || $gene eq '') {
6394: # They did not supply us with enough data to enroll the student, so
6395: # we need to pick up more information.
6396: my %tmp = &get('environment',
6397: ['firstname','middlename','lastname', 'generation','id']
6398: ,$udom,$uname);
6399:
6400: #foreach my $key (keys(%tmp)) {
6401: # &logthis("key $key = ".$tmp{$key});
6402: #}
6403: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6404: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6405: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
6406: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
6407: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6408: }
6409: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
6410: my $reply=cput('classlist',
6411: {"$uname:$udom" =>
6412: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
6413: $cdom,$cnum);
6414: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6415: return 'error: '.$reply;
6416: } else {
6417: &devalidate_getsection_cache($udom,$uname,$cid);
6418: }
6419: # Add student role to user
6420: my $uurl='/'.$cid;
6421: $uurl=~s/\_/\//g;
6422: if ($usec) {
6423: $uurl.='/'.$usec;
6424: }
6425: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
6426: }
6427:
6428: sub format_name {
6429: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6430: my $name;
6431: if ($first ne 'lastname') {
6432: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6433: } else {
6434: if ($lastname=~/\S/) {
6435: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6436: $name=~s/\s+,/,/;
6437: } else {
6438: $name.= $firstname.' '.$middlename.' '.$generation;
6439: }
6440: }
6441: $name=~s/^\s+//;
6442: $name=~s/\s+$//;
6443: $name=~s/\s+/ /g;
6444: return $name;
6445: }
6446:
6447: # ------------------------------------------------- Write to course preferences
6448:
6449: sub writecoursepref {
6450: my ($courseid,%prefs)=@_;
6451: $courseid=~s/^\///;
6452: $courseid=~s/\_/\//g;
6453: my ($cdomain,$cnum)=split(/\//,$courseid);
6454: my $chome=homeserver($cnum,$cdomain);
6455: if (($chome eq '') || ($chome eq 'no_host')) {
6456: return 'error: no such course';
6457: }
6458: my $cstring='';
6459: foreach my $pref (keys(%prefs)) {
6460: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
6461: }
6462: $cstring=~s/\&$//;
6463: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6464: }
6465:
6466: # ---------------------------------------------------------- Make/modify course
6467:
6468: sub createcourse {
6469: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6470: $course_owner,$crstype,$cnum,$context,$category)=@_;
6471: $url=&declutter($url);
6472: my $cid='';
6473: unless (&allowed('ccc',$udom)) {
6474: if ($context eq 'requestcourses') {
6475: unless (&usertools_access($course_owner,$udom,$category,undef,$context)) {
6476: return 'refused';
6477: }
6478: } else {
6479: return 'refused';
6480: }
6481: }
6482: # --------------------------------------------------------------- Get Unique ID
6483: my $uname;
6484: if ($cnum =~ /^$match_courseid$/) {
6485: my $chome=&homeserver($cnum,$udom,'true');
6486: if (($chome eq '') || ($chome eq 'no_host')) {
6487: $uname = $cnum;
6488: } else {
6489: $uname = &generate_coursenum($udom);
6490: }
6491: } else {
6492: $uname = &generate_coursenum($udom);
6493: }
6494: return $uname if ($uname =~ /^error/);
6495: # -------------------------------------------------- Check supplied server name
6496: $course_server = $env{'user.homeserver'} if (! defined($course_server));
6497: if (! &is_library($course_server)) {
6498: return 'error:bad server name '.$course_server;
6499: }
6500: # ------------------------------------------------------------- Make the course
6501: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
6502: $course_server);
6503: unless ($reply eq 'ok') { return 'error: '.$reply; }
6504: my $uhome=&homeserver($uname,$udom,'true');
6505: if (($uhome eq '') || ($uhome eq 'no_host')) {
6506: return 'error: no such course';
6507: }
6508: # ----------------------------------------------------------------- Course made
6509: # log existence
6510: my $newcourse = {
6511: $udom.'_'.$uname => {
6512: description => $description,
6513: inst_code => $inst_code,
6514: owner => $course_owner,
6515: type => $crstype,
6516: },
6517: };
6518: &courseidput($udom,$newcourse,$uhome,'notime');
6519: # set toplevel url
6520: my $topurl=$url;
6521: unless ($nonstandard) {
6522: # ------------------------------------------ For standard courses, make top url
6523: my $mapurl=&clutter($url);
6524: if ($mapurl eq '/res/') { $mapurl=''; }
6525: $env{'form.initmap'}=(<<ENDINITMAP);
6526: <map>
6527: <resource id="1" type="start"></resource>
6528: <resource id="2" src="$mapurl"></resource>
6529: <resource id="3" type="finish"></resource>
6530: <link index="1" from="1" to="2"></link>
6531: <link index="2" from="2" to="3"></link>
6532: </map>
6533: ENDINITMAP
6534: $topurl=&declutter(
6535: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
6536: );
6537: }
6538: # ----------------------------------------------------------- Write preferences
6539: &writecoursepref($udom.'_'.$uname,
6540: ('description' => $description,
6541: 'url' => $topurl));
6542: return '/'.$udom.'/'.$uname;
6543: }
6544:
6545: # ------------------------------------------------------------------- Create ID
6546: sub generate_coursenum {
6547: my ($udom) = @_;
6548: my $domdesc = &domain($udom);
6549: return 'error: invalid domain' if ($domdesc eq '');
6550: my $uname=int(1+rand(9)).
6551: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6552: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6553: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6554: # ----------------------------------------------- Make sure that does not exist
6555: my $uhome=&homeserver($uname,$udom,'true');
6556: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6557: $uname=int(1+rand(9)).
6558: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6559: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6560: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6561: $uhome=&homeserver($uname,$udom,'true');
6562: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6563: return 'error: unable to generate unique course-ID';
6564: }
6565: }
6566: return $uname;
6567: }
6568:
6569: sub is_course {
6570: my ($cdom,$cnum) = @_;
6571: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
6572: undef,'.');
6573: if (exists($courses{$cdom.'_'.$cnum})) {
6574: return 1;
6575: }
6576: return 0;
6577: }
6578:
6579: sub store_userdata {
6580: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
6581: my $result;
6582: if ($datakey ne '') {
6583: if (ref($storehash) eq 'HASH') {
6584: if ($udom eq '' || $uname eq '') {
6585: $udom = $env{'user.domain'};
6586: $uname = $env{'user.name'};
6587: }
6588: my $uhome=&homeserver($uname,$udom);
6589: if (($uhome eq '') || ($uhome eq 'no_host')) {
6590: $result = 'error: no_host';
6591: } else {
6592: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6593: $storehash->{'host'} = $perlvar{'lonHostID'};
6594:
6595: my $namevalue='';
6596: foreach my $key (keys(%{$storehash})) {
6597: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6598: }
6599: $namevalue=~s/\&$//;
6600: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
6601: "$namespace:$datakey:$namevalue",$uhome);
6602: }
6603: } else {
6604: $result = 'error: data to store was not a hash reference';
6605: }
6606: } else {
6607: $result= 'error: invalid requestkey';
6608: }
6609: return $result;
6610: }
6611:
6612: # ---------------------------------------------------------- Assign Custom Role
6613:
6614: sub assigncustomrole {
6615: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
6616: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
6617: $end,$start,$deleteflag,$selfenroll,$context);
6618: }
6619:
6620: # ----------------------------------------------------------------- Revoke Role
6621:
6622: sub revokerole {
6623: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
6624: my $now=time;
6625: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
6626: }
6627:
6628: # ---------------------------------------------------------- Revoke Custom Role
6629:
6630: sub revokecustomrole {
6631: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
6632: my $now=time;
6633: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
6634: $deleteflag,$selfenroll,$context);
6635: }
6636:
6637: # ------------------------------------------------------------ Disk usage
6638: sub diskusage {
6639: my ($udom,$uname,$directorypath,$getpropath)=@_;
6640: $directorypath =~ s/\/$//;
6641: my $listing=&reply('du2:'.&escape($directorypath).':'
6642: .&escape($getpropath).':'.&escape($uname).':'
6643: .&escape($udom),homeserver($uname,$udom));
6644: if ($listing eq 'unknown_cmd') {
6645: if ($getpropath) {
6646: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6647: }
6648: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6649: }
6650: return $listing;
6651: }
6652:
6653: sub is_locked {
6654: my ($file_name, $domain, $user) = @_;
6655: my @check;
6656: my $is_locked;
6657: push @check, $file_name;
6658: my %locked = &get('file_permissions',\@check,
6659: $env{'user.domain'},$env{'user.name'});
6660: my ($tmp)=keys(%locked);
6661: if ($tmp=~/^error:/) { undef(%locked); }
6662:
6663: if (ref($locked{$file_name}) eq 'ARRAY') {
6664: $is_locked = 'false';
6665: foreach my $entry (@{$locked{$file_name}}) {
6666: if (ref($entry) eq 'ARRAY') {
6667: $is_locked = 'true';
6668: last;
6669: }
6670: }
6671: } else {
6672: $is_locked = 'false';
6673: }
6674: }
6675:
6676: sub declutter_portfile {
6677: my ($file) = @_;
6678: $file =~ s{^(/portfolio/|portfolio/)}{/};
6679: return $file;
6680: }
6681:
6682: # ------------------------------------------------------------- Mark as Read Only
6683:
6684: sub mark_as_readonly {
6685: my ($domain,$user,$files,$what) = @_;
6686: my %current_permissions = &dump('file_permissions',$domain,$user);
6687: my ($tmp)=keys(%current_permissions);
6688: if ($tmp=~/^error:/) { undef(%current_permissions); }
6689: foreach my $file (@{$files}) {
6690: $file = &declutter_portfile($file);
6691: push(@{$current_permissions{$file}},$what);
6692: }
6693: &put('file_permissions',\%current_permissions,$domain,$user);
6694: return;
6695: }
6696:
6697: # ------------------------------------------------------------Save Selected Files
6698:
6699: sub save_selected_files {
6700: my ($user, $path, @files) = @_;
6701: my $filename = $user."savedfiles";
6702: my @other_files = &files_not_in_path($user, $path);
6703: open (OUT, '>'.$tmpdir.$filename);
6704: foreach my $file (@files) {
6705: print (OUT $env{'form.currentpath'}.$file."\n");
6706: }
6707: foreach my $file (@other_files) {
6708: print (OUT $file."\n");
6709: }
6710: close (OUT);
6711: return 'ok';
6712: }
6713:
6714: sub clear_selected_files {
6715: my ($user) = @_;
6716: my $filename = $user."savedfiles";
6717: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6718: print (OUT undef);
6719: close (OUT);
6720: return ("ok");
6721: }
6722:
6723: sub files_in_path {
6724: my ($user, $path) = @_;
6725: my $filename = $user."savedfiles";
6726: my %return_files;
6727: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6728: while (my $line_in = <IN>) {
6729: chomp ($line_in);
6730: my @paths_and_file = split (m!/!, $line_in);
6731: my $file_part = pop (@paths_and_file);
6732: my $path_part = join ('/', @paths_and_file);
6733: $path_part.='/';
6734: my $path_and_file = $path_part.$file_part;
6735: if ($path_part eq $path) {
6736: $return_files{$file_part}= 'selected';
6737: }
6738: }
6739: close (IN);
6740: return (\%return_files);
6741: }
6742:
6743: # called in portfolio select mode, to show files selected NOT in current directory
6744: sub files_not_in_path {
6745: my ($user, $path) = @_;
6746: my $filename = $user."savedfiles";
6747: my @return_files;
6748: my $path_part;
6749: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6750: while (my $line = <IN>) {
6751: #ok, I know it's clunky, but I want it to work
6752: my @paths_and_file = split(m|/|, $line);
6753: my $file_part = pop(@paths_and_file);
6754: chomp($file_part);
6755: my $path_part = join('/', @paths_and_file);
6756: $path_part .= '/';
6757: my $path_and_file = $path_part.$file_part;
6758: if ($path_part ne $path) {
6759: push(@return_files, ($path_and_file));
6760: }
6761: }
6762: close(OUT);
6763: return (@return_files);
6764: }
6765:
6766: #----------------------------------------------Get portfolio file permissions
6767:
6768: sub get_portfile_permissions {
6769: my ($domain,$user) = @_;
6770: my %current_permissions = &dump('file_permissions',$domain,$user);
6771: my ($tmp)=keys(%current_permissions);
6772: if ($tmp=~/^error:/) { undef(%current_permissions); }
6773: return \%current_permissions;
6774: }
6775:
6776: #---------------------------------------------Get portfolio file access controls
6777:
6778: sub get_access_controls {
6779: my ($current_permissions,$group,$file) = @_;
6780: my %access;
6781: my $real_file = $file;
6782: $file =~ s/\.meta$//;
6783: if (defined($file)) {
6784: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6785: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
6786: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
6787: }
6788: }
6789: } else {
6790: foreach my $key (keys(%{$current_permissions})) {
6791: if ($key =~ /\0accesscontrol$/) {
6792: if (defined($group)) {
6793: if ($key !~ m-^\Q$group\E/-) {
6794: next;
6795: }
6796: }
6797: my ($fullpath) = split(/\0/,$key);
6798: if (ref($$current_permissions{$key}) eq 'HASH') {
6799: foreach my $control (keys(%{$$current_permissions{$key}})) {
6800: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6801: }
6802: }
6803: }
6804: }
6805: }
6806: return %access;
6807: }
6808:
6809: sub modify_access_controls {
6810: my ($file_name,$changes,$domain,$user)=@_;
6811: my ($outcome,$deloutcome);
6812: my %store_permissions;
6813: my %new_values;
6814: my %new_control;
6815: my %translation;
6816: my @deletions = ();
6817: my $now = time;
6818: if (exists($$changes{'activate'})) {
6819: if (ref($$changes{'activate'}) eq 'HASH') {
6820: my @newitems = sort(keys(%{$$changes{'activate'}}));
6821: my $numnew = scalar(@newitems);
6822: for (my $i=0; $i<$numnew; $i++) {
6823: my $newkey = $newitems[$i];
6824: my $newid = &Apache::loncommon::get_cgi_id();
6825: if ($newkey =~ /^\d+:/) {
6826: $newkey =~ s/^(\d+)/$newid/;
6827: $translation{$1} = $newid;
6828: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6829: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6830: $translation{$1} = $newid;
6831: }
6832: $new_values{$file_name."\0".$newkey} =
6833: $$changes{'activate'}{$newitems[$i]};
6834: $new_control{$newkey} = $now;
6835: }
6836: }
6837: }
6838: my %todelete;
6839: my %changed_items;
6840: foreach my $action ('delete','update') {
6841: if (exists($$changes{$action})) {
6842: if (ref($$changes{$action}) eq 'HASH') {
6843: foreach my $key (keys(%{$$changes{$action}})) {
6844: my ($itemnum) = ($key =~ /^([^:]+):/);
6845: if ($action eq 'delete') {
6846: $todelete{$itemnum} = 1;
6847: } else {
6848: $changed_items{$itemnum} = $key;
6849: }
6850: }
6851: }
6852: }
6853: }
6854: # get lock on access controls for file.
6855: my $lockhash = {
6856: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6857: ':'.$env{'user.domain'},
6858: };
6859: my $tries = 0;
6860: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6861:
6862: while (($gotlock ne 'ok') && $tries <3) {
6863: $tries ++;
6864: sleep 1;
6865: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6866: }
6867: if ($gotlock eq 'ok') {
6868: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6869: my ($tmp)=keys(%curr_permissions);
6870: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6871: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6872: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6873: if (ref($curr_controls) eq 'HASH') {
6874: foreach my $control_item (keys(%{$curr_controls})) {
6875: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6876: if (defined($todelete{$itemnum})) {
6877: push(@deletions,$file_name."\0".$control_item);
6878: } else {
6879: if (defined($changed_items{$itemnum})) {
6880: $new_control{$changed_items{$itemnum}} = $now;
6881: push(@deletions,$file_name."\0".$control_item);
6882: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6883: } else {
6884: $new_control{$control_item} = $$curr_controls{$control_item};
6885: }
6886: }
6887: }
6888: }
6889: }
6890: my ($group);
6891: if (&is_course($domain,$user)) {
6892: ($group,my $file) = split(/\//,$file_name,2);
6893: }
6894: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6895: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6896: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6897: # remove lock
6898: my @del_lock = ($file_name."\0".'locked_access_records');
6899: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
6900: my $sqlresult =
6901: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
6902: $group);
6903: } else {
6904: $outcome = "error: could not obtain lockfile\n";
6905: }
6906: return ($outcome,$deloutcome,\%new_values,\%translation);
6907: }
6908:
6909: sub make_public_indefinitely {
6910: my ($requrl) = @_;
6911: my $now = time;
6912: my $action = 'activate';
6913: my $aclnum = 0;
6914: if (&is_portfolio_url($requrl)) {
6915: my (undef,$udom,$unum,$file_name,$group) =
6916: &parse_portfolio_url($requrl);
6917: my $current_perms = &get_portfile_permissions($udom,$unum);
6918: my %access_controls = &get_access_controls($current_perms,
6919: $group,$file_name);
6920: foreach my $key (keys(%{$access_controls{$file_name}})) {
6921: my ($num,$scope,$end,$start) =
6922: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6923: if ($scope eq 'public') {
6924: if ($start <= $now && $end == 0) {
6925: $action = 'none';
6926: } else {
6927: $action = 'update';
6928: $aclnum = $num;
6929: }
6930: last;
6931: }
6932: }
6933: if ($action eq 'none') {
6934: return 'ok';
6935: } else {
6936: my %changes;
6937: my $newend = 0;
6938: my $newstart = $now;
6939: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6940: $changes{$action}{$newkey} = {
6941: type => 'public',
6942: time => {
6943: start => $newstart,
6944: end => $newend,
6945: },
6946: };
6947: my ($outcome,$deloutcome,$new_values,$translation) =
6948: &modify_access_controls($file_name,\%changes,$udom,$unum);
6949: return $outcome;
6950: }
6951: } else {
6952: return 'invalid';
6953: }
6954: }
6955:
6956: #------------------------------------------------------Get Marked as Read Only
6957:
6958: sub get_marked_as_readonly {
6959: my ($domain,$user,$what,$group) = @_;
6960: my $current_permissions = &get_portfile_permissions($domain,$user);
6961: my @readonly_files;
6962: my $cmp1=$what;
6963: if (ref($what)) { $cmp1=join('',@{$what}) };
6964: while (my ($file_name,$value) = each(%{$current_permissions})) {
6965: if (defined($group)) {
6966: if ($file_name !~ m-^\Q$group\E/-) {
6967: next;
6968: }
6969: }
6970: if (ref($value) eq "ARRAY"){
6971: foreach my $stored_what (@{$value}) {
6972: my $cmp2=$stored_what;
6973: if (ref($stored_what) eq 'ARRAY') {
6974: $cmp2=join('',@{$stored_what});
6975: }
6976: if ($cmp1 eq $cmp2) {
6977: push(@readonly_files, $file_name);
6978: last;
6979: } elsif (!defined($what)) {
6980: push(@readonly_files, $file_name);
6981: last;
6982: }
6983: }
6984: }
6985: }
6986: return @readonly_files;
6987: }
6988: #-----------------------------------------------------------Get Marked as Read Only Hash
6989:
6990: sub get_marked_as_readonly_hash {
6991: my ($current_permissions,$group,$what) = @_;
6992: my %readonly_files;
6993: while (my ($file_name,$value) = each(%{$current_permissions})) {
6994: if (defined($group)) {
6995: if ($file_name !~ m-^\Q$group\E/-) {
6996: next;
6997: }
6998: }
6999: if (ref($value) eq "ARRAY"){
7000: foreach my $stored_what (@{$value}) {
7001: if (ref($stored_what) eq 'ARRAY') {
7002: foreach my $lock_descriptor(@{$stored_what}) {
7003: if ($lock_descriptor eq 'graded') {
7004: $readonly_files{$file_name} = 'graded';
7005: } elsif ($lock_descriptor eq 'handback') {
7006: $readonly_files{$file_name} = 'handback';
7007: } else {
7008: if (!exists($readonly_files{$file_name})) {
7009: $readonly_files{$file_name} = 'locked';
7010: }
7011: }
7012: }
7013: }
7014: }
7015: }
7016: }
7017: return %readonly_files;
7018: }
7019: # ------------------------------------------------------------ Unmark as Read Only
7020:
7021: sub unmark_as_readonly {
7022: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7023: # for portfolio submissions, $what contains [$symb,$crsid]
7024: my ($domain,$user,$what,$file_name,$group) = @_;
7025: $file_name = &declutter_portfile($file_name);
7026: my $symb_crs = $what;
7027: if (ref($what)) { $symb_crs=join('',@$what); }
7028: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
7029: my ($tmp)=keys(%current_permissions);
7030: if ($tmp=~/^error:/) { undef(%current_permissions); }
7031: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
7032: foreach my $file (@readonly_files) {
7033: my $clean_file = &declutter_portfile($file);
7034: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
7035: my $current_locks = $current_permissions{$file};
7036: my @new_locks;
7037: my @del_keys;
7038: if (ref($current_locks) eq "ARRAY"){
7039: foreach my $locker (@{$current_locks}) {
7040: my $compare=$locker;
7041: if (ref($locker) eq 'ARRAY') {
7042: $compare=join('',@{$locker});
7043: if ($compare ne $symb_crs) {
7044: push(@new_locks, $locker);
7045: }
7046: }
7047: }
7048: if (scalar(@new_locks) > 0) {
7049: $current_permissions{$file} = \@new_locks;
7050: } else {
7051: push(@del_keys, $file);
7052: &del('file_permissions',\@del_keys, $domain, $user);
7053: delete($current_permissions{$file});
7054: }
7055: }
7056: }
7057: &put('file_permissions',\%current_permissions,$domain,$user);
7058: return;
7059: }
7060:
7061: # ------------------------------------------------------------ Directory lister
7062:
7063: sub dirlist {
7064: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
7065: $uri=~s/^\///;
7066: $uri=~s/\/$//;
7067: my ($udom, $uname);
7068: if ($getuserdir) {
7069: $udom = $userdomain;
7070: $uname = $username;
7071: } else {
7072: (undef,$udom,$uname)=split(/\//,$uri);
7073: if(defined($userdomain)) {
7074: $udom = $userdomain;
7075: }
7076: if(defined($username)) {
7077: $uname = $username;
7078: }
7079: }
7080: my ($dirRoot,$listing,@listing_results);
7081:
7082: $dirRoot = $perlvar{'lonDocRoot'};
7083: if (defined($getpropath)) {
7084: $dirRoot = &propath($udom,$uname);
7085: $dirRoot =~ s/\/$//;
7086: } elsif (defined($getuserdir)) {
7087: my $subdir=$uname.'__';
7088: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7089: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7090: ."/$udom/$subdir/$uname";
7091: } elsif (defined($alternateRoot)) {
7092: $dirRoot = $alternateRoot;
7093: }
7094:
7095: if($udom) {
7096: if($uname) {
7097: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
7098: .$getuserdir.':'.&escape($dirRoot)
7099: .':'.&escape($uname).':'.&escape($udom),
7100: &homeserver($uname,$udom));
7101: if ($listing eq 'unknown_cmd') {
7102: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7103: &homeserver($uname,$udom));
7104: } else {
7105: @listing_results = map { &unescape($_); } split(/:/,$listing);
7106: }
7107: if ($listing eq 'unknown_cmd') {
7108: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7109: &homeserver($uname,$udom));
7110: @listing_results = split(/:/,$listing);
7111: } else {
7112: @listing_results = map { &unescape($_); } split(/:/,$listing);
7113: }
7114: return @listing_results;
7115: } elsif(!$alternateRoot) {
7116: my %allusers;
7117: my %servers = &get_servers($udom,'library');
7118: foreach my $tryserver (keys(%servers)) {
7119: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7120: &escape($udom),$tryserver);
7121: if ($listing eq 'unknown_cmd') {
7122: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7123: $udom, $tryserver);
7124: } else {
7125: @listing_results = map { &unescape($_); } split(/:/,$listing);
7126: }
7127: if ($listing eq 'unknown_cmd') {
7128: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7129: $udom, $tryserver);
7130: @listing_results = split(/:/,$listing);
7131: } else {
7132: @listing_results =
7133: map { &unescape($_); } split(/:/,$listing);
7134: }
7135: if ($listing_results[0] ne 'no_such_dir' &&
7136: $listing_results[0] ne 'empty' &&
7137: $listing_results[0] ne 'con_lost') {
7138: foreach my $line (@listing_results) {
7139: my ($entry) = split(/&/,$line,2);
7140: $allusers{$entry} = 1;
7141: }
7142: }
7143: }
7144: my $alluserstr='';
7145: foreach my $user (sort(keys(%allusers))) {
7146: $alluserstr.=$user.'&user:';
7147: }
7148: $alluserstr=~s/:$//;
7149: return split(/:/,$alluserstr);
7150: } else {
7151: return ('missing user name');
7152: }
7153: } elsif(!defined($getpropath)) {
7154: my @all_domains = sort(&all_domains());
7155: foreach my $domain (@all_domains) {
7156: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7157: }
7158: return @all_domains;
7159: } else {
7160: return ('missing domain');
7161: }
7162: }
7163:
7164: # --------------------------------------------- GetFileTimestamp
7165: # This function utilizes dirlist and returns the date stamp for
7166: # when it was last modified. It will also return an error of -1
7167: # if an error occurs
7168:
7169: sub GetFileTimestamp {
7170: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
7171: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7172: $studentName = &LONCAPA::clean_username($studentName);
7173: my ($fileStat) =
7174: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7175: undef,$getuserdir);
7176: my @stats = split('&', $fileStat);
7177: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7178: # @stats contains first the filename, then the stat output
7179: return $stats[10]; # so this is 10 instead of 9.
7180: } else {
7181: return -1;
7182: }
7183: }
7184:
7185: sub stat_file {
7186: my ($uri) = @_;
7187: $uri = &clutter_with_no_wrapper($uri);
7188:
7189: my ($udom,$uname,$file);
7190: if ($uri =~ m-^/(uploaded|editupload)/-) {
7191: ($udom,$uname,$file) =
7192: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
7193: $file = 'userfiles/'.$file;
7194: }
7195: if ($uri =~ m-^/res/-) {
7196: ($udom,$uname) =
7197: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
7198: $file = $uri;
7199: }
7200:
7201: if (!$udom || !$uname || !$file) {
7202: # unable to handle the uri
7203: return ();
7204: }
7205: my $getpropath;
7206: if ($file =~ /^userfiles\//) {
7207: $getpropath = 1;
7208: }
7209: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
7210: my @stats = split('&', $result);
7211:
7212: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7213: shift(@stats); #filename is first
7214: return @stats;
7215: }
7216: return ();
7217: }
7218:
7219: # -------------------------------------------------------- Value of a Condition
7220:
7221: # gets the value of a specific preevaluated condition
7222: # stored in the string $env{user.state.<cid>}
7223: # or looks up a condition reference in the bighash and if if hasn't
7224: # already been evaluated recurses into docondval to get the value of
7225: # the condition, then memoizing it to
7226: # $env{user.state.<cid>.<condition>}
7227: sub directcondval {
7228: my $number=shift;
7229: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
7230: &Apache::lonuserstate::evalstate();
7231: }
7232: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7233: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7234: } elsif ($number =~ /^_/) {
7235: my $sub_condition;
7236: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7237: &GDBM_READER(),0640)) {
7238: $sub_condition=$bighash{'conditions'.$number};
7239: untie(%bighash);
7240: }
7241: my $value = &docondval($sub_condition);
7242: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
7243: return $value;
7244: }
7245: if ($env{'user.state.'.$env{'request.course.id'}}) {
7246: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
7247: } else {
7248: return 2;
7249: }
7250: }
7251:
7252: # get the collection of conditions for this resource
7253: sub condval {
7254: my $condidx=shift;
7255: my $allpathcond='';
7256: foreach my $cond (split(/\|/,$condidx)) {
7257: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7258: $allpathcond.=
7259: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7260: }
7261: }
7262: $allpathcond=~s/\|$//;
7263: return &docondval($allpathcond);
7264: }
7265:
7266: #evaluates an expression of conditions
7267: sub docondval {
7268: my ($allpathcond) = @_;
7269: my $result=0;
7270: if ($env{'request.course.id'}
7271: && defined($allpathcond)) {
7272: my $operand='|';
7273: my @stack;
7274: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7275: if ($chunk eq '(') {
7276: push @stack,($operand,$result);
7277: } elsif ($chunk eq ')') {
7278: my $before=pop @stack;
7279: if (pop @stack eq '&') {
7280: $result=$result>$before?$before:$result;
7281: } else {
7282: $result=$result>$before?$result:$before;
7283: }
7284: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7285: $operand=$chunk;
7286: } else {
7287: my $new=directcondval($chunk);
7288: if ($operand eq '&') {
7289: $result=$result>$new?$new:$result;
7290: } else {
7291: $result=$result>$new?$result:$new;
7292: }
7293: }
7294: }
7295: }
7296: return $result;
7297: }
7298:
7299: # ---------------------------------------------------- Devalidate courseresdata
7300:
7301: sub devalidatecourseresdata {
7302: my ($coursenum,$coursedomain)=@_;
7303: my $hashid=$coursenum.':'.$coursedomain;
7304: &devalidate_cache_new('courseres',$hashid);
7305: }
7306:
7307:
7308: # --------------------------------------------------- Course Resourcedata Query
7309: #
7310: # Parameters:
7311: # $coursenum - Number of the course.
7312: # $coursedomain - Domain at which the course was created.
7313: # Returns:
7314: # A hash of the course parameters along (I think) with timestamps
7315: # and version info.
7316:
7317: sub get_courseresdata {
7318: my ($coursenum,$coursedomain)=@_;
7319: my $coursehom=&homeserver($coursenum,$coursedomain);
7320: my $hashid=$coursenum.':'.$coursedomain;
7321: my ($result,$cached)=&is_cached_new('courseres',$hashid);
7322: my %dumpreply;
7323: unless (defined($cached)) {
7324: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
7325: $result=\%dumpreply;
7326: my ($tmp) = keys(%dumpreply);
7327: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7328: &do_cache_new('courseres',$hashid,$result,600);
7329: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7330: return $tmp;
7331: } elsif ($tmp =~ /^(error)/) {
7332: $result=undef;
7333: &do_cache_new('courseres',$hashid,$result,600);
7334: }
7335: }
7336: return $result;
7337: }
7338:
7339: sub devalidateuserresdata {
7340: my ($uname,$udom)=@_;
7341: my $hashid="$udom:$uname";
7342: &devalidate_cache_new('userres',$hashid);
7343: }
7344:
7345: sub get_userresdata {
7346: my ($uname,$udom)=@_;
7347: #most student don\'t have any data set, check if there is some data
7348: if (&EXT_cache_status($udom,$uname)) { return undef; }
7349:
7350: my $hashid="$udom:$uname";
7351: my ($result,$cached)=&is_cached_new('userres',$hashid);
7352: if (!defined($cached)) {
7353: my %resourcedata=&dump('resourcedata',$udom,$uname);
7354: $result=\%resourcedata;
7355: &do_cache_new('userres',$hashid,$result,600);
7356: }
7357: my ($tmp)=keys(%$result);
7358: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7359: return $result;
7360: }
7361: #error 2 occurs when the .db doesn't exist
7362: if ($tmp!~/error: 2 /) {
7363: &logthis("<font color=\"blue\">WARNING:".
7364: " Trying to get resource data for ".
7365: $uname." at ".$udom.": ".
7366: $tmp."</font>");
7367: } elsif ($tmp=~/error: 2 /) {
7368: #&EXT_cache_set($udom,$uname);
7369: &do_cache_new('userres',$hashid,undef,600);
7370: undef($tmp); # not really an error so don't send it back
7371: }
7372: return $tmp;
7373: }
7374: #----------------------------------------------- resdata - return resource data
7375: # Purpose:
7376: # Return resource data for either users or for a course.
7377: # Parameters:
7378: # $name - Course/user name.
7379: # $domain - Name of the domain the user/course is registered on.
7380: # $type - Type of thing $name is (must be 'course' or 'user'
7381: # @which - Array of names of resources desired.
7382: # Returns:
7383: # The value of the first reasource in @which that is found in the
7384: # resource hash.
7385: # Exceptional Conditions:
7386: # If the $type passed in is not valid (not the string 'course' or
7387: # 'user', an undefined reference is returned.
7388: # If none of the resources are found, an undef is returned
7389: sub resdata {
7390: my ($name,$domain,$type,@which)=@_;
7391: my $result;
7392: if ($type eq 'course') {
7393: $result=&get_courseresdata($name,$domain);
7394: } elsif ($type eq 'user') {
7395: $result=&get_userresdata($name,$domain);
7396: }
7397: if (!ref($result)) { return $result; }
7398: foreach my $item (@which) {
7399: if (defined($result->{$item->[0]})) {
7400: return [$result->{$item->[0]},$item->[1]];
7401: }
7402: }
7403: return undef;
7404: }
7405:
7406: #
7407: # EXT resource caching routines
7408: #
7409:
7410: sub clear_EXT_cache_status {
7411: &delenv('cache.EXT.');
7412: }
7413:
7414: sub EXT_cache_status {
7415: my ($target_domain,$target_user) = @_;
7416: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7417: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
7418: # We know already the user has no data
7419: return 1;
7420: } else {
7421: return 0;
7422: }
7423: }
7424:
7425: sub EXT_cache_set {
7426: my ($target_domain,$target_user) = @_;
7427: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7428: #&appenv({$cachename => time});
7429: }
7430:
7431: # --------------------------------------------------------- Value of a Variable
7432: sub EXT {
7433:
7434: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
7435: unless ($varname) { return ''; }
7436: #get real user name/domain, courseid and symb
7437: my $courseid;
7438: my $publicuser;
7439: if ($symbparm) {
7440: $symbparm=&get_symb_from_alias($symbparm);
7441: }
7442: if (!($uname && $udom)) {
7443: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
7444: if (!$symbparm) { $symbparm=$cursymb; }
7445: } else {
7446: $courseid=$env{'request.course.id'};
7447: }
7448: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7449: my $rest;
7450: if (defined($therest[0])) {
7451: $rest=join('.',@therest);
7452: } else {
7453: $rest='';
7454: }
7455:
7456: my $qualifierrest=$qualifier;
7457: if ($rest) { $qualifierrest.='.'.$rest; }
7458: my $spacequalifierrest=$space;
7459: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
7460: if ($realm eq 'user') {
7461: # --------------------------------------------------------------- user.resource
7462: if ($space eq 'resource') {
7463: if ( (defined($Apache::lonhomework::parsing_a_problem)
7464: || defined($Apache::lonhomework::parsing_a_task))
7465: &&
7466: ($symbparm eq &symbread()) ) {
7467: # if we are in the middle of processing the resource the
7468: # get the value we are planning on committing
7469: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7470: return $Apache::lonhomework::results{$qualifierrest};
7471: } else {
7472: return $Apache::lonhomework::history{$qualifierrest};
7473: }
7474: } else {
7475: my %restored;
7476: if ($publicuser || $env{'request.state'} eq 'construct') {
7477: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7478: } else {
7479: %restored=&restore($symbparm,$courseid,$udom,$uname);
7480: }
7481: return $restored{$qualifierrest};
7482: }
7483: # ----------------------------------------------------------------- user.access
7484: } elsif ($space eq 'access') {
7485: # FIXME - not supporting calls for a specific user
7486: return &allowed($qualifier,$rest);
7487: # ------------------------------------------ user.preferences, user.environment
7488: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
7489: if (($uname eq $env{'user.name'}) &&
7490: ($udom eq $env{'user.domain'})) {
7491: return $env{join('.',('environment',$qualifierrest))};
7492: } else {
7493: my %returnhash;
7494: if (!$publicuser) {
7495: %returnhash=&userenvironment($udom,$uname,
7496: $qualifierrest);
7497: }
7498: return $returnhash{$qualifierrest};
7499: }
7500: # ----------------------------------------------------------------- user.course
7501: } elsif ($space eq 'course') {
7502: # FIXME - not supporting calls for a specific user
7503: return $env{join('.',('request.course',$qualifier))};
7504: # ------------------------------------------------------------------- user.role
7505: } elsif ($space eq 'role') {
7506: # FIXME - not supporting calls for a specific user
7507: my ($role,$where)=split(/\./,$env{'request.role'});
7508: if ($qualifier eq 'value') {
7509: return $role;
7510: } elsif ($qualifier eq 'extent') {
7511: return $where;
7512: }
7513: # ----------------------------------------------------------------- user.domain
7514: } elsif ($space eq 'domain') {
7515: return $udom;
7516: # ------------------------------------------------------------------- user.name
7517: } elsif ($space eq 'name') {
7518: return $uname;
7519: # ---------------------------------------------------- Any other user namespace
7520: } else {
7521: my %reply;
7522: if (!$publicuser) {
7523: %reply=&get($space,[$qualifierrest],$udom,$uname);
7524: }
7525: return $reply{$qualifierrest};
7526: }
7527: } elsif ($realm eq 'query') {
7528: # ---------------------------------------------- pull stuff out of query string
7529: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7530: [$spacequalifierrest]);
7531: return $env{'form.'.$spacequalifierrest};
7532: } elsif ($realm eq 'request') {
7533: # ------------------------------------------------------------- request.browser
7534: if ($space eq 'browser') {
7535: if ($qualifier eq 'textremote') {
7536: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
7537: return 1;
7538: } else {
7539: return 0;
7540: }
7541: } else {
7542: return $env{'browser.'.$qualifier};
7543: }
7544: # ------------------------------------------------------------ request.filename
7545: } else {
7546: return $env{'request.'.$spacequalifierrest};
7547: }
7548: } elsif ($realm eq 'course') {
7549: # ---------------------------------------------------------- course.description
7550: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
7551: } elsif ($realm eq 'resource') {
7552:
7553: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
7554: if (!$symbparm) { $symbparm=&symbread(); }
7555: }
7556:
7557: if ($space eq 'title') {
7558: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7559: return &gettitle($symbparm);
7560: }
7561:
7562: if ($space eq 'map') {
7563: my ($map) = &decode_symb($symbparm);
7564: return &symbread($map);
7565: }
7566: if ($space eq 'filename') {
7567: if ($symbparm) {
7568: return &clutter((&decode_symb($symbparm))[2]);
7569: }
7570: return &hreflocation('',$env{'request.filename'});
7571: }
7572:
7573: my ($section, $group, @groups);
7574: my ($courselevelm,$courselevel);
7575: if ($symbparm && defined($courseid) &&
7576: $courseid eq $env{'request.course.id'}) {
7577:
7578: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
7579:
7580: # ----------------------------------------------------- Cascading lookup scheme
7581: my $symbp=$symbparm;
7582: my $mapp=&deversion((&decode_symb($symbp))[0]);
7583:
7584: my $symbparm=$symbp.'.'.$spacequalifierrest;
7585: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7586:
7587: if (($env{'user.name'} eq $uname) &&
7588: ($env{'user.domain'} eq $udom)) {
7589: $section=$env{'request.course.sec'};
7590: @groups = split(/:/,$env{'request.course.groups'});
7591: @groups=&sort_course_groups($courseid,@groups);
7592: } else {
7593: if (! defined($usection)) {
7594: $section=&getsection($udom,$uname,$courseid);
7595: } else {
7596: $section = $usection;
7597: }
7598: @groups = &get_users_groups($udom,$uname,$courseid);
7599: }
7600:
7601: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7602: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7603: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7604:
7605: $courselevel=$courseid.'.'.$spacequalifierrest;
7606: my $courselevelr=$courseid.'.'.$symbparm;
7607: $courselevelm=$courseid.'.'.$mapparm;
7608:
7609: # ----------------------------------------------------------- first, check user
7610:
7611: my $userreply=&resdata($uname,$udom,'user',
7612: ([$courselevelr,'resource'],
7613: [$courselevelm,'map' ],
7614: [$courselevel, 'course' ]));
7615: if (defined($userreply)) { return &get_reply($userreply); }
7616:
7617: # ------------------------------------------------ second, check some of course
7618: my $coursereply;
7619: if (@groups > 0) {
7620: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7621: $mapparm,$spacequalifierrest);
7622: if (defined($coursereply)) { return &get_reply($coursereply); }
7623: }
7624:
7625: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7626: $env{'course.'.$courseid.'.domain'},
7627: 'course',
7628: ([$seclevelr, 'resource'],
7629: [$seclevelm, 'map' ],
7630: [$seclevel, 'course' ],
7631: [$courselevelr,'resource']));
7632: if (defined($coursereply)) { return &get_reply($coursereply); }
7633:
7634: # ------------------------------------------------------ third, check map parms
7635: my %parmhash=();
7636: my $thisparm='';
7637: if (tie(%parmhash,'GDBM_File',
7638: $env{'request.course.fn'}.'_parms.db',
7639: &GDBM_READER(),0640)) {
7640: $thisparm=$parmhash{$symbparm};
7641: untie(%parmhash);
7642: }
7643: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
7644: }
7645: # ------------------------------------------ fourth, look in resource metadata
7646:
7647: $spacequalifierrest=~s/\./\_/;
7648: my $filename;
7649: if (!$symbparm) { $symbparm=&symbread(); }
7650: if ($symbparm) {
7651: $filename=(&decode_symb($symbparm))[2];
7652: } else {
7653: $filename=$env{'request.filename'};
7654: }
7655: my $metadata=&metadata($filename,$spacequalifierrest);
7656: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7657: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
7658: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7659:
7660: # ---------------------------------------------- fourth, look in rest of course
7661: if ($symbparm && defined($courseid) &&
7662: $courseid eq $env{'request.course.id'}) {
7663: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7664: $env{'course.'.$courseid.'.domain'},
7665: 'course',
7666: ([$courselevelm,'map' ],
7667: [$courselevel, 'course']));
7668: if (defined($coursereply)) { return &get_reply($coursereply); }
7669: }
7670: # ------------------------------------------------------------------ Cascade up
7671: unless ($space eq '0') {
7672: my @parts=split(/_/,$space);
7673: my $id=pop(@parts);
7674: my $part=join('_',@parts);
7675: if ($part eq '') { $part='0'; }
7676: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
7677: $symbparm,$udom,$uname,$section,1);
7678: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
7679: }
7680: if ($recurse) { return undef; }
7681: my $pack_def=&packages_tab_default($filename,$varname);
7682: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
7683: # ---------------------------------------------------- Any other user namespace
7684: } elsif ($realm eq 'environment') {
7685: # ----------------------------------------------------------------- environment
7686: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7687: return $env{'environment.'.$spacequalifierrest};
7688: } else {
7689: if ($uname eq 'anonymous' && $udom eq '') {
7690: return '';
7691: }
7692: my %returnhash=&userenvironment($udom,$uname,
7693: $spacequalifierrest);
7694: return $returnhash{$spacequalifierrest};
7695: }
7696: } elsif ($realm eq 'system') {
7697: # ----------------------------------------------------------------- system.time
7698: if ($space eq 'time') {
7699: return time;
7700: }
7701: } elsif ($realm eq 'server') {
7702: # ----------------------------------------------------------------- system.time
7703: if ($space eq 'name') {
7704: return $ENV{'SERVER_NAME'};
7705: }
7706: }
7707: return '';
7708: }
7709:
7710: sub get_reply {
7711: my ($reply_value) = @_;
7712: if (ref($reply_value) eq 'ARRAY') {
7713: if (wantarray) {
7714: return @$reply_value;
7715: }
7716: return $reply_value->[0];
7717: } else {
7718: return $reply_value;
7719: }
7720: }
7721:
7722: sub check_group_parms {
7723: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7724: my @groupitems = ();
7725: my $resultitem;
7726: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
7727: foreach my $group (@{$groups}) {
7728: foreach my $level (@levels) {
7729: my $item = $courseid.'.['.$group.'].'.$level->[0];
7730: push(@groupitems,[$item,$level->[1]]);
7731: }
7732: }
7733: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7734: $env{'course.'.$courseid.'.domain'},
7735: 'course',@groupitems);
7736: return $coursereply;
7737: }
7738:
7739: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
7740: my ($courseid,@groups) = @_;
7741: @groups = sort(@groups);
7742: return @groups;
7743: }
7744:
7745: sub packages_tab_default {
7746: my ($uri,$varname)=@_;
7747: my (undef,$part,$name)=split(/\./,$varname);
7748:
7749: my (@extension,@specifics,$do_default);
7750: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
7751: my ($pack_type,$pack_part)=split(/_/,$package,2);
7752: if ($pack_type eq 'default') {
7753: $do_default=1;
7754: } elsif ($pack_type eq 'extension') {
7755: push(@extension,[$package,$pack_type,$pack_part]);
7756: } elsif ($pack_part eq $part || $pack_type eq 'part') {
7757: # only look at packages defaults for packages that this id is
7758: push(@specifics,[$package,$pack_type,$pack_part]);
7759: }
7760: }
7761: # first look for a package that matches the requested part id
7762: foreach my $package (@specifics) {
7763: my (undef,$pack_type,$pack_part)=@{$package};
7764: next if ($pack_part ne $part);
7765: if (defined($packagetab{"$pack_type&$name&default"})) {
7766: return $packagetab{"$pack_type&$name&default"};
7767: }
7768: }
7769: # look for any possible matching non extension_ package
7770: foreach my $package (@specifics) {
7771: my (undef,$pack_type,$pack_part)=@{$package};
7772: if (defined($packagetab{"$pack_type&$name&default"})) {
7773: return $packagetab{"$pack_type&$name&default"};
7774: }
7775: if ($pack_type eq 'part') { $pack_part='0'; }
7776: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7777: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
7778: }
7779: }
7780: # look for any posible extension_ match
7781: foreach my $package (@extension) {
7782: my ($package,$pack_type)=@{$package};
7783: if (defined($packagetab{"$pack_type&$name&default"})) {
7784: return $packagetab{"$pack_type&$name&default"};
7785: }
7786: if (defined($packagetab{$package."&$name&default"})) {
7787: return $packagetab{$package."&$name&default"};
7788: }
7789: }
7790: # look for a global default setting
7791: if ($do_default && defined($packagetab{"default&$name&default"})) {
7792: return $packagetab{"default&$name&default"};
7793: }
7794: return undef;
7795: }
7796:
7797: sub add_prefix_and_part {
7798: my ($prefix,$part)=@_;
7799: my $keyroot;
7800: if (defined($prefix) && $prefix !~ /^__/) {
7801: # prefix that has a part already
7802: $keyroot=$prefix;
7803: } elsif (defined($prefix)) {
7804: # prefix that is missing a part
7805: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7806: } else {
7807: # no prefix at all
7808: if (defined($part)) { $keyroot='_'.$part; }
7809: }
7810: return $keyroot;
7811: }
7812:
7813: # ---------------------------------------------------------------- Get metadata
7814:
7815: my %metaentry;
7816: sub metadata {
7817: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
7818: $uri=&declutter($uri);
7819: # if it is a non metadata possible uri return quickly
7820: if (($uri eq '') ||
7821: (($uri =~ m|^/*adm/|) &&
7822: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
7823: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7824: return undef;
7825: }
7826: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7827: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
7828: return undef;
7829: }
7830: my $filename=$uri;
7831: $uri=~s/\.meta$//;
7832: #
7833: # Is the metadata already cached?
7834: # Look at timestamp of caching
7835: # Everything is cached by the main uri, libraries are never directly cached
7836: #
7837: if (!defined($liburi)) {
7838: my ($result,$cached)=&is_cached_new('meta',$uri);
7839: if (defined($cached)) { return $result->{':'.$what}; }
7840: }
7841: {
7842: #
7843: # Is this a recursive call for a library?
7844: #
7845: # if (! exists($metacache{$uri})) {
7846: # $metacache{$uri}={};
7847: # }
7848: my $cachetime = 60*60;
7849: if ($liburi) {
7850: $liburi=&declutter($liburi);
7851: $filename=$liburi;
7852: } else {
7853: &devalidate_cache_new('meta',$uri);
7854: undef(%metaentry);
7855: }
7856: my %metathesekeys=();
7857: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
7858: my $metastring;
7859: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
7860: my $which = &hreflocation('','/'.($liburi || $uri));
7861: $metastring =
7862: &Apache::lonnet::ssi_body($which,
7863: ('grade_target' => 'meta'));
7864: $cachetime = 1; # only want this cached in the child not long term
7865: } elsif ($uri !~ m -^(editupload)/-) {
7866: my $file=&filelocation('',&clutter($filename));
7867: #push(@{$metaentry{$uri.'.file'}},$file);
7868: $metastring=&getfile($file);
7869: }
7870: my $parser=HTML::LCParser->new(\$metastring);
7871: my $token;
7872: undef %metathesekeys;
7873: while ($token=$parser->get_token) {
7874: if ($token->[0] eq 'S') {
7875: if (defined($token->[2]->{'package'})) {
7876: #
7877: # This is a package - get package info
7878: #
7879: my $package=$token->[2]->{'package'};
7880: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7881: if (defined($token->[2]->{'id'})) {
7882: $keyroot.='_'.$token->[2]->{'id'};
7883: }
7884: if ($metaentry{':packages'}) {
7885: $metaentry{':packages'}.=','.$package.$keyroot;
7886: } else {
7887: $metaentry{':packages'}=$package.$keyroot;
7888: }
7889: foreach my $pack_entry (keys(%packagetab)) {
7890: my $part=$keyroot;
7891: $part=~s/^\_//;
7892: if ($pack_entry=~/^\Q$package\E\&/ ||
7893: $pack_entry=~/^\Q$package\E_0\&/) {
7894: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
7895: # ignore package.tab specified default values
7896: # here &package_tab_default() will fetch those
7897: if ($subp eq 'default') { next; }
7898: my $value=$packagetab{$pack_entry};
7899: my $unikey;
7900: if ($pack =~ /_0$/) {
7901: $unikey='parameter_0_'.$name;
7902: $part=0;
7903: } else {
7904: $unikey='parameter'.$keyroot.'_'.$name;
7905: }
7906: if ($subp eq 'display') {
7907: $value.=' [Part: '.$part.']';
7908: }
7909: $metaentry{':'.$unikey.'.part'}=$part;
7910: $metathesekeys{$unikey}=1;
7911: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7912: $metaentry{':'.$unikey.'.'.$subp}=$value;
7913: }
7914: if (defined($metaentry{':'.$unikey.'.default'})) {
7915: $metaentry{':'.$unikey}=
7916: $metaentry{':'.$unikey.'.default'};
7917: }
7918: }
7919: }
7920: } else {
7921: #
7922: # This is not a package - some other kind of start tag
7923: #
7924: my $entry=$token->[1];
7925: my $unikey;
7926: if ($entry eq 'import') {
7927: $unikey='';
7928: } else {
7929: $unikey=$entry;
7930: }
7931: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7932:
7933: if (defined($token->[2]->{'id'})) {
7934: $unikey.='_'.$token->[2]->{'id'};
7935: }
7936:
7937: if ($entry eq 'import') {
7938: #
7939: # Importing a library here
7940: #
7941: if ($depthcount<20) {
7942: my $location=$parser->get_text('/import');
7943: my $dir=$filename;
7944: $dir=~s|[^/]*$||;
7945: $location=&filelocation($dir,$location);
7946: my $metadata =
7947: &metadata($uri,'keys', $location,$unikey,
7948: $depthcount+1);
7949: foreach my $meta (split(',',$metadata)) {
7950: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7951: $metathesekeys{$meta}=1;
7952: }
7953: }
7954: } else {
7955:
7956: if (defined($token->[2]->{'name'})) {
7957: $unikey.='_'.$token->[2]->{'name'};
7958: }
7959: $metathesekeys{$unikey}=1;
7960: foreach my $param (@{$token->[3]}) {
7961: $metaentry{':'.$unikey.'.'.$param} =
7962: $token->[2]->{$param};
7963: }
7964: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
7965: my $default=$metaentry{':'.$unikey.'.default'};
7966: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7967: # only ws inside the tag, and not in default, so use default
7968: # as value
7969: $metaentry{':'.$unikey}=$default;
7970: } elsif ( $internaltext =~ /\S/ ) {
7971: # something interesting inside the tag
7972: $metaentry{':'.$unikey}=$internaltext;
7973: } else {
7974: # no interesting values, don't set a default
7975: }
7976: # end of not-a-package not-a-library import
7977: }
7978: # end of not-a-package start tag
7979: }
7980: # the next is the end of "start tag"
7981: }
7982: }
7983: my ($extension) = ($uri =~ /\.(\w+)$/);
7984: $extension = lc($extension);
7985: if ($extension eq 'htm') { $extension='html'; }
7986:
7987: foreach my $key (keys(%packagetab)) {
7988: #no specific packages #how's our extension
7989: if ($key!~/^extension_\Q$extension\E&/) { next; }
7990: &metadata_create_package_def($uri,$key,'extension_'.$extension,
7991: \%metathesekeys);
7992: }
7993:
7994: if (!exists($metaentry{':packages'})
7995: || $packagetab{"import_defaults&extension_$extension"}) {
7996: foreach my $key (keys(%packagetab)) {
7997: #no specific packages well let's get default then
7998: if ($key!~/^default&/) { next; }
7999: &metadata_create_package_def($uri,$key,'default',
8000: \%metathesekeys);
8001: }
8002: }
8003: # are there custom rights to evaluate
8004: if ($metaentry{':copyright'} eq 'custom') {
8005:
8006: #
8007: # Importing a rights file here
8008: #
8009: unless ($depthcount) {
8010: my $location=$metaentry{':customdistributionfile'};
8011: my $dir=$filename;
8012: $dir=~s|[^/]*$||;
8013: $location=&filelocation($dir,$location);
8014: my $rights_metadata =
8015: &metadata($uri,'keys',$location,'_rights',
8016: $depthcount+1);
8017: foreach my $rights (split(',',$rights_metadata)) {
8018: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8019: $metathesekeys{$rights}=1;
8020: }
8021: }
8022: }
8023: # uniqifiy package listing
8024: my %seen;
8025: my @uniq_packages =
8026: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8027: $metaentry{':packages'} = join(',',@uniq_packages);
8028:
8029: $metaentry{':keys'} = join(',',keys(%metathesekeys));
8030: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8031: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
8032: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
8033: # this is the end of "was not already recently cached
8034: }
8035: return $metaentry{':'.$what};
8036: }
8037:
8038: sub metadata_create_package_def {
8039: my ($uri,$key,$package,$metathesekeys)=@_;
8040: my ($pack,$name,$subp)=split(/\&/,$key);
8041: if ($subp eq 'default') { next; }
8042:
8043: if (defined($metaentry{':packages'})) {
8044: $metaentry{':packages'}.=','.$package;
8045: } else {
8046: $metaentry{':packages'}=$package;
8047: }
8048: my $value=$packagetab{$key};
8049: my $unikey;
8050: $unikey='parameter_0_'.$name;
8051: $metaentry{':'.$unikey.'.part'}=0;
8052: $$metathesekeys{$unikey}=1;
8053: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8054: $metaentry{':'.$unikey.'.'.$subp}=$value;
8055: }
8056: if (defined($metaentry{':'.$unikey.'.default'})) {
8057: $metaentry{':'.$unikey}=
8058: $metaentry{':'.$unikey.'.default'};
8059: }
8060: }
8061:
8062: sub metadata_generate_part0 {
8063: my ($metadata,$metacache,$uri) = @_;
8064: my %allnames;
8065: foreach my $metakey (keys(%$metadata)) {
8066: if ($metakey=~/^parameter\_(.*)/) {
8067: my $part=$$metacache{':'.$metakey.'.part'};
8068: my $name=$$metacache{':'.$metakey.'.name'};
8069: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
8070: $allnames{$name}=$part;
8071: }
8072: }
8073: }
8074: foreach my $name (keys(%allnames)) {
8075: $$metadata{"parameter_0_$name"}=1;
8076: my $key=":parameter_0_$name";
8077: $$metacache{"$key.part"}='0';
8078: $$metacache{"$key.name"}=$name;
8079: $$metacache{"$key.type"}=$$metacache{':parameter_'.
8080: $allnames{$name}.'_'.$name.
8081: '.type'};
8082: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
8083: '.display'};
8084: my $expr='[Part: '.$allnames{$name}.']';
8085: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
8086: $$metacache{"$key.display"}=$olddis;
8087: }
8088: }
8089:
8090: # ------------------------------------------------------ Devalidate title cache
8091:
8092: sub devalidate_title_cache {
8093: my ($url)=@_;
8094: if (!$env{'request.course.id'}) { return; }
8095: my $symb=&symbread($url);
8096: if (!$symb) { return; }
8097: my $key=$env{'request.course.id'}."\0".$symb;
8098: &devalidate_cache_new('title',$key);
8099: }
8100:
8101: # ------------------------------------------------- Get the title of a course
8102:
8103: sub current_course_title {
8104: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8105: }
8106: # ------------------------------------------------- Get the title of a resource
8107:
8108: sub gettitle {
8109: my $urlsymb=shift;
8110: my $symb=&symbread($urlsymb);
8111: if ($symb) {
8112: my $key=$env{'request.course.id'}."\0".$symb;
8113: my ($result,$cached)=&is_cached_new('title',$key);
8114: if (defined($cached)) {
8115: return $result;
8116: }
8117: my ($map,$resid,$url)=&decode_symb($symb);
8118: my $title='';
8119: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8120: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8121: } else {
8122: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8123: &GDBM_READER(),0640)) {
8124: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8125: $title=$bighash{'title_'.$mapid.'.'.$resid};
8126: untie(%bighash);
8127: }
8128: }
8129: $title=~s/\&colon\;/\:/gs;
8130: if ($title) {
8131: return &do_cache_new('title',$key,$title,600);
8132: }
8133: $urlsymb=$url;
8134: }
8135: my $title=&metadata($urlsymb,'title');
8136: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8137: return $title;
8138: }
8139:
8140: sub get_slot {
8141: my ($which,$cnum,$cdom)=@_;
8142: if (!$cnum || !$cdom) {
8143: (undef,my $courseid)=&whichuser();
8144: $cdom=$env{'course.'.$courseid.'.domain'};
8145: $cnum=$env{'course.'.$courseid.'.num'};
8146: }
8147: my $key=join("\0",'slots',$cdom,$cnum,$which);
8148: my %slotinfo;
8149: if (exists($remembered{$key})) {
8150: $slotinfo{$which} = $remembered{$key};
8151: } else {
8152: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8153: &Apache::lonhomework::showhash(%slotinfo);
8154: my ($tmp)=keys(%slotinfo);
8155: if ($tmp=~/^error:/) { return (); }
8156: $remembered{$key} = $slotinfo{$which};
8157: }
8158: if (ref($slotinfo{$which}) eq 'HASH') {
8159: return %{$slotinfo{$which}};
8160: }
8161: return $slotinfo{$which};
8162: }
8163: # ------------------------------------------------- Update symbolic store links
8164:
8165: sub symblist {
8166: my ($mapname,%newhash)=@_;
8167: $mapname=&deversion(&declutter($mapname));
8168: my %hash;
8169: if (($env{'request.course.fn'}) && (%newhash)) {
8170: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8171: &GDBM_WRCREAT(),0640)) {
8172: foreach my $url (keys(%newhash)) {
8173: next if ($url eq 'last_known'
8174: && $env{'form.no_update_last_known'});
8175: $hash{declutter($url)}=&encode_symb($mapname,
8176: $newhash{$url}->[1],
8177: $newhash{$url}->[0]);
8178: }
8179: if (untie(%hash)) {
8180: return 'ok';
8181: }
8182: }
8183: }
8184: return 'error';
8185: }
8186:
8187: # --------------------------------------------------------------- Verify a symb
8188:
8189: sub symbverify {
8190: my ($symb,$thisurl)=@_;
8191: my $thisfn=$thisurl;
8192: $thisfn=&declutter($thisfn);
8193: # direct jump to resource in page or to a sequence - will construct own symbs
8194: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8195: # check URL part
8196: my ($map,$resid,$url)=&decode_symb($symb);
8197:
8198: unless ($url eq $thisfn) { return 0; }
8199:
8200: $symb=&symbclean($symb);
8201: $thisurl=&deversion($thisurl);
8202: $thisfn=&deversion($thisfn);
8203:
8204: my %bighash;
8205: my $okay=0;
8206:
8207: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8208: &GDBM_READER(),0640)) {
8209: my $ids=$bighash{'ids_'.&clutter($thisurl)};
8210: unless ($ids) {
8211: $ids=$bighash{'ids_/'.$thisurl};
8212: }
8213: if ($ids) {
8214: # ------------------------------------------------------------------- Has ID(s)
8215: foreach my $id (split(/\,/,$ids)) {
8216: my ($mapid,$resid)=split(/\./,$id);
8217: if (
8218: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8219: eq $symb) {
8220: if (($env{'request.role.adv'}) ||
8221: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
8222: $okay=1;
8223: }
8224: }
8225: }
8226: }
8227: untie(%bighash);
8228: }
8229: return $okay;
8230: }
8231:
8232: # --------------------------------------------------------------- Clean-up symb
8233:
8234: sub symbclean {
8235: my $symb=shift;
8236: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8237: # remove version from map
8238: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
8239:
8240: # remove version from URL
8241: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
8242:
8243: # remove wrapper
8244:
8245: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
8246: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
8247: return $symb;
8248: }
8249:
8250: # ---------------------------------------------- Split symb to find map and url
8251:
8252: sub encode_symb {
8253: my ($map,$resid,$url)=@_;
8254: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8255: }
8256:
8257: sub decode_symb {
8258: my $symb=shift;
8259: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8260: my ($map,$resid,$url)=split(/___/,$symb);
8261: return (&fixversion($map),$resid,&fixversion($url));
8262: }
8263:
8264: sub fixversion {
8265: my $fn=shift;
8266: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
8267: my %bighash;
8268: my $uri=&clutter($fn);
8269: my $key=$env{'request.course.id'}.'_'.$uri;
8270: # is this cached?
8271: my ($result,$cached)=&is_cached_new('courseresversion',$key);
8272: if (defined($cached)) { return $result; }
8273: # unfortunately not cached, or expired
8274: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8275: &GDBM_READER(),0640)) {
8276: if ($bighash{'version_'.$uri}) {
8277: my $version=$bighash{'version_'.$uri};
8278: unless (($version eq 'mostrecent') ||
8279: ($version==&getversion($uri))) {
8280: $uri=~s/\.(\w+)$/\.$version\.$1/;
8281: }
8282: }
8283: untie %bighash;
8284: }
8285: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
8286: }
8287:
8288: sub deversion {
8289: my $url=shift;
8290: $url=~s/\.\d+\.(\w+)$/\.$1/;
8291: return $url;
8292: }
8293:
8294: # ------------------------------------------------------ Return symb list entry
8295:
8296: sub symbread {
8297: my ($thisfn,$donotrecurse)=@_;
8298: my $cache_str='request.symbread.cached.'.$thisfn;
8299: if (defined($env{$cache_str})) { return $env{$cache_str}; }
8300: # no filename provided? try from environment
8301: unless ($thisfn) {
8302: if ($env{'request.symb'}) {
8303: return $env{$cache_str}=&symbclean($env{'request.symb'});
8304: }
8305: $thisfn=$env{'request.filename'};
8306: }
8307: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
8308: # is that filename actually a symb? Verify, clean, and return
8309: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
8310: if (&symbverify($thisfn,$1)) {
8311: return $env{$cache_str}=&symbclean($thisfn);
8312: }
8313: }
8314: $thisfn=declutter($thisfn);
8315: my %hash;
8316: my %bighash;
8317: my $syval='';
8318: if (($env{'request.course.fn'}) && ($thisfn)) {
8319: my $targetfn = $thisfn;
8320: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
8321: $targetfn = 'adm/wrapper/'.$thisfn;
8322: }
8323: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8324: $targetfn=$1;
8325: }
8326: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8327: &GDBM_READER(),0640)) {
8328: $syval=$hash{$targetfn};
8329: untie(%hash);
8330: }
8331: # ---------------------------------------------------------- There was an entry
8332: if ($syval) {
8333: #unless ($syval=~/\_\d+$/) {
8334: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
8335: #&appenv({'request.ambiguous' => $thisfn});
8336: #return $env{$cache_str}='';
8337: #}
8338: #$syval.=$1;
8339: #}
8340: } else {
8341: # ------------------------------------------------------- Was not in symb table
8342: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8343: &GDBM_READER(),0640)) {
8344: # ---------------------------------------------- Get ID(s) for current resource
8345: my $ids=$bighash{'ids_'.&clutter($thisfn)};
8346: unless ($ids) {
8347: $ids=$bighash{'ids_/'.$thisfn};
8348: }
8349: unless ($ids) {
8350: # alias?
8351: $ids=$bighash{'mapalias_'.$thisfn};
8352: }
8353: if ($ids) {
8354: # ------------------------------------------------------------------- Has ID(s)
8355: my @possibilities=split(/\,/,$ids);
8356: if ($#possibilities==0) {
8357: # ----------------------------------------------- There is only one possibility
8358: my ($mapid,$resid)=split(/\./,$ids);
8359: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8360: $resid,$thisfn);
8361: } elsif (!$donotrecurse) {
8362: # ------------------------------------------ There is more than one possibility
8363: my $realpossible=0;
8364: foreach my $id (@possibilities) {
8365: my $file=$bighash{'src_'.$id};
8366: if (&allowed('bre',$file)) {
8367: my ($mapid,$resid)=split(/\./,$id);
8368: if ($bighash{'map_type_'.$mapid} ne 'page') {
8369: $realpossible++;
8370: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8371: $resid,$thisfn);
8372: }
8373: }
8374: }
8375: if ($realpossible!=1) { $syval=''; }
8376: } else {
8377: $syval='';
8378: }
8379: }
8380: untie(%bighash)
8381: }
8382: }
8383: if ($syval) {
8384: return $env{$cache_str}=$syval;
8385: }
8386: }
8387: &appenv({'request.ambiguous' => $thisfn});
8388: return $env{$cache_str}='';
8389: }
8390:
8391: # ---------------------------------------------------------- Return random seed
8392:
8393: sub numval {
8394: my $txt=shift;
8395: $txt=~tr/A-J/0-9/;
8396: $txt=~tr/a-j/0-9/;
8397: $txt=~tr/K-T/0-9/;
8398: $txt=~tr/k-t/0-9/;
8399: $txt=~tr/U-Z/0-5/;
8400: $txt=~tr/u-z/0-5/;
8401: $txt=~s/\D//g;
8402: if ($_64bit) { if ($txt > 2**32) { return -1; } }
8403: return int($txt);
8404: }
8405:
8406: sub numval2 {
8407: my $txt=shift;
8408: $txt=~tr/A-J/0-9/;
8409: $txt=~tr/a-j/0-9/;
8410: $txt=~tr/K-T/0-9/;
8411: $txt=~tr/k-t/0-9/;
8412: $txt=~tr/U-Z/0-5/;
8413: $txt=~tr/u-z/0-5/;
8414: $txt=~s/\D//g;
8415: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8416: my $total;
8417: foreach my $val (@txts) { $total+=$val; }
8418: if ($_64bit) { if ($total > 2**32) { return -1; } }
8419: return int($total);
8420: }
8421:
8422: sub numval3 {
8423: use integer;
8424: my $txt=shift;
8425: $txt=~tr/A-J/0-9/;
8426: $txt=~tr/a-j/0-9/;
8427: $txt=~tr/K-T/0-9/;
8428: $txt=~tr/k-t/0-9/;
8429: $txt=~tr/U-Z/0-5/;
8430: $txt=~tr/u-z/0-5/;
8431: $txt=~s/\D//g;
8432: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8433: my $total;
8434: foreach my $val (@txts) { $total+=$val; }
8435: if ($_64bit) { $total=(($total<<32)>>32); }
8436: return $total;
8437: }
8438:
8439: sub digest {
8440: my ($data)=@_;
8441: my $digest=&Digest::MD5::md5($data);
8442: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8443: my ($e,$f);
8444: {
8445: use integer;
8446: $e=($a+$b);
8447: $f=($c+$d);
8448: if ($_64bit) {
8449: $e=(($e<<32)>>32);
8450: $f=(($f<<32)>>32);
8451: }
8452: }
8453: if (wantarray) {
8454: return ($e,$f);
8455: } else {
8456: my $g;
8457: {
8458: use integer;
8459: $g=($e+$f);
8460: if ($_64bit) {
8461: $g=(($g<<32)>>32);
8462: }
8463: }
8464: return $g;
8465: }
8466: }
8467:
8468: sub latest_rnd_algorithm_id {
8469: return '64bit5';
8470: }
8471:
8472: sub get_rand_alg {
8473: my ($courseid)=@_;
8474: if (!$courseid) { $courseid=(&whichuser())[1]; }
8475: if ($courseid) {
8476: return $env{"course.$courseid.rndseed"};
8477: }
8478: return &latest_rnd_algorithm_id();
8479: }
8480:
8481: sub validCODE {
8482: my ($CODE)=@_;
8483: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8484: return 0;
8485: }
8486:
8487: sub getCODE {
8488: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
8489: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8490: defined($Apache::lonhomework::parsing_a_task) ) &&
8491: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
8492: return $Apache::lonhomework::history{'resource.CODE'};
8493: }
8494: return undef;
8495: }
8496:
8497: sub rndseed {
8498: my ($symb,$courseid,$domain,$username)=@_;
8499: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
8500: if (!defined($symb)) {
8501: unless ($symb=$wsymb) { return time; }
8502: }
8503: if (!$courseid) { $courseid=$wcourseid; }
8504: if (!$domain) { $domain=$wdomain; }
8505: if (!$username) { $username=$wusername }
8506: my $which=&get_rand_alg();
8507:
8508: if (defined(&getCODE())) {
8509: if ($which eq '64bit5') {
8510: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8511: } elsif ($which eq '64bit4') {
8512: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8513: } else {
8514: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8515: }
8516: } elsif ($which eq '64bit5') {
8517: return &rndseed_64bit5($symb,$courseid,$domain,$username);
8518: } elsif ($which eq '64bit4') {
8519: return &rndseed_64bit4($symb,$courseid,$domain,$username);
8520: } elsif ($which eq '64bit3') {
8521: return &rndseed_64bit3($symb,$courseid,$domain,$username);
8522: } elsif ($which eq '64bit2') {
8523: return &rndseed_64bit2($symb,$courseid,$domain,$username);
8524: } elsif ($which eq '64bit') {
8525: return &rndseed_64bit($symb,$courseid,$domain,$username);
8526: }
8527: return &rndseed_32bit($symb,$courseid,$domain,$username);
8528: }
8529:
8530: sub rndseed_32bit {
8531: my ($symb,$courseid,$domain,$username)=@_;
8532: {
8533: use integer;
8534: my $symbchck=unpack("%32C*",$symb) << 27;
8535: my $symbseed=numval($symb) << 22;
8536: my $namechck=unpack("%32C*",$username) << 17;
8537: my $nameseed=numval($username) << 12;
8538: my $domainseed=unpack("%32C*",$domain) << 7;
8539: my $courseseed=unpack("%32C*",$courseid);
8540: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
8541: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8542: #&logthis("rndseed :$num:$symb");
8543: if ($_64bit) { $num=(($num<<32)>>32); }
8544: return $num;
8545: }
8546: }
8547:
8548: sub rndseed_64bit {
8549: my ($symb,$courseid,$domain,$username)=@_;
8550: {
8551: use integer;
8552: my $symbchck=unpack("%32S*",$symb) << 21;
8553: my $symbseed=numval($symb) << 10;
8554: my $namechck=unpack("%32S*",$username);
8555:
8556: my $nameseed=numval($username) << 21;
8557: my $domainseed=unpack("%32S*",$domain) << 10;
8558: my $courseseed=unpack("%32S*",$courseid);
8559:
8560: my $num1=$symbchck+$symbseed+$namechck;
8561: my $num2=$nameseed+$domainseed+$courseseed;
8562: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8563: #&logthis("rndseed :$num:$symb");
8564: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8565: return "$num1,$num2";
8566: }
8567: }
8568:
8569: sub rndseed_64bit2 {
8570: my ($symb,$courseid,$domain,$username)=@_;
8571: {
8572: use integer;
8573: # strings need to be an even # of cahracters long, it it is odd the
8574: # last characters gets thrown away
8575: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8576: my $symbseed=numval($symb) << 10;
8577: my $namechck=unpack("%32S*",$username.' ');
8578:
8579: my $nameseed=numval($username) << 21;
8580: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8581: my $courseseed=unpack("%32S*",$courseid.' ');
8582:
8583: my $num1=$symbchck+$symbseed+$namechck;
8584: my $num2=$nameseed+$domainseed+$courseseed;
8585: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8586: #&logthis("rndseed :$num:$symb");
8587: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8588: return "$num1,$num2";
8589: }
8590: }
8591:
8592: sub rndseed_64bit3 {
8593: my ($symb,$courseid,$domain,$username)=@_;
8594: {
8595: use integer;
8596: # strings need to be an even # of cahracters long, it it is odd the
8597: # last characters gets thrown away
8598: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8599: my $symbseed=numval2($symb) << 10;
8600: my $namechck=unpack("%32S*",$username.' ');
8601:
8602: my $nameseed=numval2($username) << 21;
8603: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8604: my $courseseed=unpack("%32S*",$courseid.' ');
8605:
8606: my $num1=$symbchck+$symbseed+$namechck;
8607: my $num2=$nameseed+$domainseed+$courseseed;
8608: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8609: #&logthis("rndseed :$num1:$num2:$_64bit");
8610: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8611:
8612: return "$num1:$num2";
8613: }
8614: }
8615:
8616: sub rndseed_64bit4 {
8617: my ($symb,$courseid,$domain,$username)=@_;
8618: {
8619: use integer;
8620: # strings need to be an even # of cahracters long, it it is odd the
8621: # last characters gets thrown away
8622: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8623: my $symbseed=numval3($symb) << 10;
8624: my $namechck=unpack("%32S*",$username.' ');
8625:
8626: my $nameseed=numval3($username) << 21;
8627: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8628: my $courseseed=unpack("%32S*",$courseid.' ');
8629:
8630: my $num1=$symbchck+$symbseed+$namechck;
8631: my $num2=$nameseed+$domainseed+$courseseed;
8632: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8633: #&logthis("rndseed :$num1:$num2:$_64bit");
8634: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8635:
8636: return "$num1:$num2";
8637: }
8638: }
8639:
8640: sub rndseed_64bit5 {
8641: my ($symb,$courseid,$domain,$username)=@_;
8642: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8643: return "$num1:$num2";
8644: }
8645:
8646: sub rndseed_CODE_64bit {
8647: my ($symb,$courseid,$domain,$username)=@_;
8648: {
8649: use integer;
8650: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8651: my $symbseed=numval2($symb);
8652: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8653: my $CODEseed=numval(&getCODE());
8654: my $courseseed=unpack("%32S*",$courseid.' ');
8655: my $num1=$symbseed+$CODEchck;
8656: my $num2=$CODEseed+$courseseed+$symbchck;
8657: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8658: #&logthis("rndseed :$num1:$num2:$symb");
8659: if ($_64bit) { $num1=(($num1<<32)>>32); }
8660: if ($_64bit) { $num2=(($num2<<32)>>32); }
8661: return "$num1:$num2";
8662: }
8663: }
8664:
8665: sub rndseed_CODE_64bit4 {
8666: my ($symb,$courseid,$domain,$username)=@_;
8667: {
8668: use integer;
8669: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8670: my $symbseed=numval3($symb);
8671: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8672: my $CODEseed=numval3(&getCODE());
8673: my $courseseed=unpack("%32S*",$courseid.' ');
8674: my $num1=$symbseed+$CODEchck;
8675: my $num2=$CODEseed+$courseseed+$symbchck;
8676: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8677: #&logthis("rndseed :$num1:$num2:$symb");
8678: if ($_64bit) { $num1=(($num1<<32)>>32); }
8679: if ($_64bit) { $num2=(($num2<<32)>>32); }
8680: return "$num1:$num2";
8681: }
8682: }
8683:
8684: sub rndseed_CODE_64bit5 {
8685: my ($symb,$courseid,$domain,$username)=@_;
8686: my $code = &getCODE();
8687: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8688: return "$num1:$num2";
8689: }
8690:
8691: sub setup_random_from_rndseed {
8692: my ($rndseed)=@_;
8693: if ($rndseed =~/([,:])/) {
8694: my ($num1,$num2)=split(/[,:]/,$rndseed);
8695: &Math::Random::random_set_seed(abs($num1),abs($num2));
8696: } else {
8697: &Math::Random::random_set_seed_from_phrase($rndseed);
8698: }
8699: }
8700:
8701: sub latest_receipt_algorithm_id {
8702: return 'receipt3';
8703: }
8704:
8705: sub recunique {
8706: my $fucourseid=shift;
8707: my $unique;
8708: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8709: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8710: $unique=$env{"course.$fucourseid.internal.encseed"};
8711: } else {
8712: $unique=$perlvar{'lonReceipt'};
8713: }
8714: return unpack("%32C*",$unique);
8715: }
8716:
8717: sub recprefix {
8718: my $fucourseid=shift;
8719: my $prefix;
8720: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8721: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8722: $prefix=$env{"course.$fucourseid.internal.encpref"};
8723: } else {
8724: $prefix=$perlvar{'lonHostID'};
8725: }
8726: return unpack("%32C*",$prefix);
8727: }
8728:
8729: sub ireceipt {
8730: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
8731:
8732: my $return =&recprefix($fucourseid).'-';
8733:
8734: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8735: $env{'request.state'} eq 'construct') {
8736: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8737: return $return;
8738: }
8739:
8740: my $cuname=unpack("%32C*",$funame);
8741: my $cudom=unpack("%32C*",$fudom);
8742: my $cucourseid=unpack("%32C*",$fucourseid);
8743: my $cusymb=unpack("%32C*",$fusymb);
8744: my $cunique=&recunique($fucourseid);
8745: my $cpart=unpack("%32S*",$part);
8746: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8747:
8748: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
8749:
8750: $return.= ($cunique%$cuname+
8751: $cunique%$cudom+
8752: $cusymb%$cuname+
8753: $cusymb%$cudom+
8754: $cucourseid%$cuname+
8755: $cucourseid%$cudom+
8756: $cpart%$cuname+
8757: $cpart%$cudom);
8758: } else {
8759: $return.= ($cunique%$cuname+
8760: $cunique%$cudom+
8761: $cusymb%$cuname+
8762: $cusymb%$cudom+
8763: $cucourseid%$cuname+
8764: $cucourseid%$cudom);
8765: }
8766: return $return;
8767: }
8768:
8769: sub receipt {
8770: my ($part)=@_;
8771: my ($symb,$courseid,$domain,$name) = &whichuser();
8772: return &ireceipt($name,$domain,$courseid,$symb,$part);
8773: }
8774:
8775: sub whichuser {
8776: my ($passedsymb)=@_;
8777: my ($symb,$courseid,$domain,$name,$publicuser);
8778: if (defined($env{'form.grade_symb'})) {
8779: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8780: my $allowed=&allowed('vgr',$tmp_courseid);
8781: if (!$allowed &&
8782: exists($env{'request.course.sec'}) &&
8783: $env{'request.course.sec'} !~ /^\s*$/) {
8784: $allowed=&allowed('vgr',$tmp_courseid.
8785: '/'.$env{'request.course.sec'});
8786: }
8787: if ($allowed) {
8788: ($symb)=&get_env_multiple('form.grade_symb');
8789: $courseid=$tmp_courseid;
8790: ($domain)=&get_env_multiple('form.grade_domain');
8791: ($name)=&get_env_multiple('form.grade_username');
8792: return ($symb,$courseid,$domain,$name,$publicuser);
8793: }
8794: }
8795: if (!$passedsymb) {
8796: $symb=&symbread();
8797: } else {
8798: $symb=$passedsymb;
8799: }
8800: $courseid=$env{'request.course.id'};
8801: $domain=$env{'user.domain'};
8802: $name=$env{'user.name'};
8803: if ($name eq 'public' && $domain eq 'public') {
8804: if (!defined($env{'form.username'})) {
8805: $env{'form.username'}.=time.rand(10000000);
8806: }
8807: $name.=$env{'form.username'};
8808: }
8809: return ($symb,$courseid,$domain,$name,$publicuser);
8810:
8811: }
8812:
8813: # ------------------------------------------------------------ Serves up a file
8814: # returns either the contents of the file or
8815: # -1 if the file doesn't exist
8816: #
8817: # if the target is a file that was uploaded via DOCS,
8818: # a check will be made to see if a current copy exists on the local server,
8819: # if it does this will be served, otherwise a copy will be retrieved from
8820: # the home server for the course and stored in /home/httpd/html/userfiles on
8821: # the local server.
8822:
8823: sub getfile {
8824: my ($file) = @_;
8825: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8826: &repcopy($file);
8827: return &readfile($file);
8828: }
8829:
8830: sub repcopy_userfile {
8831: my ($file)=@_;
8832: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8833: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
8834: my ($cdom,$cnum,$filename) =
8835: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
8836: my $uri="/uploaded/$cdom/$cnum/$filename";
8837: if (-e "$file") {
8838: # we already have a local copy, check it out
8839: my @fileinfo = stat($file);
8840: my $rtncode;
8841: my $info;
8842: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
8843: if ($lwpresp ne 'ok') {
8844: # there is no such file anymore, even though we had a local copy
8845: if ($rtncode eq '404') {
8846: unlink($file);
8847: }
8848: return -1;
8849: }
8850: if ($info < $fileinfo[9]) {
8851: # nice, the file we have is up-to-date, just say okay
8852: return 'ok';
8853: } else {
8854: # the file is outdated, get rid of it
8855: unlink($file);
8856: }
8857: }
8858: # one way or the other, at this point, we don't have the file
8859: # construct the correct path for the file
8860: my @parts = ($cdom,$cnum);
8861: if ($filename =~ m|^(.+)/[^/]+$|) {
8862: push @parts, split(/\//,$1);
8863: }
8864: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8865: foreach my $part (@parts) {
8866: $path .= '/'.$part;
8867: if (!-e $path) {
8868: mkdir($path,0770);
8869: }
8870: }
8871: # now the path exists for sure
8872: # get a user agent
8873: my $ua=new LWP::UserAgent;
8874: my $transferfile=$file.'.in.transfer';
8875: # FIXME: this should flock
8876: if (-e $transferfile) { return 'ok'; }
8877: my $request;
8878: $uri=~s/^\///;
8879: my $homeserver = &homeserver($cnum,$cdom);
8880: my $protocol = $protocol{$homeserver};
8881: $protocol = 'http' if ($protocol ne 'https');
8882: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
8883: my $response=$ua->request($request,$transferfile);
8884: # did it work?
8885: if ($response->is_error()) {
8886: unlink($transferfile);
8887: &logthis("Userfile repcopy failed for $uri");
8888: return -1;
8889: }
8890: # worked, rename the transfer file
8891: rename($transferfile,$file);
8892: return 'ok';
8893: }
8894:
8895: sub tokenwrapper {
8896: my $uri=shift;
8897: $uri=~s|^https?\://([^/]+)||;
8898: $uri=~s|^/||;
8899: $env{'user.environment'}=~/\/([^\/]+)\.id/;
8900: my $token=$1;
8901: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8902: if ($udom && $uname && $file) {
8903: $file=~s|(\?\.*)*$||;
8904: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
8905: my $homeserver = &homeserver($uname,$udom);
8906: my $protocol = $protocol{$homeserver};
8907: $protocol = 'http' if ($protocol ne 'https');
8908: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
8909: (($uri=~/\?/)?'&':'?').'token='.$token.
8910: '&tokenissued='.$perlvar{'lonHostID'};
8911: } else {
8912: return '/adm/notfound.html';
8913: }
8914: }
8915:
8916: # call with reqtype HEAD: get last modification time
8917: # call with reqtype GET: get the file contents
8918: # Do not call this with reqtype GET for large files! It loads everything into memory
8919: #
8920: sub getuploaded {
8921: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8922: $uri=~s/^\///;
8923: my $homeserver = &homeserver($cnum,$cdom);
8924: my $protocol = $protocol{$homeserver};
8925: $protocol = 'http' if ($protocol ne 'https');
8926: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
8927: my $ua=new LWP::UserAgent;
8928: my $request=new HTTP::Request($reqtype,$uri);
8929: my $response=$ua->request($request);
8930: $$rtncode = $response->code;
8931: if (! $response->is_success()) {
8932: return 'failed';
8933: }
8934: if ($reqtype eq 'HEAD') {
8935: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
8936: } elsif ($reqtype eq 'GET') {
8937: $$info = $response->content;
8938: }
8939: return 'ok';
8940: }
8941:
8942: sub readfile {
8943: my $file = shift;
8944: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8945: my $fh;
8946: open($fh,"<$file");
8947: my $a='';
8948: while (my $line = <$fh>) { $a .= $line; }
8949: return $a;
8950: }
8951:
8952: sub filelocation {
8953: my ($dir,$file) = @_;
8954: my $location;
8955: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
8956:
8957: if ($file =~ m-^/adm/-) {
8958: $file=~s-^/adm/wrapper/-/-;
8959: $file=~s-^/adm/coursedocs/showdoc/-/-;
8960: }
8961:
8962: if ($file=~m:^/~:) { # is a contruction space reference
8963: $location = $file;
8964: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
8965: } elsif ($file=~m{^/home/$match_username/public_html/}) {
8966: # is a correct contruction space reference
8967: $location = $file;
8968: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8969: $location = $file;
8970: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
8971: my ($udom,$uname,$filename)=
8972: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
8973: my $home=&homeserver($uname,$udom);
8974: my $is_me=0;
8975: my @ids=¤t_machine_ids();
8976: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8977: if ($is_me) {
8978: $location=&propath($udom,$uname).'/userfiles/'.$filename;
8979: } else {
8980: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8981: $udom.'/'.$uname.'/'.$filename;
8982: }
8983: } elsif ($file =~ m-^/adm/-) {
8984: $location = $perlvar{'lonDocRoot'}.'/'.$file;
8985: } else {
8986: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8987: $file=~s:^/res/:/:;
8988: if ( !( $file =~ m:^/:) ) {
8989: $location = $dir. '/'.$file;
8990: } else {
8991: $location = '/home/httpd/html/res'.$file;
8992: }
8993: }
8994: $location=~s://+:/:g; # remove duplicate /
8995: while ($location=~m{/\.\./}) {
8996: if ($location =~ m{/[^/]+/\.\./}) {
8997: $location=~ s{/[^/]+/\.\./}{/}g;
8998: } else {
8999: $location=~ s{/\.\./}{/}g;
9000: }
9001: } #remove dir/..
9002: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9003: return $location;
9004: }
9005:
9006: sub hreflocation {
9007: my ($dir,$file)=@_;
9008: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
9009: $file=filelocation($dir,$file);
9010: } elsif ($file=~m-^/adm/-) {
9011: $file=~s-^/adm/wrapper/-/-;
9012: $file=~s-^/adm/coursedocs/showdoc/-/-;
9013: }
9014: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9015: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
9016: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9017: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
9018: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
9019: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
9020: -/uploaded/$1/$2/-x;
9021: }
9022: if ($file=~ m{^/userfiles/}) {
9023: $file =~ s{^/userfiles/}{/uploaded/};
9024: }
9025: return $file;
9026: }
9027:
9028: sub current_machine_domains {
9029: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9030: }
9031:
9032: sub machine_domains {
9033: my ($hostname) = @_;
9034: my @domains;
9035: my %hostname = &all_hostnames();
9036: while( my($id, $name) = each(%hostname)) {
9037: # &logthis("-$id-$name-$hostname-");
9038: if ($hostname eq $name) {
9039: push(@domains,&host_domain($id));
9040: }
9041: }
9042: return @domains;
9043: }
9044:
9045: sub current_machine_ids {
9046: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9047: }
9048:
9049: sub machine_ids {
9050: my ($hostname) = @_;
9051: $hostname ||= &hostname($perlvar{'lonHostID'});
9052: my @ids;
9053: my %name_to_host = &all_names();
9054: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9055: return @{ $name_to_host{$hostname} };
9056: }
9057: return;
9058: }
9059:
9060: sub additional_machine_domains {
9061: my @domains;
9062: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9063: while( my $line = <$fh>) {
9064: $line =~ s/\s//g;
9065: push(@domains,$line);
9066: }
9067: return @domains;
9068: }
9069:
9070: sub default_login_domain {
9071: my $domain = $perlvar{'lonDefDomain'};
9072: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9073: foreach my $posdom (¤t_machine_domains(),
9074: &additional_machine_domains()) {
9075: if (lc($posdom) eq lc($testdomain)) {
9076: $domain=$posdom;
9077: last;
9078: }
9079: }
9080: return $domain;
9081: }
9082:
9083: # ------------------------------------------------------------- Declutters URLs
9084:
9085: sub declutter {
9086: my $thisfn=shift;
9087: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9088: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9089: $thisfn=~s/^\///;
9090: $thisfn=~s|^adm/wrapper/||;
9091: $thisfn=~s|^adm/coursedocs/showdoc/||;
9092: $thisfn=~s/^res\///;
9093: $thisfn=~s/\?.+$//;
9094: return $thisfn;
9095: }
9096:
9097: # ------------------------------------------------------------- Clutter up URLs
9098:
9099: sub clutter {
9100: my $thisfn='/'.&declutter(shift);
9101: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
9102: || $thisfn =~ m{^/adm/(includes|pages)} ) {
9103: $thisfn='/res'.$thisfn;
9104: }
9105: if ($thisfn !~m|/adm|) {
9106: if ($thisfn =~ m|/ext/|) {
9107: $thisfn='/adm/wrapper'.$thisfn;
9108: } else {
9109: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9110: my $embstyle=&Apache::loncommon::fileembstyle($ext);
9111: if ($embstyle eq 'ssi'
9112: || ($embstyle eq 'hdn')
9113: || ($embstyle eq 'rat')
9114: || ($embstyle eq 'prv')
9115: || ($embstyle eq 'ign')) {
9116: #do nothing with these
9117: } elsif (($embstyle eq 'img')
9118: || ($embstyle eq 'emb')
9119: || ($embstyle eq 'wrp')) {
9120: $thisfn='/adm/wrapper'.$thisfn;
9121: } elsif ($embstyle eq 'unk'
9122: && $thisfn!~/\.(sequence|page)$/) {
9123: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
9124: } else {
9125: # &logthis("Got a blank emb style");
9126: }
9127: }
9128: }
9129: return $thisfn;
9130: }
9131:
9132: sub clutter_with_no_wrapper {
9133: my $uri = &clutter(shift);
9134: if ($uri =~ m-^/adm/-) {
9135: $uri =~ s-^/adm/wrapper/-/-;
9136: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9137: }
9138: return $uri;
9139: }
9140:
9141: sub freeze_escape {
9142: my ($value)=@_;
9143: if (ref($value)) {
9144: $value=&nfreeze($value);
9145: return '__FROZEN__'.&escape($value);
9146: }
9147: return &escape($value);
9148: }
9149:
9150:
9151: sub thaw_unescape {
9152: my ($value)=@_;
9153: if ($value =~ /^__FROZEN__/) {
9154: substr($value,0,10,undef);
9155: $value=&unescape($value);
9156: return &thaw($value);
9157: }
9158: return &unescape($value);
9159: }
9160:
9161: sub correct_line_ends {
9162: my ($result)=@_;
9163: $$result =~s/\r\n/\n/mg;
9164: $$result =~s/\r/\n/mg;
9165: }
9166: # ================================================================ Main Program
9167:
9168: sub goodbye {
9169: &logthis("Starting Shut down");
9170: #not converted to using infrastruture and probably shouldn't be
9171: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
9172: #converted
9173: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
9174: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9175: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9176: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
9177: #1.1 only
9178: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9179: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9180: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9181: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9182: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
9183: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9184: &logthis(sprintf("%-20s is %s",'hits',$hits));
9185: &flushcourselogs();
9186: &logthis("Shutting down");
9187: }
9188:
9189: sub get_dns {
9190: my ($url,$func,$ignore_cache) = @_;
9191: if (!$ignore_cache) {
9192: my ($content,$cached)=
9193: &Apache::lonnet::is_cached_new('dns',$url);
9194: if ($cached) {
9195: &$func($content);
9196: return;
9197: }
9198: }
9199:
9200: my %alldns;
9201: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9202: foreach my $dns (<$config>) {
9203: next if ($dns !~ /^\^(\S*)/x);
9204: my $line = $1;
9205: my ($host,$protocol) = split(/:/,$line);
9206: if ($protocol ne 'https') {
9207: $protocol = 'http';
9208: }
9209: $alldns{$host} = $protocol;
9210: }
9211: while (%alldns) {
9212: my ($dns) = keys(%alldns);
9213: my $ua=new LWP::UserAgent;
9214: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
9215: my $response=$ua->request($request);
9216: delete($alldns{$dns});
9217: next if ($response->is_error());
9218: my @content = split("\n",$response->content);
9219: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
9220: &$func(\@content);
9221: return;
9222: }
9223: close($config);
9224: my $which = (split('/',$url))[3];
9225: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9226: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
9227: my @content = <$config>;
9228: &$func(\@content);
9229: return;
9230: }
9231: # ------------------------------------------------------------ Read domain file
9232: {
9233: my $loaded;
9234: my %domain;
9235:
9236: sub parse_domain_tab {
9237: my ($lines) = @_;
9238: foreach my $line (@$lines) {
9239: next if ($line =~ /^(\#|\s*$ )/x);
9240:
9241: chomp($line);
9242: my ($name,@elements) = split(/:/,$line,9);
9243: my %this_domain;
9244: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9245: 'lang_def', 'city', 'longi', 'lati',
9246: 'primary') {
9247: $this_domain{$field} = shift(@elements);
9248: }
9249: $domain{$name} = \%this_domain;
9250: }
9251: }
9252:
9253: sub reset_domain_info {
9254: undef($loaded);
9255: undef(%domain);
9256: }
9257:
9258: sub load_domain_tab {
9259: my ($ignore_cache) = @_;
9260: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
9261: my $fh;
9262: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9263: my @lines = <$fh>;
9264: &parse_domain_tab(\@lines);
9265: }
9266: close($fh);
9267: $loaded = 1;
9268: }
9269:
9270: sub domain {
9271: &load_domain_tab() if (!$loaded);
9272:
9273: my ($name,$what) = @_;
9274: return if ( !exists($domain{$name}) );
9275:
9276: if (!$what) {
9277: return $domain{$name}{'description'};
9278: }
9279: return $domain{$name}{$what};
9280: }
9281:
9282: sub domain_info {
9283: &load_domain_tab() if (!$loaded);
9284: return %domain;
9285: }
9286:
9287: }
9288:
9289:
9290: # ------------------------------------------------------------- Read hosts file
9291: {
9292: my %hostname;
9293: my %hostdom;
9294: my %libserv;
9295: my $loaded;
9296: my %name_to_host;
9297:
9298: sub parse_hosts_tab {
9299: my ($file) = @_;
9300: foreach my $configline (@$file) {
9301: next if ($configline =~ /^(\#|\s*$ )/x);
9302: next if ($configline =~ /^\^/);
9303: chomp($configline);
9304: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
9305: $name=~s/\s//g;
9306: if ($id && $domain && $role && $name) {
9307: $hostname{$id}=$name;
9308: push(@{$name_to_host{$name}}, $id);
9309: $hostdom{$id}=$domain;
9310: if ($role eq 'library') { $libserv{$id}=$name; }
9311: if (defined($protocol)) {
9312: if ($protocol eq 'https') {
9313: $protocol{$id} = $protocol;
9314: } else {
9315: $protocol{$id} = 'http';
9316: }
9317: } else {
9318: $protocol{$id} = 'http';
9319: }
9320: }
9321: }
9322: }
9323:
9324: sub reset_hosts_info {
9325: &purge_remembered();
9326: &reset_domain_info();
9327: &reset_hosts_ip_info();
9328: undef(%name_to_host);
9329: undef(%hostname);
9330: undef(%hostdom);
9331: undef(%libserv);
9332: undef($loaded);
9333: }
9334:
9335: sub load_hosts_tab {
9336: my ($ignore_cache) = @_;
9337: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
9338: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9339: my @config = <$config>;
9340: &parse_hosts_tab(\@config);
9341: close($config);
9342: $loaded=1;
9343: }
9344:
9345: sub hostname {
9346: &load_hosts_tab() if (!$loaded);
9347:
9348: my ($lonid) = @_;
9349: return $hostname{$lonid};
9350: }
9351:
9352: sub all_hostnames {
9353: &load_hosts_tab() if (!$loaded);
9354:
9355: return %hostname;
9356: }
9357:
9358: sub all_names {
9359: &load_hosts_tab() if (!$loaded);
9360:
9361: return %name_to_host;
9362: }
9363:
9364: sub all_host_domain {
9365: &load_hosts_tab() if (!$loaded);
9366: return %hostdom;
9367: }
9368:
9369: sub is_library {
9370: &load_hosts_tab() if (!$loaded);
9371:
9372: return exists($libserv{$_[0]});
9373: }
9374:
9375: sub all_library {
9376: &load_hosts_tab() if (!$loaded);
9377:
9378: return %libserv;
9379: }
9380:
9381: sub get_servers {
9382: &load_hosts_tab() if (!$loaded);
9383:
9384: my ($domain,$type) = @_;
9385: my %possible_hosts = ($type eq 'library') ? %libserv
9386: : %hostname;
9387: my %result;
9388: if (ref($domain) eq 'ARRAY') {
9389: while ( my ($host,$hostname) = each(%possible_hosts)) {
9390: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
9391: $result{$host} = $hostname;
9392: }
9393: }
9394: } else {
9395: while ( my ($host,$hostname) = each(%possible_hosts)) {
9396: if ($hostdom{$host} eq $domain) {
9397: $result{$host} = $hostname;
9398: }
9399: }
9400: }
9401: return %result;
9402: }
9403:
9404: sub host_domain {
9405: &load_hosts_tab() if (!$loaded);
9406:
9407: my ($lonid) = @_;
9408: return $hostdom{$lonid};
9409: }
9410:
9411: sub all_domains {
9412: &load_hosts_tab() if (!$loaded);
9413:
9414: my %seen;
9415: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9416: return @uniq;
9417: }
9418: }
9419:
9420: {
9421: my %iphost;
9422: my %name_to_ip;
9423: my %lonid_to_ip;
9424:
9425: sub get_hosts_from_ip {
9426: my ($ip) = @_;
9427: my %iphosts = &get_iphost();
9428: if (ref($iphosts{$ip})) {
9429: return @{$iphosts{$ip}};
9430: }
9431: return;
9432: }
9433:
9434: sub reset_hosts_ip_info {
9435: undef(%iphost);
9436: undef(%name_to_ip);
9437: undef(%lonid_to_ip);
9438: }
9439:
9440: sub get_host_ip {
9441: my ($lonid) = @_;
9442: if (exists($lonid_to_ip{$lonid})) {
9443: return $lonid_to_ip{$lonid};
9444: }
9445: my $name=&hostname($lonid);
9446: my $ip = gethostbyname($name);
9447: return if (!$ip || length($ip) ne 4);
9448: $ip=inet_ntoa($ip);
9449: $name_to_ip{$name} = $ip;
9450: $lonid_to_ip{$lonid} = $ip;
9451: return $ip;
9452: }
9453:
9454: sub get_iphost {
9455: my ($ignore_cache) = @_;
9456:
9457: if (!$ignore_cache) {
9458: if (%iphost) {
9459: return %iphost;
9460: }
9461: my ($ip_info,$cached)=
9462: &Apache::lonnet::is_cached_new('iphost','iphost');
9463: if ($cached) {
9464: %iphost = %{$ip_info->[0]};
9465: %name_to_ip = %{$ip_info->[1]};
9466: %lonid_to_ip = %{$ip_info->[2]};
9467: return %iphost;
9468: }
9469: }
9470:
9471: # get yesterday's info for fallback
9472: my %old_name_to_ip;
9473: my ($ip_info,$cached)=
9474: &Apache::lonnet::is_cached_new('iphost','iphost');
9475: if ($cached) {
9476: %old_name_to_ip = %{$ip_info->[1]};
9477: }
9478:
9479: my %name_to_host = &all_names();
9480: foreach my $name (keys(%name_to_host)) {
9481: my $ip;
9482: if (!exists($name_to_ip{$name})) {
9483: $ip = gethostbyname($name);
9484: if (!$ip || length($ip) ne 4) {
9485: if (defined($old_name_to_ip{$name})) {
9486: $ip = $old_name_to_ip{$name};
9487: &logthis("Can't find $name defaulting to old $ip");
9488: } else {
9489: &logthis("Name $name no IP found");
9490: next;
9491: }
9492: } else {
9493: $ip=inet_ntoa($ip);
9494: }
9495: $name_to_ip{$name} = $ip;
9496: } else {
9497: $ip = $name_to_ip{$name};
9498: }
9499: foreach my $id (@{ $name_to_host{$name} }) {
9500: $lonid_to_ip{$id} = $ip;
9501: }
9502: push(@{$iphost{$ip}},@{$name_to_host{$name}});
9503: }
9504: &Apache::lonnet::do_cache_new('iphost','iphost',
9505: [\%iphost,\%name_to_ip,\%lonid_to_ip],
9506: 48*60*60);
9507:
9508: return %iphost;
9509: }
9510:
9511: #
9512: # Given a DNS returns the loncapa host name for that DNS
9513: #
9514: sub host_from_dns {
9515: my ($dns) = @_;
9516: my @hosts;
9517: my $ip;
9518:
9519: if (exists($name_to_ip{$dns})) {
9520: $ip = $name_to_ip{$dns};
9521: }
9522: if (!$ip) {
9523: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9524: if (length($ip) == 4) {
9525: $ip = &IO::Socket::inet_ntoa($ip);
9526: }
9527: }
9528: if ($ip) {
9529: @hosts = get_hosts_from_ip($ip);
9530: return $hosts[0];
9531: }
9532: return undef;
9533: }
9534:
9535: }
9536:
9537: BEGIN {
9538:
9539: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9540: unless ($readit) {
9541: {
9542: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9543: %perlvar = (%perlvar,%{$configvars});
9544: }
9545:
9546:
9547: # ------------------------------------------------------ Read spare server file
9548: {
9549: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
9550:
9551: while (my $configline=<$config>) {
9552: chomp($configline);
9553: if ($configline) {
9554: my ($host,$type) = split(':',$configline,2);
9555: if (!defined($type) || $type eq '') { $type = 'default' };
9556: push(@{ $spareid{$type} }, $host);
9557: }
9558: }
9559: close($config);
9560: }
9561: # ------------------------------------------------------------ Read permissions
9562: {
9563: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
9564:
9565: while (my $configline=<$config>) {
9566: chomp($configline);
9567: if ($configline) {
9568: my ($role,$perm)=split(/ /,$configline);
9569: if ($perm ne '') { $pr{$role}=$perm; }
9570: }
9571: }
9572: close($config);
9573: }
9574:
9575: # -------------------------------------------- Read plain texts for permissions
9576: {
9577: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
9578:
9579: while (my $configline=<$config>) {
9580: chomp($configline);
9581: if ($configline) {
9582: my ($short,@plain)=split(/:/,$configline);
9583: %{$prp{$short}} = ();
9584: if (@plain > 0) {
9585: $prp{$short}{'std'} = $plain[0];
9586: for (my $i=1; $i<@plain; $i++) {
9587: $prp{$short}{'alt'.$i} = $plain[$i];
9588: }
9589: }
9590: }
9591: }
9592: close($config);
9593: }
9594:
9595: # ---------------------------------------------------------- Read package table
9596: {
9597: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
9598:
9599: while (my $configline=<$config>) {
9600: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
9601: chomp($configline);
9602: my ($short,$plain)=split(/:/,$configline);
9603: my ($pack,$name)=split(/\&/,$short);
9604: if ($plain ne '') {
9605: $packagetab{$pack.'&'.$name.'&name'}=$name;
9606: $packagetab{$short}=$plain;
9607: }
9608: }
9609: close($config);
9610: }
9611:
9612: # ------------- set up temporary directory
9613: {
9614: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9615:
9616: }
9617:
9618: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9619: 'compress_threshold'=> 20_000,
9620: });
9621:
9622: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
9623: $dumpcount=0;
9624: $locknum=0;
9625:
9626: &logtouch();
9627: &logthis('<font color="yellow">INFO: Read configuration</font>');
9628: $readit=1;
9629: {
9630: use integer;
9631: my $test=(2**32)+1;
9632: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
9633: &logthis(" Detected 64bit platform ($_64bit)");
9634: }
9635: }
9636: }
9637:
9638: 1;
9639: __END__
9640:
9641: =pod
9642:
9643: =head1 NAME
9644:
9645: Apache::lonnet - Subroutines to ask questions about things in the network.
9646:
9647: =head1 SYNOPSIS
9648:
9649: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
9650:
9651: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9652:
9653: Common parameters:
9654:
9655: =over 4
9656:
9657: =item *
9658:
9659: $uname : an internal username (if $cname expecting a course Id specifically)
9660:
9661: =item *
9662:
9663: $udom : a domain (if $cdom expecting a course's domain specifically)
9664:
9665: =item *
9666:
9667: $symb : a resource instance identifier
9668:
9669: =item *
9670:
9671: $namespace : the name of a .db file that contains the data needed or
9672: being set.
9673:
9674: =back
9675:
9676: =head1 OVERVIEW
9677:
9678: lonnet provides subroutines which interact with the
9679: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9680: about classes, users, and resources.
9681:
9682: For many of these objects you can also use this to store data about
9683: them or modify them in various ways.
9684:
9685: =head2 Symbs
9686:
9687: To identify a specific instance of a resource, LON-CAPA uses symbols
9688: or "symbs"X<symb>. These identifiers are built from the URL of the
9689: map, the resource number of the resource in the map, and the URL of
9690: the resource itself. The latter is somewhat redundant, but might help
9691: if maps change.
9692:
9693: An example is
9694:
9695: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9696:
9697: The respective map entry is
9698:
9699: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9700: title="Problem 2">
9701: </resource>
9702:
9703: Symbs are used by the random number generator, as well as to store and
9704: restore data specific to a certain instance of for example a problem.
9705:
9706: =head2 Storing And Retrieving Data
9707:
9708: X<store()>X<cstore()>X<restore()>Three of the most important functions
9709: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9710: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9711: is is the non-critical message twin of cstore. These functions are for
9712: handlers to store a perl hash to a user's permanent data space in an
9713: easy manner, and to retrieve it again on another call. It is expected
9714: that a handler would use this once at the beginning to retrieve data,
9715: and then again once at the end to send only the new data back.
9716:
9717: The data is stored in the user's data directory on the user's
9718: homeserver under the ID of the course.
9719:
9720: The hash that is returned by restore will have all of the previous
9721: value for all of the elements of the hash.
9722:
9723: Example:
9724:
9725: #creating a hash
9726: my %hash;
9727: $hash{'foo'}='bar';
9728:
9729: #storing it
9730: &Apache::lonnet::cstore(\%hash);
9731:
9732: #changing a value
9733: $hash{'foo'}='notbar';
9734:
9735: #adding a new value
9736: $hash{'bar'}='foo';
9737: &Apache::lonnet::cstore(\%hash);
9738:
9739: #retrieving the hash
9740: my %history=&Apache::lonnet::restore();
9741:
9742: #print the hash
9743: foreach my $key (sort(keys(%history))) {
9744: print("\%history{$key} = $history{$key}");
9745: }
9746:
9747: Will print out:
9748:
9749: %history{1:foo} = bar
9750: %history{1:keys} = foo:timestamp
9751: %history{1:timestamp} = 990455579
9752: %history{2:bar} = foo
9753: %history{2:foo} = notbar
9754: %history{2:keys} = foo:bar:timestamp
9755: %history{2:timestamp} = 990455580
9756: %history{bar} = foo
9757: %history{foo} = notbar
9758: %history{timestamp} = 990455580
9759: %history{version} = 2
9760:
9761: Note that the special hash entries C<keys>, C<version> and
9762: C<timestamp> were added to the hash. C<version> will be equal to the
9763: total number of versions of the data that have been stored. The
9764: C<timestamp> attribute will be the UNIX time the hash was
9765: stored. C<keys> is available in every historical section to list which
9766: keys were added or changed at a specific historical revision of a
9767: hash.
9768:
9769: B<Warning>: do not store the hash that restore returns directly. This
9770: will cause a mess since it will restore the historical keys as if the
9771: were new keys. I.E. 1:foo will become 1:1:foo etc.
9772:
9773: Calling convention:
9774:
9775: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9776: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
9777:
9778: For more detailed information, see lonnet specific documentation.
9779:
9780: =head1 RETURN MESSAGES
9781:
9782: =over 4
9783:
9784: =item * B<con_lost>: unable to contact remote host
9785:
9786: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9787: when the connection is brought back up
9788:
9789: =item * B<con_failed>: unable to contact remote host and unable to save message
9790: for later delivery
9791:
9792: =item * B<error:>: an error a occurred, a description of the error follows the :
9793:
9794: =item * B<no_such_host>: unable to fund a host associated with the user/domain
9795: that was requested
9796:
9797: =back
9798:
9799: =head1 PUBLIC SUBROUTINES
9800:
9801: =head2 Session Environment Functions
9802:
9803: =over 4
9804:
9805: =item *
9806: X<appenv()>
9807: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
9808: the user envirnoment file, and will be restored for each access this
9809: user makes during this session, also modifies the %env for the current
9810: process. Optional rolesarrayref - if defined contains a reference to an array
9811: of roles which are exempt from the restriction on modifying user.role entries
9812: in the user's environment.db and in %env.
9813:
9814: =item *
9815: X<delenv()>
9816: B<delenv($delthis,$regexp)>: removes all items from the session
9817: environment file that begin with $delthis. If the
9818: optional second arg - $regexp - is true, $delthis is treated as a
9819: regular expression, otherwise \Q$delthis\E is used.
9820: The values are also deleted from the current processes %env.
9821:
9822: =item * get_env_multiple($name)
9823:
9824: gets $name from the %env hash, it seemlessly handles the cases where multiple
9825: values may be defined and end up as an array ref.
9826:
9827: returns an array of values
9828:
9829: =back
9830:
9831: =head2 User Information
9832:
9833: =over 4
9834:
9835: =item *
9836: X<queryauthenticate()>
9837: B<queryauthenticate($uname,$udom)>: try to determine user's current
9838: authentication scheme
9839:
9840: =item *
9841: X<authenticate()>
9842: B<authenticate($uname,$upass,$udom)>: try to
9843: authenticate user from domain's lib servers (first use the current
9844: one). C<$upass> should be the users password.
9845:
9846: =item *
9847: X<homeserver()>
9848: B<homeserver($uname,$udom)>: find the server which has
9849: the user's directory and files (there must be only one), this caches
9850: the answer, and also caches if there is a borken connection.
9851:
9852: =item *
9853: X<idget()>
9854: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9855: (IDs are a unique resource in a domain, there must be only 1 ID per
9856: username, and only 1 username per ID in a specific domain) (returns
9857: hash: id=>name,id=>name)
9858:
9859: =item *
9860: X<idrget()>
9861: B<idrget($udom,@unames)>: find the IDs behind a list of
9862: usernames (returns hash: name=>id,name=>id)
9863:
9864: =item *
9865: X<idput()>
9866: B<idput($udom,%ids)>: store away a list of names and associated IDs
9867:
9868: =item *
9869: X<rolesinit()>
9870: B<rolesinit($udom,$username,$authhost)>: get user privileges
9871:
9872: =item *
9873: X<getsection()>
9874: B<getsection($udom,$uname,$cname)>: finds the section of student in the
9875: course $cname, return section name/number or '' for "not in course"
9876: and '-1' for "no section"
9877:
9878: =item *
9879: X<userenvironment()>
9880: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
9881: passed in @what from the requested user's environment, returns a hash
9882:
9883: =item *
9884: X<userlog_query()>
9885: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9886: activity.log file. %filters defines filters applied when parsing the
9887: log file. These can be start or end timestamps, or the type of action
9888: - log to look for Login or Logout events, check for Checkin or
9889: Checkout, role for role selection. The response is in the form
9890: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9891: escaped strings of the action recorded in the activity.log file.
9892:
9893: =back
9894:
9895: =head2 User Roles
9896:
9897: =over 4
9898:
9899: =item *
9900:
9901: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
9902: F: full access
9903: U,I,K: authentication modes (cxx only)
9904: '': forbidden
9905: 1: user needs to choose course
9906: 2: browse allowed
9907: A: passphrase authentication needed
9908:
9909: =item *
9910:
9911: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9912: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9913: and course level
9914:
9915: =item *
9916:
9917: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
9918: (rolesplain.tab); plain text explanation of a user role term.
9919: $type is Course (default) or Community.
9920: If $forcedefault evaluates to true, text returned will be default
9921: text for $type. Otherwise, if this is a course, the text returned
9922: will be a custom name for the role (if defined in the course's
9923: environment). If no custom name is defined the default is returned.
9924:
9925: =item *
9926:
9927: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
9928: All arguments are optional. Returns a hash of a roles, either for
9929: co-author/assistant author roles for a user's Construction Space
9930: (default), or if $context is 'userroles', roles for the user himself,
9931: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9932: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9933: For each key, value is set to colon-separated start and end times for
9934: the role. If no username and domain are specified, will default to
9935: current user/domain. Types, roles, and roledoms are references to arrays
9936: of role statuses (active, future or previous), roles
9937: (e.g., cc,in, st etc.) and domains of the roles which can be used
9938: to restrict the list of roles reported. If no array ref is
9939: provided for types, will default to return only active roles.
9940:
9941: =back
9942:
9943: =head2 User Modification
9944:
9945: =over 4
9946:
9947: =item *
9948:
9949: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
9950: user for the level given by URL. Optional start and end dates (leave empty
9951: string or zero for "no date")
9952:
9953: =item *
9954:
9955: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9956: change a users, password, possible return values are: ok,
9957: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9958: refused
9959:
9960: =item *
9961:
9962: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
9963:
9964: =item *
9965:
9966: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9967: $forceid,$desiredhome,$email,$inststatus) :
9968: modify user
9969:
9970: =item *
9971:
9972: modifystudent
9973:
9974: modify a student's enrollment and identification information.
9975: The course id is resolved based on the current users environment.
9976: This means the envoking user must be a course coordinator or otherwise
9977: associated with a course.
9978:
9979: This call is essentially a wrapper for lonnet::modifyuser and
9980: lonnet::modify_student_enrollment
9981:
9982: Inputs:
9983:
9984: =over 4
9985:
9986: =item B<$udom> Student's loncapa domain
9987:
9988: =item B<$uname> Student's loncapa login name
9989:
9990: =item B<$uid> Student/Employee ID
9991:
9992: =item B<$umode> Student's authentication mode
9993:
9994: =item B<$upass> Student's password
9995:
9996: =item B<$first> Student's first name
9997:
9998: =item B<$middle> Student's middle name
9999:
10000: =item B<$last> Student's last name
10001:
10002: =item B<$gene> Student's generation
10003:
10004: =item B<$usec> Student's section in course
10005:
10006: =item B<$end> Unix time of the roles expiration
10007:
10008: =item B<$start> Unix time of the roles start date
10009:
10010: =item B<$forceid> If defined, allow $uid to be changed
10011:
10012: =item B<$desiredhome> server to use as home server for student
10013:
10014: =item B<$email> Student's permanent e-mail address
10015:
10016: =item B<$type> Type of enrollment (auto or manual)
10017:
10018: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10019:
10020: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10021:
10022: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10023:
10024: =item B<$context> role change context (shown in User Management Logs display in a course)
10025:
10026: =item B<$inststatus> institutional status of user - : separated string of escaped status types
10027:
10028: =back
10029:
10030: =item *
10031:
10032: modify_student_enrollment
10033:
10034: Change a students enrollment status in a class. The environment variable
10035: 'role.request.course' must be defined for this function to proceed.
10036:
10037: Inputs:
10038:
10039: =over 4
10040:
10041: =item $udom, students domain
10042:
10043: =item $uname, students name
10044:
10045: =item $uid, students user id
10046:
10047: =item $first, students first name
10048:
10049: =item $middle
10050:
10051: =item $last
10052:
10053: =item $gene
10054:
10055: =item $usec
10056:
10057: =item $end
10058:
10059: =item $start
10060:
10061: =item $type
10062:
10063: =item $locktype
10064:
10065: =item $cid
10066:
10067: =item $selfenroll
10068:
10069: =item $context
10070:
10071: =back
10072:
10073:
10074: =item *
10075:
10076: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10077: custom role; give a custom role to a user for the level given by URL. Specify
10078: name and domain of role author, and role name
10079:
10080: =item *
10081:
10082: revokerole($udom,$uname,$url,$role) : revoke a role for url
10083:
10084: =item *
10085:
10086: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10087:
10088: =back
10089:
10090: =head2 Course Infomation
10091:
10092: =over 4
10093:
10094: =item *
10095:
10096: coursedescription($courseid) : returns a hash of information about the
10097: specified course id, including all environment settings for the
10098: course, the description of the course will be in the hash under the
10099: key 'description'
10100:
10101: =item *
10102:
10103: resdata($name,$domain,$type,@which) : request for current parameter
10104: setting for a specific $type, where $type is either 'course' or 'user',
10105: @what should be a list of parameters to ask about. This routine caches
10106: answers for 5 minutes.
10107:
10108: =item *
10109:
10110: get_courseresdata($courseid, $domain) : dump the entire course resource
10111: data base, returning a hash that is keyed by the resource name and has
10112: values that are the resource value. I believe that the timestamps and
10113: versions are also returned.
10114:
10115:
10116: =back
10117:
10118: =head2 Course Modification
10119:
10120: =over 4
10121:
10122: =item *
10123:
10124: writecoursepref($courseid,%prefs) : write preferences (environment
10125: database) for a course
10126:
10127: =item *
10128:
10129: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10130:
10131: =item *
10132:
10133: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
10134:
10135: =back
10136:
10137: =head2 Resource Subroutines
10138:
10139: =over 4
10140:
10141: =item *
10142:
10143: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10144:
10145: =item *
10146:
10147: repcopy($filename) : subscribes to the requested file, and attempts to
10148: replicate from the owning library server, Might return
10149: 'unavailable', 'not_found', 'forbidden', 'ok', or
10150: 'bad_request', also attempts to grab the metadata for the
10151: resource. Expects the local filesystem pathname
10152: (/home/httpd/html/res/....)
10153:
10154: =back
10155:
10156: =head2 Resource Information
10157:
10158: =over 4
10159:
10160: =item *
10161:
10162: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10163: a vairety of different possible values, $varname should be a request
10164: string, and the other parameters can be used to specify who and what
10165: one is asking about.
10166:
10167: Possible values for $varname are environment.lastname (or other item
10168: from the envirnment hash), user.name (or someother aspect about the
10169: user), resource.0.maxtries (or some other part and parameter of a
10170: resource)
10171:
10172: =item *
10173:
10174: directcondval($number) : get current value of a condition; reads from a state
10175: string
10176:
10177: =item *
10178:
10179: condval($condidx) : value of condition index based on state
10180:
10181: =item *
10182:
10183: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10184: resource's metadata, $what should be either a specific key, or either
10185: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10186: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10187:
10188: this function automatically caches all requests
10189:
10190: =item *
10191:
10192: metadata_query($query,$custom,$customshow) : make a metadata query against the
10193: network of library servers; returns file handle of where SQL and regex results
10194: will be stored for query
10195:
10196: =item *
10197:
10198: symbread($filename) : return symbolic list entry (filename argument optional);
10199: returns the data handle
10200:
10201: =item *
10202:
10203: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10204: a possible symb for the URL in $thisfn, and if is an encryypted
10205: resource that the user accessed using /enc/ returns a 1 on success, 0
10206: on failure, user must be in a course, as it assumes the existance of
10207: the course initial hash, and uses $env('request.course.id'}
10208:
10209:
10210: =item *
10211:
10212: symbclean($symb) : removes versions numbers from a symb, returns the
10213: cleaned symb
10214:
10215: =item *
10216:
10217: is_on_map($uri) : checks if the $uri is somewhere on the current
10218: course map, user must be in a course for it to work.
10219:
10220: =item *
10221:
10222: numval($salt) : return random seed value (addend for rndseed)
10223:
10224: =item *
10225:
10226: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10227: a random seed, all arguments are optional, if they aren't sent it uses the
10228: environment to derive them. Note: if symb isn't sent and it can't get one
10229: from &symbread it will use the current time as its return value
10230:
10231: =item *
10232:
10233: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10234: unfakeable, receipt
10235:
10236: =item *
10237:
10238: receipt() : API to ireceipt working off of env values; given out to users
10239:
10240: =item *
10241:
10242: countacc($url) : count the number of accesses to a given URL
10243:
10244: =item *
10245:
10246: 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
10247:
10248: =item *
10249:
10250: 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)
10251:
10252: =item *
10253:
10254: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10255:
10256: =item *
10257:
10258: devalidate($symb) : devalidate temporary spreadsheet calculations,
10259: forcing spreadsheet to reevaluate the resource scores next time.
10260:
10261: =back
10262:
10263: =head2 Storing/Retreiving Data
10264:
10265: =over 4
10266:
10267: =item *
10268:
10269: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10270: for this url; hashref needs to be given and should be a \%hashname; the
10271: remaining args aren't required and if they aren't passed or are '' they will
10272: be derived from the env
10273:
10274: =item *
10275:
10276: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10277: uses critical subroutine
10278:
10279: =item *
10280:
10281: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10282: all args are optional
10283:
10284: =item *
10285:
10286: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10287: dumps the complete (or key matching regexp) namespace into a hash
10288: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10289: normally &store()ed into
10290:
10291: $range should be either an integer '100' (give me the first 100
10292: matching records)
10293: or be two integers sperated by a - with no spaces
10294: '30-50' (give me the 30th through the 50th matching
10295: records)
10296:
10297:
10298: =item *
10299:
10300: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10301: replaces a &store() version of data with a replacement set of data
10302: for a particular resource in a namespace passed in the $storehash hash
10303: reference
10304:
10305: =item *
10306:
10307: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10308: works very similar to store/cstore, but all data is stored in a
10309: temporary location and can be reset using tmpreset, $storehash should
10310: be a hash reference, returns nothing on success
10311:
10312: =item *
10313:
10314: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10315: similar to restore, but all data is stored in a temporary location and
10316: can be reset using tmpreset. Returns a hash of values on success,
10317: error string otherwise.
10318:
10319: =item *
10320:
10321: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10322: deltes all keys for $symb form the temporary storage hash.
10323:
10324: =item *
10325:
10326: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10327: reference filled in from namesp ($udom and $uname are optional)
10328:
10329: =item *
10330:
10331: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10332: namesp ($udom and $uname are optional)
10333:
10334: =item *
10335:
10336: dump($namespace,$udom,$uname,$regexp,$range) :
10337: dumps the complete (or key matching regexp) namespace into a hash
10338: ($udom, $uname, $regexp, $range are optional)
10339:
10340: $range should be either an integer '100' (give me the first 100
10341: matching records)
10342: or be two integers sperated by a - with no spaces
10343: '30-50' (give me the 30th through the 50th matching
10344: records)
10345: =item *
10346:
10347: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10348: $store can be a scalar, an array reference, or if the amount to be
10349: incremented is > 1, a hash reference.
10350:
10351: ($udom and $uname are optional)
10352:
10353: =item *
10354:
10355: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10356: ($udom and $uname are optional)
10357:
10358: =item *
10359:
10360: cput($namespace,$storehash,$udom,$uname) : critical put
10361: ($udom and $uname are optional)
10362:
10363: =item *
10364:
10365: newput($namespace,$storehash,$udom,$uname) :
10366:
10367: Attempts to store the items in the $storehash, but only if they don't
10368: currently exist, if this succeeds you can be certain that you have
10369: successfully created a new key value pair in the $namespace db.
10370:
10371:
10372: Args:
10373: $namespace: name of database to store values to
10374: $storehash: hashref to store to the db
10375: $udom: (optional) domain of user containing the db
10376: $uname: (optional) name of user caontaining the db
10377:
10378: Returns:
10379: 'ok' -> succeeded in storing all keys of $storehash
10380: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10381: least <key> already existed in the db (other
10382: requested keys may also already exist)
10383: 'error: <msg>' -> unable to tie the DB or other error occurred
10384: 'con_lost' -> unable to contact request server
10385: 'refused' -> action was not allowed by remote machine
10386:
10387:
10388: =item *
10389:
10390: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10391: reference filled in from namesp (encrypts the return communication)
10392: ($udom and $uname are optional)
10393:
10394: =item *
10395:
10396: log($udom,$name,$home,$message) : write to permanent log for user; use
10397: critical subroutine
10398:
10399: =item *
10400:
10401: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10402: array reference filled in from namespace found in domain level on either
10403: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10404:
10405: =item *
10406:
10407: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10408: domain level either on specified domain server ($uhome) or primary domain
10409: server ($udom and $uhome are optional)
10410:
10411: =item *
10412:
10413: get_domain_defaults($target_domain) : returns hash with defaults for
10414: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10415: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10416: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10417: Values are retrieved from cache (if current), or from domain's configuration.db
10418: (if available), or lastly from values in lonTabs/dns_domain,tab,
10419: or lonTabs/domain.tab.
10420:
10421: %domdefaults = &get_auth_defaults($target_domain);
10422:
10423: =back
10424:
10425: =head2 Network Status Functions
10426:
10427: =over 4
10428:
10429: =item *
10430:
10431: dirlist($uri) : return directory list based on URI
10432:
10433: =item *
10434:
10435: spareserver() : find server with least workload from spare.tab
10436:
10437:
10438: =item *
10439:
10440: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10441: if there is no corresponding loncapa host.
10442:
10443: =back
10444:
10445:
10446: =head2 Apache Request
10447:
10448: =over 4
10449:
10450: =item *
10451:
10452: ssi($url,%hash) : server side include, does a complete request cycle on url to
10453: localhost, posts hash
10454:
10455: =back
10456:
10457: =head2 Data to String to Data
10458:
10459: =over 4
10460:
10461: =item *
10462:
10463: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10464: and '&' separators, supports elements that are arrayrefs and hashrefs
10465:
10466: =item *
10467:
10468: hashref2str($hashref) : convert a hashref into a string complete with
10469: escaping and '=' and '&' separators, supports elements that are
10470: arrayrefs and hashrefs
10471:
10472: =item *
10473:
10474: arrayref2str($arrayref) : convert an arrayref into a string complete
10475: with escaping and '&' separators, supports elements that are arrayrefs
10476: and hashrefs
10477:
10478: =item *
10479:
10480: str2hash($string) : convert string to hash using unescaping and
10481: splitting on '=' and '&', supports elements that are arrayrefs and
10482: hashrefs
10483:
10484: =item *
10485:
10486: str2array($string) : convert string to hash using unescaping and
10487: splitting on '&', supports elements that are arrayrefs and hashrefs
10488:
10489: =back
10490:
10491: =head2 Logging Routines
10492:
10493: =over 4
10494:
10495: These routines allow one to make log messages in the lonnet.log and
10496: lonnet.perm logfiles.
10497:
10498: =item *
10499:
10500: logtouch() : make sure the logfile, lonnet.log, exists
10501:
10502: =item *
10503:
10504: logthis() : append message to the normal lonnet.log file, it gets
10505: preiodically rolled over and deleted.
10506:
10507: =item *
10508:
10509: logperm() : append a permanent message to lonnet.perm.log, this log
10510: file never gets deleted by any automated portion of the system, only
10511: messages of critical importance should go in here.
10512:
10513: =back
10514:
10515: =head2 General File Helper Routines
10516:
10517: =over 4
10518:
10519: =item *
10520:
10521: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10522: (a) files in /uploaded
10523: (i) If a local copy of the file exists -
10524: compares modification date of local copy with last-modified date for
10525: definitive version stored on home server for course. If local copy is
10526: stale, requests a new version from the home server and stores it.
10527: If the original has been removed from the home server, then local copy
10528: is unlinked.
10529: (ii) If local copy does not exist -
10530: requests the file from the home server and stores it.
10531:
10532: If $caller is 'uploadrep':
10533: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10534: for request for files originally uploaded via DOCS.
10535: - returns 'ok' if fresh local copy now available, -1 otherwise.
10536:
10537: Otherwise:
10538: This indicates a call from the content generation phase of the request.
10539: - returns the entire contents of the file or -1.
10540:
10541: (b) files in /res
10542: - returns the entire contents of a file or -1;
10543: it properly subscribes to and replicates the file if neccessary.
10544:
10545:
10546: =item *
10547:
10548: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10549: reference
10550:
10551: returns either a stat() list of data about the file or an empty list
10552: if the file doesn't exist or couldn't find out about it (connection
10553: problems or user unknown)
10554:
10555: =item *
10556:
10557: filelocation($dir,$file) : returns file system location of a file
10558: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10559: directory that relative $file lookups are to looked in ($dir of /a/dir
10560: and a file of ../bob will become /a/bob)
10561:
10562: =item *
10563:
10564: hreflocation($dir,$file) : returns file system location or a URL; same as
10565: filelocation except for hrefs
10566:
10567: =item *
10568:
10569: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10570:
10571: =back
10572:
10573: =head2 Usererfile file routines (/uploaded*)
10574:
10575: =over 4
10576:
10577: =item *
10578:
10579: userfileupload(): main rotine for putting a file in a user or course's
10580: filespace, arguments are,
10581:
10582: formname - required - this is the name of the element in $env where the
10583: filename, and the contents of the file to create/modifed exist
10584: the filename is in $env{'form.'.$formname.'.filename'} and the
10585: contents of the file is located in $env{'form.'.$formname}
10586: coursedoc - if true, store the file in the course of the active role
10587: of the current user
10588: subdir - required - subdirectory to put the file in under ../userfiles/
10589: if undefined, it will be placed in "unknown"
10590:
10591: (This routine calls clean_filename() to remove any dangerous
10592: characters from the filename, and then calls finuserfileupload() to
10593: complete the transaction)
10594:
10595: returns either the url of the uploaded file (/uploaded/....) if successful
10596: and /adm/notfound.html if unsuccessful
10597:
10598: =item *
10599:
10600: clean_filename(): routine for cleaing a filename up for storage in
10601: userfile space, argument is:
10602:
10603: filename - proposed filename
10604:
10605: returns: the new clean filename
10606:
10607: =item *
10608:
10609: finishuserfileupload(): routine that creaes and sends the file to
10610: userspace, probably shouldn't be called directly
10611:
10612: docuname: username or courseid of destination for the file
10613: docudom: domain of user/course of destination for the file
10614: formname: same as for userfileupload()
10615: fname: filename (inculding subdirectories) for the file
10616:
10617: returns either the url of the uploaded file (/uploaded/....) if successful
10618: and /adm/notfound.html if unsuccessful
10619:
10620: =item *
10621:
10622: renameuserfile(): renames an existing userfile to a new name
10623:
10624: Args:
10625: docuname: username or courseid of destination for the file
10626: docudom: domain of user/course of destination for the file
10627: old: current file name (including any subdirs under userfiles)
10628: new: desired file name (including any subdirs under userfiles)
10629:
10630: =item *
10631:
10632: mkdiruserfile(): creates a directory is a userfiles dir
10633:
10634: Args:
10635: docuname: username or courseid of destination for the file
10636: docudom: domain of user/course of destination for the file
10637: dir: dir to create (including any subdirs under userfiles)
10638:
10639: =item *
10640:
10641: removeuserfile(): removes a file that exists in userfiles
10642:
10643: Args:
10644: docuname: username or courseid of destination for the file
10645: docudom: domain of user/course of destination for the file
10646: fname: filname to delete (including any subdirs under userfiles)
10647:
10648: =item *
10649:
10650: removeuploadedurl(): convience function for removeuserfile()
10651:
10652: Args:
10653: url: a full /uploaded/... url to delete
10654:
10655: =item *
10656:
10657: get_portfile_permissions():
10658: Args:
10659: domain: domain of user or course contain the portfolio files
10660: user: name of user or num of course contain the portfolio files
10661: Returns:
10662: hashref of a dump of the proper file_permissions.db
10663:
10664:
10665: =item *
10666:
10667: get_access_controls():
10668:
10669: Args:
10670: current_permissions: the hash ref returned from get_portfile_permissions()
10671: group: (optional) the group you want the files associated with
10672: file: (optional) the file you want access info on
10673:
10674: Returns:
10675: a hash (keys are file names) of hashes containing
10676: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10677: values are XML containing access control settings (see below)
10678:
10679: Internal notes:
10680:
10681: access controls are stored in file_permissions.db as key=value pairs.
10682: key -> path to file/file_name\0uniqueID:scope_end_start
10683: where scope -> public,guest,course,group,domains or users.
10684: end -> UNIX time for end of access (0 -> no end date)
10685: start -> UNIX time for start of access
10686:
10687: value -> XML description of access control
10688: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10689: <start></start>
10690: <end></end>
10691:
10692: <password></password> for scope type = guest
10693:
10694: <domain></domain> for scope type = course or group
10695: <number></number>
10696: <roles id="">
10697: <role></role>
10698: <access></access>
10699: <section></section>
10700: <group></group>
10701: </roles>
10702:
10703: <dom></dom> for scope type = domains
10704:
10705: <users> for scope type = users
10706: <user>
10707: <uname></uname>
10708: <udom></udom>
10709: </user>
10710: </users>
10711: </scope>
10712:
10713: Access data is also aggregated for each file in an additional key=value pair:
10714: key -> path to file/file_name\0accesscontrol
10715: value -> reference to hash
10716: hash contains key = value pairs
10717: where key = uniqueID:scope_end_start
10718: value = UNIX time record was last updated
10719:
10720: Used to improve speed of look-ups of access controls for each file.
10721:
10722: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10723:
10724: modify_access_controls():
10725:
10726: Modifies access controls for a portfolio file
10727: Args
10728: 1. file name
10729: 2. reference to hash of required changes,
10730: 3. domain
10731: 4. username
10732: where domain,username are the domain of the portfolio owner
10733: (either a user or a course)
10734:
10735: Returns:
10736: 1. result of additions or updates ('ok' or 'error', with error message).
10737: 2. result of deletions ('ok' or 'error', with error message).
10738: 3. reference to hash of any new or updated access controls.
10739: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10740: key = integer (inbound ID)
10741: value = uniqueID
10742:
10743: =back
10744:
10745: =head2 HTTP Helper Routines
10746:
10747: =over 4
10748:
10749: =item *
10750:
10751: escape() : unpack non-word characters into CGI-compatible hex codes
10752:
10753: =item *
10754:
10755: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10756:
10757: =back
10758:
10759: =head1 PRIVATE SUBROUTINES
10760:
10761: =head2 Underlying communication routines (Shouldn't call)
10762:
10763: =over 4
10764:
10765: =item *
10766:
10767: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10768:
10769: =item *
10770:
10771: reply() : uses subreply to send a message to remote machine, logs all failures
10772:
10773: =item *
10774:
10775: critical() : passes a critical message to another server; if cannot
10776: get through then place message in connection buffer directory and
10777: returns con_delayed, if incapable of saving message, returns
10778: con_failed
10779:
10780: =item *
10781:
10782: reconlonc() : tries to reconnect lonc client processes.
10783:
10784: =back
10785:
10786: =head2 Resource Access Logging
10787:
10788: =over 4
10789:
10790: =item *
10791:
10792: flushcourselogs() : flush (save) buffer logs and access logs
10793:
10794: =item *
10795:
10796: courselog($what) : save message for course in hash
10797:
10798: =item *
10799:
10800: courseacclog($what) : save message for course using &courselog(). Perform
10801: special processing for specific resource types (problems, exams, quizzes, etc).
10802:
10803: =item *
10804:
10805: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10806: as a PerlChildExitHandler
10807:
10808: =back
10809:
10810: =head2 Other
10811:
10812: =over 4
10813:
10814: =item *
10815:
10816: symblist($mapname,%newhash) : update symbolic storage links
10817:
10818: =back
10819:
10820: =cut
10821:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>