File:
[LON-CAPA] /
loncom /
lonnet /
perl /
lonnet.pm
Revision
1.1029:
download - view:
text,
annotated -
select for diffs
Mon Sep 28 19:13:37 2009 UTC (14 years, 9 months ago) by
raeburn
Branches:
MAIN
CVS tags:
HEAD
- Store creation date, creator, and creation context in nohist_courseids.db file.
- Include additional filters to filter courses by creation date and creation context when retrieving information from nohist_courseids.db.
1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1029 2009/09/28 19:13:37 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 File::MMagic;
96: use LONCAPA qw(:DEFAULT :match);
97: use LONCAPA::Configuration;
98:
99: my $readit;
100: my $max_connection_retries = 10; # Or some such value.
101:
102: my $upload_photo_form = 0; #Variable to check when user upload a photo 0=not 1=true
103:
104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
109:
110: # --------------------------------------------------------------------- Logging
111: {
112: my $logid;
113: sub instructor_log {
114: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
115: if (($cnum eq '') || ($cdom eq '')) {
116: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
117: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
118: }
119: $logid++;
120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
122: return &Apache::lonnet::put('nohist_'.$hash_name,
123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
126: 'exe_time' => $now,
127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
133: },$cdom,$cnum);
134: }
135: }
136:
137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
153: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
154: print $fh $logstring;
155: close($fh);
156: }
157: return 1;
158: }
159:
160: sub logperm {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
165: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
166: print $fh "$now:$message:$local\n";
167: close($fh);
168: }
169: return 1;
170: }
171:
172: sub create_connection {
173: my ($hostname,$lonid) = @_;
174: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
175: Type => SOCK_STREAM,
176: Timeout => 10);
177: return 0 if (!$client);
178: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
179: my $result = <$client>;
180: chomp($result);
181: return 1 if ($result eq 'done');
182: return 0;
183: }
184:
185: sub get_server_timezone {
186: my ($cnum,$cdom) = @_;
187: my $home=&homeserver($cnum,$cdom);
188: if ($home ne 'no_host') {
189: my $cachetime = 24*3600;
190: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
191: if (defined($cached)) {
192: return $timezone;
193: } else {
194: my $timezone = &reply('servertimezone',$home);
195: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
196: }
197: }
198: }
199:
200: sub get_server_loncaparev {
201: my ($dom,$lonhost) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: undef($lonhost);
205: }
206: }
207: if (!defined($lonhost)) {
208: if (defined(&domain($dom,'primary'))) {
209: $lonhost=&domain($dom,'primary');
210: if ($lonhost eq 'no_host') {
211: undef($lonhost);
212: }
213: }
214: }
215: if (defined($lonhost)) {
216: my $cachetime = 24*3600;
217: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
218: if (defined($cached)) {
219: return $loncaparev;
220: } else {
221: my $loncaparev = &reply('serverloncaparev',$lonhost);
222: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
223: }
224: }
225: }
226:
227: # -------------------------------------------------- Non-critical communication
228: sub subreply {
229: my ($cmd,$server)=@_;
230: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
231: #
232: # With loncnew process trimming, there's a timing hole between lonc server
233: # process exit and the master server picking up the listen on the AF_UNIX
234: # socket. In that time interval, a lock file will exist:
235:
236: my $lockfile=$peerfile.".lock";
237: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
238: sleep(1);
239: }
240: # At this point, either a loncnew parent is listening or an old lonc
241: # or loncnew child is listening so we can connect or everything's dead.
242: #
243: # We'll give the connection a few tries before abandoning it. If
244: # connection is not possible, we'll con_lost back to the client.
245: #
246: my $client;
247: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
248: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
249: Type => SOCK_STREAM,
250: Timeout => 10);
251: if ($client) {
252: last; # Connected!
253: } else {
254: &create_connection(&hostname($server),$server);
255: }
256: sleep(1); # Try again later if failed connection.
257: }
258: my $answer;
259: if ($client) {
260: print $client "sethost:$server:$cmd\n";
261: $answer=<$client>;
262: if (!$answer) { $answer="con_lost"; }
263: chomp($answer);
264: } else {
265: $answer = 'con_lost'; # Failed connection.
266: }
267: return $answer;
268: }
269:
270: sub reply {
271: my ($cmd,$server)=@_;
272: unless (defined(&hostname($server))) { return 'no_such_host'; }
273: my $answer=subreply($cmd,$server);
274: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
275: &logthis("<font color=\"blue\">WARNING:".
276: " $cmd to $server returned $answer</font>");
277: }
278: return $answer;
279: }
280:
281: # ----------------------------------------------------------- Send USR1 to lonc
282:
283: sub reconlonc {
284: my ($lonid) = @_;
285: my $hostname = &hostname($lonid);
286: if ($lonid) {
287: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
288: if ($hostname && -e $peerfile) {
289: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
290: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
291: Type => SOCK_STREAM,
292: Timeout => 10);
293: if ($client) {
294: print $client ("reset_retries\n");
295: my $answer=<$client>;
296: #reset just this one.
297: }
298: }
299: return;
300: }
301:
302: &logthis("Trying to reconnect lonc");
303: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
304: if (open(my $fh,"<$loncfile")) {
305: my $loncpid=<$fh>;
306: chomp($loncpid);
307: if (kill 0 => $loncpid) {
308: &logthis("lonc at pid $loncpid responding, sending USR1");
309: kill USR1 => $loncpid;
310: sleep 1;
311: } else {
312: &logthis(
313: "<font color=\"blue\">WARNING:".
314: " lonc at pid $loncpid not responding, giving up</font>");
315: }
316: } else {
317: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
318: }
319: }
320:
321: # ------------------------------------------------------ Critical communication
322:
323: sub critical {
324: my ($cmd,$server)=@_;
325: unless (&hostname($server)) {
326: &logthis("<font color=\"blue\">WARNING:".
327: " Critical message to unknown server ($server)</font>");
328: return 'no_such_host';
329: }
330: my $answer=reply($cmd,$server);
331: if ($answer eq 'con_lost') {
332: &reconlonc("$perlvar{'lonSockDir'}/$server");
333: my $answer=reply($cmd,$server);
334: if ($answer eq 'con_lost') {
335: my $now=time;
336: my $middlename=$cmd;
337: $middlename=substr($middlename,0,16);
338: $middlename=~s/\W//g;
339: my $dfilename=
340: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
341: $dumpcount++;
342: {
343: my $dfh;
344: if (open($dfh,">$dfilename")) {
345: print $dfh "$cmd\n";
346: close($dfh);
347: }
348: }
349: sleep 2;
350: my $wcmd='';
351: {
352: my $dfh;
353: if (open($dfh,"<$dfilename")) {
354: $wcmd=<$dfh>;
355: close($dfh);
356: }
357: }
358: chomp($wcmd);
359: if ($wcmd eq $cmd) {
360: &logthis("<font color=\"blue\">WARNING: ".
361: "Connection buffer $dfilename: $cmd</font>");
362: &logperm("D:$server:$cmd");
363: return 'con_delayed';
364: } else {
365: &logthis("<font color=\"red\">CRITICAL:"
366: ." Critical connection failed: $server $cmd</font>");
367: &logperm("F:$server:$cmd");
368: return 'con_failed';
369: }
370: }
371: }
372: return $answer;
373: }
374:
375: # ------------------------------------------- check if return value is an error
376:
377: sub error {
378: my ($result) = @_;
379: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
380: if ($2 == 2) { return undef; }
381: return $1;
382: }
383: return undef;
384: }
385:
386: sub convert_and_load_session_env {
387: my ($lonidsdir,$handle)=@_;
388: my @profile;
389: {
390: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
391: if (!$opened) {
392: return 0;
393: }
394: flock($idf,LOCK_SH);
395: @profile=<$idf>;
396: close($idf);
397: }
398: my %temp_env;
399: foreach my $line (@profile) {
400: if ($line !~ m/=/) {
401: return 0;
402: }
403: chomp($line);
404: my ($envname,$envvalue)=split(/=/,$line,2);
405: $temp_env{&unescape($envname)} = &unescape($envvalue);
406: }
407: unlink("$lonidsdir/$handle.id");
408: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
409: 0640)) {
410: %disk_env = %temp_env;
411: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
412: untie(%disk_env);
413: }
414: return 1;
415: }
416:
417: # ------------------------------------------- Transfer profile into environment
418: my $env_loaded;
419: sub transfer_profile_to_env {
420: my ($lonidsdir,$handle,$force_transfer) = @_;
421: if (!$force_transfer && $env_loaded) { return; }
422:
423: if (!defined($lonidsdir)) {
424: $lonidsdir = $perlvar{'lonIDsDir'};
425: }
426: if (!defined($handle)) {
427: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
428: }
429:
430: my $convert;
431: {
432: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
433: if (!$opened) {
434: return;
435: }
436: flock($idf,LOCK_SH);
437: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
438: &GDBM_READER(),0640)) {
439: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
440: untie(%disk_env);
441: } else {
442: $convert = 1;
443: }
444: }
445: if ($convert) {
446: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
447: &logthis("Failed to load session, or convert session.");
448: }
449: }
450:
451: my %remove;
452: while ( my $envname = each(%env) ) {
453: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
454: if ($time < time-300) {
455: $remove{$key}++;
456: }
457: }
458: }
459:
460: $env{'user.environment'} = "$lonidsdir/$handle.id";
461: $env_loaded=1;
462: foreach my $expired_key (keys(%remove)) {
463: &delenv($expired_key);
464: }
465: }
466:
467: # ---------------------------------------------------- Check for valid session
468: sub check_for_valid_session {
469: my ($r) = @_;
470: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
471: my $lonid=$cookies{'lonID'};
472: return undef if (!$lonid);
473:
474: my $handle=&LONCAPA::clean_handle($lonid->value);
475: my $lonidsdir=$r->dir_config('lonIDsDir');
476: return undef if (!-e "$lonidsdir/$handle.id");
477:
478: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
479: return undef if (!$opened);
480:
481: flock($idf,LOCK_SH);
482: my %disk_env;
483: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
484: &GDBM_READER(),0640)) {
485: return undef;
486: }
487:
488: if (!defined($disk_env{'user.name'})
489: || !defined($disk_env{'user.domain'})) {
490: return undef;
491: }
492: return $handle;
493: }
494:
495: sub timed_flock {
496: my ($file,$lock_type) = @_;
497: my $failed=0;
498: eval {
499: local $SIG{__DIE__}='DEFAULT';
500: local $SIG{ALRM}=sub {
501: $failed=1;
502: die("failed lock");
503: };
504: alarm(13);
505: flock($file,$lock_type);
506: alarm(0);
507: };
508: if ($failed) {
509: return undef;
510: } else {
511: return 1;
512: }
513: }
514:
515: # ---------------------------------------------------------- Append Environment
516:
517: sub appenv {
518: my ($newenv,$roles) = @_;
519: if (ref($newenv) eq 'HASH') {
520: foreach my $key (keys(%{$newenv})) {
521: my $refused = 0;
522: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
523: $refused = 1;
524: if (ref($roles) eq 'ARRAY') {
525: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
526: if (grep(/^\Q$role\E$/,@{$roles})) {
527: $refused = 0;
528: }
529: }
530: }
531: if ($refused) {
532: &logthis("<font color=\"blue\">WARNING: ".
533: "Attempt to modify environment ".$key." to ".$newenv->{$key}
534: .'</font>');
535: delete($newenv->{$key});
536: } else {
537: $env{$key}=$newenv->{$key};
538: }
539: }
540: my $opened = open(my $env_file,'+<',$env{'user.environment'});
541: if ($opened
542: && &timed_flock($env_file,LOCK_EX)
543: &&
544: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
545: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
546: while (my ($key,$value) = each(%{$newenv})) {
547: $disk_env{$key} = $value;
548: }
549: untie(%disk_env);
550: }
551: }
552: return 'ok';
553: }
554: # ----------------------------------------------------- Delete from Environment
555:
556: sub delenv {
557: my ($delthis,$regexp) = @_;
558: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
559: &logthis("<font color=\"blue\">WARNING: ".
560: "Attempt to delete from environment ".$delthis);
561: return 'error';
562: }
563: my $opened = open(my $env_file,'+<',$env{'user.environment'});
564: if ($opened
565: && &timed_flock($env_file,LOCK_EX)
566: &&
567: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
568: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
569: foreach my $key (keys(%disk_env)) {
570: if ($regexp) {
571: if ($key=~/^$delthis/) {
572: delete($env{$key});
573: delete($disk_env{$key});
574: }
575: } else {
576: if ($key=~/^\Q$delthis\E/) {
577: delete($env{$key});
578: delete($disk_env{$key});
579: }
580: }
581: }
582: untie(%disk_env);
583: }
584: return 'ok';
585: }
586:
587: sub get_env_multiple {
588: my ($name) = @_;
589: my @values;
590: if (defined($env{$name})) {
591: # exists is it an array
592: if (ref($env{$name})) {
593: @values=@{ $env{$name} };
594: } else {
595: $values[0]=$env{$name};
596: }
597: }
598: return(@values);
599: }
600:
601: # ------------------------------------------------------------------- Locking
602:
603: sub set_lock {
604: my ($text)=@_;
605: $locknum++;
606: my $id=$$.'-'.$locknum;
607: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
608: 'session.lock.'.$id => $text});
609: return $id;
610: }
611:
612: sub get_locks {
613: my $num=0;
614: my %texts=();
615: foreach my $lock (split(/\,/,$env{'session.locks'})) {
616: if ($lock=~/\w/) {
617: $num++;
618: $texts{$lock}=$env{'session.lock.'.$lock};
619: }
620: }
621: return ($num,%texts);
622: }
623:
624: sub remove_lock {
625: my ($id)=@_;
626: my $newlocks='';
627: foreach my $lock (split(/\,/,$env{'session.locks'})) {
628: if (($lock=~/\w/) && ($lock ne $id)) {
629: $newlocks.=','.$lock;
630: }
631: }
632: &appenv({'session.locks' => $newlocks});
633: &delenv('session.lock.'.$id);
634: }
635:
636: sub remove_all_locks {
637: my $activelocks=$env{'session.locks'};
638: foreach my $lock (split(/\,/,$env{'session.locks'})) {
639: if ($lock=~/\w/) {
640: &remove_lock($lock);
641: }
642: }
643: }
644:
645:
646: # ------------------------------------------ Find out current server userload
647: sub userload {
648: my $numusers=0;
649: {
650: opendir(LONIDS,$perlvar{'lonIDsDir'});
651: my $filename;
652: my $curtime=time;
653: while ($filename=readdir(LONIDS)) {
654: next if ($filename eq '.' || $filename eq '..');
655: next if ($filename =~ /publicuser_\d+\.id/);
656: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
657: if ($curtime-$mtime < 1800) { $numusers++; }
658: }
659: closedir(LONIDS);
660: }
661: my $userloadpercent=0;
662: my $maxuserload=$perlvar{'lonUserLoadLim'};
663: if ($maxuserload) {
664: $userloadpercent=100*$numusers/$maxuserload;
665: }
666: $userloadpercent=sprintf("%.2f",$userloadpercent);
667: return $userloadpercent;
668: }
669:
670: # ------------------------------------------ Fight off request when overloaded
671:
672: sub overloaderror {
673: my ($r,$checkserver)=@_;
674: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
675: my $loadavg;
676: if ($checkserver eq $perlvar{'lonHostID'}) {
677: open(my $loadfile,'/proc/loadavg');
678: $loadavg=<$loadfile>;
679: $loadavg =~ s/\s.*//g;
680: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
681: close($loadfile);
682: } else {
683: $loadavg=&reply('load',$checkserver);
684: }
685: my $overload=$loadavg-100;
686: if ($overload>0) {
687: $r->err_headers_out->{'Retry-After'}=$overload;
688: $r->log_error('Overload of '.$overload.' on '.$checkserver);
689: return 413;
690: }
691: return '';
692: }
693:
694: # ------------------------------ Find server with least workload from spare.tab
695:
696: sub spareserver {
697: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
698: my $spare_server;
699: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
700: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
701: : $userloadpercent;
702:
703: foreach my $try_server (@{ $spareid{'primary'} }) {
704: ($spare_server, $lowest_load) =
705: &compare_server_load($try_server, $spare_server, $lowest_load);
706: }
707:
708: my $found_server = ($spare_server ne '' && $lowest_load < 100);
709:
710: if (!$found_server) {
711: foreach my $try_server (@{ $spareid{'default'} }) {
712: ($spare_server, $lowest_load) =
713: &compare_server_load($try_server, $spare_server, $lowest_load);
714: }
715: }
716:
717: if (!$want_server_name) {
718: my $protocol = 'http';
719: if ($protocol{$spare_server} eq 'https') {
720: $protocol = $protocol{$spare_server};
721: }
722: if (defined($spare_server)) {
723: my $hostname = &hostname($spare_server);
724: if (defined($hostname)) {
725: $spare_server = $protocol.'://'.$hostname;
726: }
727: }
728: }
729: return $spare_server;
730: }
731:
732: sub compare_server_load {
733: my ($try_server, $spare_server, $lowest_load) = @_;
734:
735: my $loadans = &reply('load', $try_server);
736: my $userloadans = &reply('userload',$try_server);
737:
738: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
739: next; #didn't get a number from the server
740: }
741:
742: my $load;
743: if ($loadans =~ /\d/) {
744: if ($userloadans =~ /\d/) {
745: #both are numbers, pick the bigger one
746: $load = ($loadans > $userloadans) ? $loadans
747: : $userloadans;
748: } else {
749: $load = $loadans;
750: }
751: } else {
752: $load = $userloadans;
753: }
754:
755: if (($load =~ /\d/) && ($load < $lowest_load)) {
756: $spare_server = $try_server;
757: $lowest_load = $load;
758: }
759: return ($spare_server,$lowest_load);
760: }
761:
762: # --------------------------- ask offload servers if user already has a session
763: sub find_existing_session {
764: my ($udom,$uname) = @_;
765: foreach my $try_server (@{ $spareid{'primary'} },
766: @{ $spareid{'default'} }) {
767: return $try_server if (&has_user_session($try_server, $udom, $uname));
768: }
769: return;
770: }
771:
772: # -------------------------------- ask if server already has a session for user
773: sub has_user_session {
774: my ($lonid,$udom,$uname) = @_;
775: my $result = &reply(join(':','userhassession',
776: map {&escape($_)} ($udom,$uname)),$lonid);
777: return 1 if ($result eq 'ok');
778:
779: return 0;
780: }
781:
782: # --------------------------------------------- Try to change a user's password
783:
784: sub changepass {
785: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
786: $currentpass = &escape($currentpass);
787: $newpass = &escape($newpass);
788: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
789: $server);
790: if (! $answer) {
791: &logthis("No reply on password change request to $server ".
792: "by $uname in domain $udom.");
793: } elsif ($answer =~ "^ok") {
794: &logthis("$uname in $udom successfully changed their password ".
795: "on $server.");
796: } elsif ($answer =~ "^pwchange_failure") {
797: &logthis("$uname in $udom was unable to change their password ".
798: "on $server. The action was blocked by either lcpasswd ".
799: "or pwchange");
800: } elsif ($answer =~ "^non_authorized") {
801: &logthis("$uname in $udom did not get their password correct when ".
802: "attempting to change it on $server.");
803: } elsif ($answer =~ "^auth_mode_error") {
804: &logthis("$uname in $udom attempted to change their password despite ".
805: "not being locally or internally authenticated on $server.");
806: } elsif ($answer =~ "^unknown_user") {
807: &logthis("$uname in $udom attempted to change their password ".
808: "on $server but were unable to because $server is not ".
809: "their home server.");
810: } elsif ($answer =~ "^refused") {
811: &logthis("$server refused to change $uname in $udom password because ".
812: "it was sent an unencrypted request to change the password.");
813: }
814: return $answer;
815: }
816:
817: # ----------------------- Try to determine user's current authentication scheme
818:
819: sub queryauthenticate {
820: my ($uname,$udom)=@_;
821: my $uhome=&homeserver($uname,$udom);
822: if (!$uhome) {
823: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
824: return 'no_host';
825: }
826: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
827: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
828: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
829: }
830: return $answer;
831: }
832:
833: # --------- Try to authenticate user from domain's lib servers (first this one)
834:
835: sub authenticate {
836: my ($uname,$upass,$udom,$checkdefauth)=@_;
837: $upass=&escape($upass);
838: $uname= &LONCAPA::clean_username($uname);
839: my $uhome=&homeserver($uname,$udom,1);
840: my $newhome;
841: if ((!$uhome) || ($uhome eq 'no_host')) {
842: # Maybe the machine was offline and only re-appeared again recently?
843: &reconlonc();
844: # One more
845: $uhome=&homeserver($uname,$udom,1);
846: if (($uhome eq 'no_host') && $checkdefauth) {
847: if (defined(&domain($udom,'primary'))) {
848: $newhome=&domain($udom,'primary');
849: }
850: if ($newhome ne '') {
851: $uhome = $newhome;
852: }
853: }
854: if ((!$uhome) || ($uhome eq 'no_host')) {
855: &logthis("User $uname at $udom is unknown in authenticate");
856: return 'no_host';
857: }
858: }
859: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
860: if ($answer eq 'authorized') {
861: if ($newhome) {
862: &logthis("User $uname at $udom authorized by $uhome, but needs account");
863: return 'no_account_on_host';
864: } else {
865: &logthis("User $uname at $udom authorized by $uhome");
866: return $uhome;
867: }
868: }
869: if ($answer eq 'non_authorized') {
870: &logthis("User $uname at $udom rejected by $uhome");
871: return 'no_host';
872: }
873: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
874: return 'no_host';
875: }
876:
877: # ---------------------- Find the homebase for a user from domain's lib servers
878:
879: my %homecache;
880: sub homeserver {
881: my ($uname,$udom,$ignoreBadCache)=@_;
882: my $index="$uname:$udom";
883:
884: if (exists($homecache{$index})) { return $homecache{$index}; }
885:
886: my %servers = &get_servers($udom,'library');
887: foreach my $tryserver (keys(%servers)) {
888: next if ($ignoreBadCache ne 'true' &&
889: exists($badServerCache{$tryserver}));
890:
891: my $answer=reply("home:$udom:$uname",$tryserver);
892: if ($answer eq 'found') {
893: delete($badServerCache{$tryserver});
894: return $homecache{$index}=$tryserver;
895: } elsif ($answer eq 'no_host') {
896: $badServerCache{$tryserver}=1;
897: }
898: }
899: return 'no_host';
900: }
901:
902: # ------------------------------------- Find the usernames behind a list of IDs
903:
904: sub idget {
905: my ($udom,@ids)=@_;
906: my %returnhash=();
907:
908: my %servers = &get_servers($udom,'library');
909: foreach my $tryserver (keys(%servers)) {
910: my $idlist=join('&',@ids);
911: $idlist=~tr/A-Z/a-z/;
912: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
913: my @answer=();
914: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
915: @answer=split(/\&/,$reply);
916: } ;
917: my $i;
918: for ($i=0;$i<=$#ids;$i++) {
919: if ($answer[$i]) {
920: $returnhash{$ids[$i]}=$answer[$i];
921: }
922: }
923: }
924: return %returnhash;
925: }
926:
927: # ------------------------------------- Find the IDs behind a list of usernames
928:
929: sub idrget {
930: my ($udom,@unames)=@_;
931: my %returnhash=();
932: foreach my $uname (@unames) {
933: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
934: }
935: return %returnhash;
936: }
937:
938: # ------------------------------- Store away a list of names and associated IDs
939:
940: sub idput {
941: my ($udom,%ids)=@_;
942: my %servers=();
943: foreach my $uname (keys(%ids)) {
944: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
945: my $uhom=&homeserver($uname,$udom);
946: if ($uhom ne 'no_host') {
947: my $id=&escape($ids{$uname});
948: $id=~tr/A-Z/a-z/;
949: my $esc_unam=&escape($uname);
950: if ($servers{$uhom}) {
951: $servers{$uhom}.='&'.$id.'='.$esc_unam;
952: } else {
953: $servers{$uhom}=$id.'='.$esc_unam;
954: }
955: }
956: }
957: foreach my $server (keys(%servers)) {
958: &critical('idput:'.$udom.':'.$servers{$server},$server);
959: }
960: }
961:
962: # ------------------------------dump from db file owned by domainconfig user
963: sub dump_dom {
964: my ($namespace,$udom,$regexp,$range)=@_;
965: if (!$udom) {
966: $udom=$env{'user.domain'};
967: }
968: my %returnhash;
969: if ($udom) {
970: my $uname = &get_domainconfiguser($udom);
971: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
972: }
973: return %returnhash;
974: }
975:
976: # ------------------------------------------ get items from domain db files
977:
978: sub get_dom {
979: my ($namespace,$storearr,$udom,$uhome)=@_;
980: my $items='';
981: foreach my $item (@$storearr) {
982: $items.=&escape($item).'&';
983: }
984: $items=~s/\&$//;
985: if (!$udom) {
986: $udom=$env{'user.domain'};
987: if (defined(&domain($udom,'primary'))) {
988: $uhome=&domain($udom,'primary');
989: } else {
990: undef($uhome);
991: }
992: } else {
993: if (!$uhome) {
994: if (defined(&domain($udom,'primary'))) {
995: $uhome=&domain($udom,'primary');
996: }
997: }
998: }
999: if ($udom && $uhome && ($uhome ne 'no_host')) {
1000: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1001: my %returnhash;
1002: if ($rep eq '' || $rep =~ /^error: 2 /) {
1003: return %returnhash;
1004: }
1005: my @pairs=split(/\&/,$rep);
1006: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1007: return @pairs;
1008: }
1009: my $i=0;
1010: foreach my $item (@$storearr) {
1011: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1012: $i++;
1013: }
1014: return %returnhash;
1015: } else {
1016: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1017: }
1018: }
1019:
1020: # -------------------------------------------- put items in domain db files
1021:
1022: sub put_dom {
1023: my ($namespace,$storehash,$udom,$uhome)=@_;
1024: if (!$udom) {
1025: $udom=$env{'user.domain'};
1026: if (defined(&domain($udom,'primary'))) {
1027: $uhome=&domain($udom,'primary');
1028: } else {
1029: undef($uhome);
1030: }
1031: } else {
1032: if (!$uhome) {
1033: if (defined(&domain($udom,'primary'))) {
1034: $uhome=&domain($udom,'primary');
1035: }
1036: }
1037: }
1038: if ($udom && $uhome && ($uhome ne 'no_host')) {
1039: my $items='';
1040: foreach my $item (keys(%$storehash)) {
1041: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1042: }
1043: $items=~s/\&$//;
1044: return &reply("putdom:$udom:$namespace:$items",$uhome);
1045: } else {
1046: &logthis("put_dom failed - no homeserver and/or domain");
1047: }
1048: }
1049:
1050: # --------------------- newput for items in db file owned by domainconfig user
1051: sub newput_dom {
1052: my ($namespace,$storehash,$udom) = @_;
1053: my $result;
1054: if (!$udom) {
1055: $udom=$env{'user.domain'};
1056: }
1057: if ($udom) {
1058: my $uname = &get_domainconfiguser($udom);
1059: $result = &newput($namespace,$storehash,$udom,$uname);
1060: }
1061: return $result;
1062: }
1063:
1064: # --------------------- delete for items in db file owned by domainconfig user
1065: sub del_dom {
1066: my ($namespace,$storearr,$udom)=@_;
1067: if (ref($storearr) eq 'ARRAY') {
1068: if (!$udom) {
1069: $udom=$env{'user.domain'};
1070: }
1071: if ($udom) {
1072: my $uname = &get_domainconfiguser($udom);
1073: return &del($namespace,$storearr,$udom,$uname);
1074: }
1075: }
1076: }
1077:
1078: # ----------------------------------construct domainconfig user for a domain
1079: sub get_domainconfiguser {
1080: my ($udom) = @_;
1081: return $udom.'-domainconfig';
1082: }
1083:
1084: sub retrieve_inst_usertypes {
1085: my ($udom) = @_;
1086: my (%returnhash,@order);
1087: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1088: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1089: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1090: %returnhash = %{$domdefs{'inststatustypes'}};
1091: @order = @{$domdefs{'inststatusorder'}};
1092: } else {
1093: if (defined(&domain($udom,'primary'))) {
1094: my $uhome=&domain($udom,'primary');
1095: my $rep=&reply("inst_usertypes:$udom",$uhome);
1096: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1097: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1098: return (\%returnhash,\@order);
1099: }
1100: my ($hashitems,$orderitems) = split(/:/,$rep);
1101: my @pairs=split(/\&/,$hashitems);
1102: foreach my $item (@pairs) {
1103: my ($key,$value)=split(/=/,$item,2);
1104: $key = &unescape($key);
1105: next if ($key =~ /^error: 2 /);
1106: $returnhash{$key}=&thaw_unescape($value);
1107: }
1108: my @esc_order = split(/\&/,$orderitems);
1109: foreach my $item (@esc_order) {
1110: push(@order,&unescape($item));
1111: }
1112: } else {
1113: &logthis("get_dom failed - no primary domain server for $udom");
1114: }
1115: }
1116: return (\%returnhash,\@order);
1117: }
1118:
1119: sub is_domainimage {
1120: my ($url) = @_;
1121: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1122: if (&domain($1) ne '') {
1123: return '1';
1124: }
1125: }
1126: return;
1127: }
1128:
1129: sub inst_directory_query {
1130: my ($srch) = @_;
1131: my $udom = $srch->{'srchdomain'};
1132: my %results;
1133: my $homeserver = &domain($udom,'primary');
1134: my $outcome;
1135: if ($homeserver ne '') {
1136: my $queryid=&reply("querysend:instdirsearch:".
1137: &escape($srch->{'srchby'}).':'.
1138: &escape($srch->{'srchterm'}).':'.
1139: &escape($srch->{'srchtype'}),$homeserver);
1140: my $host=&hostname($homeserver);
1141: if ($queryid !~/^\Q$host\E\_/) {
1142: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1143: return;
1144: }
1145: my $response = &get_query_reply($queryid);
1146: my $maxtries = 5;
1147: my $tries = 1;
1148: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1149: $response = &get_query_reply($queryid);
1150: $tries ++;
1151: }
1152:
1153: if (!&error($response) && $response ne 'refused') {
1154: if ($response eq 'unavailable') {
1155: $outcome = $response;
1156: } else {
1157: $outcome = 'ok';
1158: my @matches = split(/\n/,$response);
1159: foreach my $match (@matches) {
1160: my ($key,$value) = split(/=/,$match);
1161: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1162: }
1163: }
1164: }
1165: }
1166: return ($outcome,%results);
1167: }
1168:
1169: sub usersearch {
1170: my ($srch) = @_;
1171: my $dom = $srch->{'srchdomain'};
1172: my %results;
1173: my %libserv = &all_library();
1174: my $query = 'usersearch';
1175: foreach my $tryserver (keys(%libserv)) {
1176: if (&host_domain($tryserver) eq $dom) {
1177: my $host=&hostname($tryserver);
1178: my $queryid=
1179: &reply("querysend:".&escape($query).':'.
1180: &escape($srch->{'srchby'}).':'.
1181: &escape($srch->{'srchtype'}).':'.
1182: &escape($srch->{'srchterm'}),$tryserver);
1183: if ($queryid !~/^\Q$host\E\_/) {
1184: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1185: next;
1186: }
1187: my $reply = &get_query_reply($queryid);
1188: my $maxtries = 1;
1189: my $tries = 1;
1190: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1191: $reply = &get_query_reply($queryid);
1192: $tries ++;
1193: }
1194: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1195: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1196: } else {
1197: my @matches;
1198: if ($reply =~ /\n/) {
1199: @matches = split(/\n/,$reply);
1200: } else {
1201: @matches = split(/\&/,$reply);
1202: }
1203: foreach my $match (@matches) {
1204: my ($uname,$udom,%userhash);
1205: foreach my $entry (split(/:/,$match)) {
1206: my ($key,$value) =
1207: map {&unescape($_);} split(/=/,$entry);
1208: $userhash{$key} = $value;
1209: if ($key eq 'username') {
1210: $uname = $value;
1211: } elsif ($key eq 'domain') {
1212: $udom = $value;
1213: }
1214: }
1215: $results{$uname.':'.$udom} = \%userhash;
1216: }
1217: }
1218: }
1219: }
1220: return %results;
1221: }
1222:
1223: sub get_instuser {
1224: my ($udom,$uname,$id) = @_;
1225: my $homeserver = &domain($udom,'primary');
1226: my ($outcome,%results);
1227: if ($homeserver ne '') {
1228: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1229: &escape($id).':'.&escape($udom),$homeserver);
1230: my $host=&hostname($homeserver);
1231: if ($queryid !~/^\Q$host\E\_/) {
1232: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1233: return;
1234: }
1235: my $response = &get_query_reply($queryid);
1236: my $maxtries = 5;
1237: my $tries = 1;
1238: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1239: $response = &get_query_reply($queryid);
1240: $tries ++;
1241: }
1242: if (!&error($response) && $response ne 'refused') {
1243: if ($response eq 'unavailable') {
1244: $outcome = $response;
1245: } else {
1246: $outcome = 'ok';
1247: my @matches = split(/\n/,$response);
1248: foreach my $match (@matches) {
1249: my ($key,$value) = split(/=/,$match);
1250: $results{&unescape($key)} = &thaw_unescape($value);
1251: }
1252: }
1253: }
1254: }
1255: my %userinfo;
1256: if (ref($results{$uname}) eq 'HASH') {
1257: %userinfo = %{$results{$uname}};
1258: }
1259: return ($outcome,%userinfo);
1260: }
1261:
1262: sub inst_rulecheck {
1263: my ($udom,$uname,$id,$item,$rules) = @_;
1264: my %returnhash;
1265: if ($udom ne '') {
1266: if (ref($rules) eq 'ARRAY') {
1267: @{$rules} = map {&escape($_);} (@{$rules});
1268: my $rulestr = join(':',@{$rules});
1269: my $homeserver=&domain($udom,'primary');
1270: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1271: my $response;
1272: if ($item eq 'username') {
1273: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1274: ':'.&escape($uname).':'.$rulestr,
1275: $homeserver));
1276: } elsif ($item eq 'id') {
1277: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1278: ':'.&escape($id).':'.$rulestr,
1279: $homeserver));
1280: } elsif ($item eq 'selfcreate') {
1281: $response=&unescape(&reply('instselfcreatecheck:'.
1282: &escape($udom).':'.&escape($uname).
1283: ':'.$rulestr,$homeserver));
1284: }
1285: if ($response ne 'refused') {
1286: my @pairs=split(/\&/,$response);
1287: foreach my $item (@pairs) {
1288: my ($key,$value)=split(/=/,$item,2);
1289: $key = &unescape($key);
1290: next if ($key =~ /^error: 2 /);
1291: $returnhash{$key}=&thaw_unescape($value);
1292: }
1293: }
1294: }
1295: }
1296: }
1297: return %returnhash;
1298: }
1299:
1300: sub inst_userrules {
1301: my ($udom,$check) = @_;
1302: my (%ruleshash,@ruleorder);
1303: if ($udom ne '') {
1304: my $homeserver=&domain($udom,'primary');
1305: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1306: my $response;
1307: if ($check eq 'id') {
1308: $response=&reply('instidrules:'.&escape($udom),
1309: $homeserver);
1310: } elsif ($check eq 'email') {
1311: $response=&reply('instemailrules:'.&escape($udom),
1312: $homeserver);
1313: } else {
1314: $response=&reply('instuserrules:'.&escape($udom),
1315: $homeserver);
1316: }
1317: if (($response ne 'refused') && ($response ne 'error') &&
1318: ($response ne 'unknown_cmd') &&
1319: ($response ne 'no_such_host')) {
1320: my ($hashitems,$orderitems) = split(/:/,$response);
1321: my @pairs=split(/\&/,$hashitems);
1322: foreach my $item (@pairs) {
1323: my ($key,$value)=split(/=/,$item,2);
1324: $key = &unescape($key);
1325: next if ($key =~ /^error: 2 /);
1326: $ruleshash{$key}=&thaw_unescape($value);
1327: }
1328: my @esc_order = split(/\&/,$orderitems);
1329: foreach my $item (@esc_order) {
1330: push(@ruleorder,&unescape($item));
1331: }
1332: }
1333: }
1334: }
1335: return (\%ruleshash,\@ruleorder);
1336: }
1337:
1338: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1339:
1340: sub get_domain_defaults {
1341: my ($domain) = @_;
1342: my $cachetime = 60*60*24;
1343: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1344: if (defined($cached)) {
1345: if (ref($result) eq 'HASH') {
1346: return %{$result};
1347: }
1348: }
1349: my %domdefaults;
1350: my %domconfig =
1351: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1352: 'requestcourses','inststatus'],$domain);
1353: if (ref($domconfig{'defaults'}) eq 'HASH') {
1354: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1355: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1356: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1357: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1358: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1359: } else {
1360: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1361: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1362: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1363: }
1364: if (ref($domconfig{'quotas'}) eq 'HASH') {
1365: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1366: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1367: } else {
1368: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1369: }
1370: my @usertools = ('aboutme','blog','portfolio');
1371: foreach my $item (@usertools) {
1372: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1373: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1374: }
1375: }
1376: }
1377: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1378: foreach my $item ('official','unofficial','community') {
1379: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1380: }
1381: }
1382: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1383: foreach my $item ('inststatustypes','inststatusorder') {
1384: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1385: }
1386: }
1387: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1388: $cachetime);
1389: return %domdefaults;
1390: }
1391:
1392: # --------------------------------------------------- Assign a key to a student
1393:
1394: sub assign_access_key {
1395: #
1396: # a valid key looks like uname:udom#comments
1397: # comments are being appended
1398: #
1399: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1400: $kdom=
1401: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1402: $knum=
1403: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1404: $cdom=
1405: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1406: $cnum=
1407: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1408: $udom=$env{'user.name'} unless (defined($udom));
1409: $uname=$env{'user.domain'} unless (defined($uname));
1410: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1411: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1412: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1413: # assigned to this person
1414: # - this should not happen,
1415: # unless something went wrong
1416: # the first time around
1417: # ready to assign
1418: $logentry=$1.'; '.$logentry;
1419: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1420: $kdom,$knum) eq 'ok') {
1421: # key now belongs to user
1422: my $envkey='key.'.$cdom.'_'.$cnum;
1423: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1424: &appenv({'environment.'.$envkey => $ckey});
1425: return 'ok';
1426: } else {
1427: return
1428: 'error: Count not permanently assign key, will need to be re-entered later.';
1429: }
1430: } else {
1431: return 'error: Could not assign key, try again later.';
1432: }
1433: } elsif (!$existing{$ckey}) {
1434: # the key does not exist
1435: return 'error: The key does not exist';
1436: } else {
1437: # the key is somebody else's
1438: return 'error: The key is already in use';
1439: }
1440: }
1441:
1442: # ------------------------------------------ put an additional comment on a key
1443:
1444: sub comment_access_key {
1445: #
1446: # a valid key looks like uname:udom#comments
1447: # comments are being appended
1448: #
1449: my ($ckey,$cdom,$cnum,$logentry)=@_;
1450: $cdom=
1451: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1452: $cnum=
1453: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1454: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1455: if ($existing{$ckey}) {
1456: $existing{$ckey}.='; '.$logentry;
1457: # ready to assign
1458: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1459: $cdom,$cnum) eq 'ok') {
1460: return 'ok';
1461: } else {
1462: return 'error: Count not store comment.';
1463: }
1464: } else {
1465: # the key does not exist
1466: return 'error: The key does not exist';
1467: }
1468: }
1469:
1470: # ------------------------------------------------------ Generate a set of keys
1471:
1472: sub generate_access_keys {
1473: my ($number,$cdom,$cnum,$logentry)=@_;
1474: $cdom=
1475: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1476: $cnum=
1477: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1478: unless (&allowed('mky',$cdom)) { return 0; }
1479: unless (($cdom) && ($cnum)) { return 0; }
1480: if ($number>10000) { return 0; }
1481: sleep(2); # make sure don't get same seed twice
1482: srand(time()^($$+($$<<15))); # from "Programming Perl"
1483: my $total=0;
1484: for (my $i=1;$i<=$number;$i++) {
1485: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1486: sprintf("%lx",int(100000*rand)).'-'.
1487: sprintf("%lx",int(100000*rand));
1488: $newkey=~s/1/g/g; # folks mix up 1 and l
1489: $newkey=~s/0/h/g; # and also 0 and O
1490: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1491: if ($existing{$newkey}) {
1492: $i--;
1493: } else {
1494: if (&put('accesskeys',
1495: { $newkey => '# generated '.localtime().
1496: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1497: '; '.$logentry },
1498: $cdom,$cnum) eq 'ok') {
1499: $total++;
1500: }
1501: }
1502: }
1503: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1504: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1505: return $total;
1506: }
1507:
1508: # ------------------------------------------------------- Validate an accesskey
1509:
1510: sub validate_access_key {
1511: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1512: $cdom=
1513: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1514: $cnum=
1515: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1516: $udom=$env{'user.domain'} unless (defined($udom));
1517: $uname=$env{'user.name'} unless (defined($uname));
1518: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1519: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1520: }
1521:
1522: # ------------------------------------- Find the section of student in a course
1523: sub devalidate_getsection_cache {
1524: my ($udom,$unam,$courseid)=@_;
1525: my $hashid="$udom:$unam:$courseid";
1526: &devalidate_cache_new('getsection',$hashid);
1527: }
1528:
1529: sub courseid_to_courseurl {
1530: my ($courseid) = @_;
1531: #already url style courseid
1532: return $courseid if ($courseid =~ m{^/});
1533:
1534: if (exists($env{'course.'.$courseid.'.num'})) {
1535: my $cnum = $env{'course.'.$courseid.'.num'};
1536: my $cdom = $env{'course.'.$courseid.'.domain'};
1537: return "/$cdom/$cnum";
1538: }
1539:
1540: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1541: if (exists($courseinfo{'num'})) {
1542: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1543: }
1544:
1545: return undef;
1546: }
1547:
1548: sub getsection {
1549: my ($udom,$unam,$courseid)=@_;
1550: my $cachetime=1800;
1551:
1552: my $hashid="$udom:$unam:$courseid";
1553: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1554: if (defined($cached)) { return $result; }
1555:
1556: my %Pending;
1557: my %Expired;
1558: #
1559: # Each role can either have not started yet (pending), be active,
1560: # or have expired.
1561: #
1562: # If there is an active role, we are done.
1563: #
1564: # If there is more than one role which has not started yet,
1565: # choose the one which will start sooner
1566: # If there is one role which has not started yet, return it.
1567: #
1568: # If there is more than one expired role, choose the one which ended last.
1569: # If there is a role which has expired, return it.
1570: #
1571: $courseid = &courseid_to_courseurl($courseid);
1572: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1573: foreach my $key (keys(%roleshash)) {
1574: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1575: my $section=$1;
1576: if ($key eq $courseid.'_st') { $section=''; }
1577: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1578: my $now=time;
1579: if (defined($end) && $end && ($now > $end)) {
1580: $Expired{$end}=$section;
1581: next;
1582: }
1583: if (defined($start) && $start && ($now < $start)) {
1584: $Pending{$start}=$section;
1585: next;
1586: }
1587: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1588: }
1589: #
1590: # Presumedly there will be few matching roles from the above
1591: # loop and the sorting time will be negligible.
1592: if (scalar(keys(%Pending))) {
1593: my ($time) = sort {$a <=> $b} keys(%Pending);
1594: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1595: }
1596: if (scalar(keys(%Expired))) {
1597: my @sorted = sort {$a <=> $b} keys(%Expired);
1598: my $time = pop(@sorted);
1599: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1600: }
1601: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1602: }
1603:
1604: sub save_cache {
1605: &purge_remembered();
1606: #&Apache::loncommon::validate_page();
1607: undef(%env);
1608: undef($env_loaded);
1609: }
1610:
1611: my $to_remember=-1;
1612: my %remembered;
1613: my %accessed;
1614: my $kicks=0;
1615: my $hits=0;
1616: sub make_key {
1617: my ($name,$id) = @_;
1618: if (length($id) > 65
1619: && length(&escape($id)) > 200) {
1620: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1621: }
1622: return &escape($name.':'.$id);
1623: }
1624:
1625: sub devalidate_cache_new {
1626: my ($name,$id,$debug) = @_;
1627: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1628: $id=&make_key($name,$id);
1629: $memcache->delete($id);
1630: delete($remembered{$id});
1631: delete($accessed{$id});
1632: }
1633:
1634: sub is_cached_new {
1635: my ($name,$id,$debug) = @_;
1636: $id=&make_key($name,$id);
1637: if (exists($remembered{$id})) {
1638: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1639: $accessed{$id}=[&gettimeofday()];
1640: $hits++;
1641: return ($remembered{$id},1);
1642: }
1643: my $value = $memcache->get($id);
1644: if (!(defined($value))) {
1645: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1646: return (undef,undef);
1647: }
1648: if ($value eq '__undef__') {
1649: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1650: $value=undef;
1651: }
1652: &make_room($id,$value,$debug);
1653: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1654: return ($value,1);
1655: }
1656:
1657: sub do_cache_new {
1658: my ($name,$id,$value,$time,$debug) = @_;
1659: $id=&make_key($name,$id);
1660: my $setvalue=$value;
1661: if (!defined($setvalue)) {
1662: $setvalue='__undef__';
1663: }
1664: if (!defined($time) ) {
1665: $time=600;
1666: }
1667: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1668: my $result = $memcache->set($id,$setvalue,$time);
1669: if (! $result) {
1670: &logthis("caching of id -> $id failed");
1671: $memcache->disconnect_all();
1672: }
1673: # need to make a copy of $value
1674: &make_room($id,$value,$debug);
1675: return $value;
1676: }
1677:
1678: sub make_room {
1679: my ($id,$value,$debug)=@_;
1680:
1681: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1682: : $value;
1683: if ($to_remember<0) { return; }
1684: $accessed{$id}=[&gettimeofday()];
1685: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1686: my $to_kick;
1687: my $max_time=0;
1688: foreach my $other (keys(%accessed)) {
1689: if (&tv_interval($accessed{$other}) > $max_time) {
1690: $to_kick=$other;
1691: $max_time=&tv_interval($accessed{$other});
1692: }
1693: }
1694: delete($remembered{$to_kick});
1695: delete($accessed{$to_kick});
1696: $kicks++;
1697: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1698: return;
1699: }
1700:
1701: sub purge_remembered {
1702: #&logthis("Tossing ".scalar(keys(%remembered)));
1703: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1704: undef(%remembered);
1705: undef(%accessed);
1706: }
1707: # ------------------------------------- Read an entry from a user's environment
1708:
1709: sub userenvironment {
1710: my ($udom,$unam,@what)=@_;
1711: my $items;
1712: foreach my $item (@what) {
1713: $items.=&escape($item).'&';
1714: }
1715: $items=~s/\&$//;
1716: my %returnhash=();
1717: my $uhome = &homeserver($unam,$udom);
1718: unless ($uhome eq 'no_host') {
1719: my @answer=split(/\&/,
1720: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1721: my $i;
1722: for ($i=0;$i<=$#what;$i++) {
1723: $returnhash{$what[$i]}=&unescape($answer[$i]);
1724: }
1725: }
1726: return %returnhash;
1727: }
1728:
1729: # ---------------------------------------------------------- Get a studentphoto
1730: sub studentphoto {
1731: my ($udom,$unam,$ext) = @_;
1732: my $home=&Apache::lonnet::homeserver($unam,$udom);
1733: if (defined($env{'request.course.id'})) {
1734: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1735: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1736: return(&retrievestudentphoto($udom,$unam,$ext));
1737: } else {
1738: my ($result,$perm_reqd)=
1739: &Apache::lonnet::auto_photo_permission($unam,$udom);
1740: if ($result eq 'ok') {
1741: if (!($perm_reqd eq 'yes')) {
1742: return(&retrievestudentphoto($udom,$unam,$ext));
1743: }
1744: }
1745: }
1746: }
1747: } else {
1748: my ($result,$perm_reqd) =
1749: &Apache::lonnet::auto_photo_permission($unam,$udom);
1750: if ($result eq 'ok') {
1751: if (!($perm_reqd eq 'yes')) {
1752: return(&retrievestudentphoto($udom,$unam,$ext));
1753: }
1754: }
1755: }
1756: return '/adm/lonKaputt/lonlogo_broken.gif';
1757: }
1758:
1759: sub retrievestudentphoto {
1760: my ($udom,$unam,$ext,$type) = @_;
1761: my $home=&Apache::lonnet::homeserver($unam,$udom);
1762: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1763: if ($ret eq 'ok') {
1764: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1765: if ($type eq 'thumbnail') {
1766: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1767: }
1768: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1769: return $tokenurl;
1770: } else {
1771: if ($type eq 'thumbnail') {
1772: return '/adm/lonKaputt/genericstudent_tn.gif';
1773: } else {
1774: return '/adm/lonKaputt/lonlogo_broken.gif';
1775: }
1776: }
1777: }
1778:
1779: # -------------------------------------------------------------------- New chat
1780:
1781: sub chatsend {
1782: my ($newentry,$anon,$group)=@_;
1783: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1784: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1785: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1786: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1787: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1788: &escape($newentry)).':'.$group,$chome);
1789: }
1790:
1791: # ------------------------------------------ Find current version of a resource
1792:
1793: sub getversion {
1794: my $fname=&clutter(shift);
1795: unless ($fname=~/^\/res\//) { return -1; }
1796: return ¤tversion(&filelocation('',$fname));
1797: }
1798:
1799: sub currentversion {
1800: my $fname=shift;
1801: my ($result,$cached)=&is_cached_new('resversion',$fname);
1802: if (defined($cached)) { return $result; }
1803: my $author=$fname;
1804: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1805: my ($udom,$uname)=split(/\//,$author);
1806: my $home=homeserver($uname,$udom);
1807: if ($home eq 'no_host') {
1808: return -1;
1809: }
1810: my $answer=reply("currentversion:$fname",$home);
1811: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1812: return -1;
1813: }
1814: return &do_cache_new('resversion',$fname,$answer,600);
1815: }
1816:
1817: # ----------------------------- Subscribe to a resource, return URL if possible
1818:
1819: sub subscribe {
1820: my $fname=shift;
1821: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1822: $fname=~s/[\n\r]//g;
1823: my $author=$fname;
1824: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1825: my ($udom,$uname)=split(/\//,$author);
1826: my $home=homeserver($uname,$udom);
1827: if ($home eq 'no_host') {
1828: return 'not_found';
1829: }
1830: my $answer=reply("sub:$fname",$home);
1831: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1832: $answer.=' by '.$home;
1833: }
1834: return $answer;
1835: }
1836:
1837: # -------------------------------------------------------------- Replicate file
1838:
1839: sub repcopy {
1840: my $filename=shift;
1841: $filename=~s/\/+/\//g;
1842: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1843: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1844: if ($filename=~m|^/home/httpd/html/userfiles/| or
1845: $filename=~m -^/*(uploaded|editupload)/-) {
1846: return &repcopy_userfile($filename);
1847: }
1848: $filename=~s/[\n\r]//g;
1849: my $transname="$filename.in.transfer";
1850: # FIXME: this should flock
1851: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1852: my $remoteurl=subscribe($filename);
1853: if ($remoteurl =~ /^con_lost by/) {
1854: &logthis("Subscribe returned $remoteurl: $filename");
1855: return 'unavailable';
1856: } elsif ($remoteurl eq 'not_found') {
1857: #&logthis("Subscribe returned not_found: $filename");
1858: return 'not_found';
1859: } elsif ($remoteurl =~ /^rejected by/) {
1860: &logthis("Subscribe returned $remoteurl: $filename");
1861: return 'forbidden';
1862: } elsif ($remoteurl eq 'directory') {
1863: return 'ok';
1864: } else {
1865: my $author=$filename;
1866: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1867: my ($udom,$uname)=split(/\//,$author);
1868: my $home=homeserver($uname,$udom);
1869: unless ($home eq $perlvar{'lonHostID'}) {
1870: my @parts=split(/\//,$filename);
1871: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1872: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1873: &logthis("Malconfiguration for replication: $filename");
1874: return 'bad_request';
1875: }
1876: my $count;
1877: for ($count=5;$count<$#parts;$count++) {
1878: $path.="/$parts[$count]";
1879: if ((-e $path)!=1) {
1880: mkdir($path,0777);
1881: }
1882: }
1883: my $ua=new LWP::UserAgent;
1884: my $request=new HTTP::Request('GET',"$remoteurl");
1885: my $response=$ua->request($request,$transname);
1886: if ($response->is_error()) {
1887: unlink($transname);
1888: my $message=$response->status_line;
1889: &logthis("<font color=\"blue\">WARNING:"
1890: ." LWP get: $message: $filename</font>");
1891: return 'unavailable';
1892: } else {
1893: if ($remoteurl!~/\.meta$/) {
1894: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1895: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1896: if ($mresponse->is_error()) {
1897: unlink($filename.'.meta');
1898: &logthis(
1899: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1900: }
1901: }
1902: rename($transname,$filename);
1903: return 'ok';
1904: }
1905: }
1906: }
1907: }
1908:
1909: # ------------------------------------------------ Get server side include body
1910: sub ssi_body {
1911: my ($filelink,%form)=@_;
1912: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1913: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1914: }
1915: my $output='';
1916: my $response;
1917: if ($filelink=~/^https?\:/) {
1918: ($output,$response)=&externalssi($filelink);
1919: } else {
1920: $filelink .= $filelink=~/\?/ ? '&' : '?';
1921: $filelink .= 'inhibitmenu=yes';
1922: ($output,$response)=&ssi($filelink,%form);
1923: }
1924: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1925: $output=~s/^.*?\<body[^\>]*\>//si;
1926: $output=~s/\<\/body\s*\>.*?$//si;
1927: if (wantarray) {
1928: return ($output, $response);
1929: } else {
1930: return $output;
1931: }
1932: }
1933:
1934: # --------------------------------------------------------- Server Side Include
1935:
1936: sub absolute_url {
1937: my ($host_name) = @_;
1938: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1939: if ($host_name eq '') {
1940: $host_name = $ENV{'SERVER_NAME'};
1941: }
1942: return $protocol.$host_name;
1943: }
1944:
1945: #
1946: # Server side include.
1947: # Parameters:
1948: # fn Possibly encrypted resource name/id.
1949: # form Hash that describes how the rendering should be done
1950: # and other things.
1951: # Returns:
1952: # Scalar context: The content of the response.
1953: # Array context: 2 element list of the content and the full response object.
1954: #
1955: sub ssi {
1956:
1957: my ($fn,%form)=@_;
1958: my $ua=new LWP::UserAgent;
1959: my $request;
1960:
1961: $form{'no_update_last_known'}=1;
1962: &Apache::lonenc::check_encrypt(\$fn);
1963: if (%form) {
1964: $request=new HTTP::Request('POST',&absolute_url().$fn);
1965: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1966: } else {
1967: $request=new HTTP::Request('GET',&absolute_url().$fn);
1968: }
1969:
1970: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1971: my $response=$ua->request($request);
1972:
1973: if (wantarray) {
1974: return ($response->content, $response);
1975: } else {
1976: return $response->content;
1977: }
1978: }
1979:
1980: sub externalssi {
1981: my ($url)=@_;
1982: my $ua=new LWP::UserAgent;
1983: my $request=new HTTP::Request('GET',$url);
1984: my $response=$ua->request($request);
1985: if (wantarray) {
1986: return ($response->content, $response);
1987: } else {
1988: return $response->content;
1989: }
1990: }
1991:
1992: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1993:
1994: sub allowuploaded {
1995: my ($srcurl,$url)=@_;
1996: $url=&clutter(&declutter($url));
1997: my $dir=$url;
1998: $dir=~s/\/[^\/]+$//;
1999: my %httpref=();
2000: my $httpurl=&hreflocation('',$url);
2001: $httpref{'httpref.'.$httpurl}=$srcurl;
2002: &Apache::lonnet::appenv(\%httpref);
2003: }
2004:
2005: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2006: # input: action, courseID, current domain, intended
2007: # path to file, source of file, instruction to parse file for objects,
2008: # ref to hash for embedded objects,
2009: # ref to hash for codebase of java objects.
2010: #
2011: # output: url to file (if action was uploaddoc),
2012: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2013: #
2014: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2015: # course.
2016: #
2017: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2018: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2019: # course's home server.
2020: #
2021: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2022: # be copied from $source (current location) to
2023: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2024: # and will then be copied to
2025: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2026: # course's home server.
2027: #
2028: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2029: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2030: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2031: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2032: # in course's home server.
2033: #
2034:
2035: sub process_coursefile {
2036: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
2037: my $fetchresult;
2038: my $home=&homeserver($docuname,$docudom);
2039: if ($action eq 'propagate') {
2040: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2041: $home);
2042: } else {
2043: my $fpath = '';
2044: my $fname = $file;
2045: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2046: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2047: my $filepath = &build_filepath($fpath);
2048: if ($action eq 'copy') {
2049: if ($source eq '') {
2050: $fetchresult = 'no source file';
2051: return $fetchresult;
2052: } else {
2053: my $destination = $filepath.'/'.$fname;
2054: rename($source,$destination);
2055: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2056: $home);
2057: }
2058: } elsif ($action eq 'uploaddoc') {
2059: open(my $fh,'>'.$filepath.'/'.$fname);
2060: print $fh $env{'form.'.$source};
2061: close($fh);
2062: if ($parser eq 'parse') {
2063: my $mm = new File::MMagic;
2064: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2065: if ($mime_type eq 'text/html') {
2066: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2067: unless ($parse_result eq 'ok') {
2068: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2069: }
2070: }
2071: }
2072: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2073: $home);
2074: if ($fetchresult eq 'ok') {
2075: return '/uploaded/'.$fpath.'/'.$fname;
2076: } else {
2077: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2078: ' to host '.$home.': '.$fetchresult);
2079: return '/adm/notfound.html';
2080: }
2081: }
2082: }
2083: unless ( $fetchresult eq 'ok') {
2084: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2085: ' to host '.$home.': '.$fetchresult);
2086: }
2087: return $fetchresult;
2088: }
2089:
2090: sub build_filepath {
2091: my ($fpath) = @_;
2092: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2093: unless ($fpath eq '') {
2094: my @parts=split('/',$fpath);
2095: foreach my $part (@parts) {
2096: $filepath.= '/'.$part;
2097: if ((-e $filepath)!=1) {
2098: mkdir($filepath,0777);
2099: }
2100: }
2101: }
2102: return $filepath;
2103: }
2104:
2105: sub store_edited_file {
2106: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2107: my $file = $primary_url;
2108: $file =~ s#^/uploaded/$docudom/$docuname/##;
2109: my $fpath = '';
2110: my $fname = $file;
2111: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2112: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2113: my $filepath = &build_filepath($fpath);
2114: open(my $fh,'>'.$filepath.'/'.$fname);
2115: print $fh $content;
2116: close($fh);
2117: my $home=&homeserver($docuname,$docudom);
2118: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2119: $home);
2120: if ($$fetchresult eq 'ok') {
2121: return '/uploaded/'.$fpath.'/'.$fname;
2122: } else {
2123: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2124: ' to host '.$home.': '.$$fetchresult);
2125: return '/adm/notfound.html';
2126: }
2127: }
2128:
2129: sub clean_filename {
2130: my ($fname,$args)=@_;
2131: # Replace Windows backslashes by forward slashes
2132: $fname=~s/\\/\//g;
2133: if (!$args->{'keep_path'}) {
2134: # Get rid of everything but the actual filename
2135: $fname=~s/^.*\/([^\/]+)$/$1/;
2136: }
2137: # Replace spaces by underscores
2138: $fname=~s/\s+/\_/g;
2139: # Replace all other weird characters by nothing
2140: $fname=~s{[^/\w\.\-]}{}g;
2141: # Replace all .\d. sequences with _\d. so they no longer look like version
2142: # numbers
2143: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2144: return $fname;
2145: }
2146: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2147: sub resizeImage {
2148: my($img_url) = @_;
2149: my $ima = Image::Magick->new;
2150: $ima->Read($img_url);
2151: if($ima->Get('width') > 400)
2152: {
2153: my $factor = $ima->Get('width')/400;
2154: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2155: }
2156: if($ima->Get('height') > 500)
2157: {
2158: my $factor = $ima->Get('height')/500;
2159: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2160: }
2161:
2162: $ima->Write($img_url);
2163: }
2164:
2165: #Wrapper function for userphotoupload
2166: sub userphotoupload
2167: {
2168: my($formname,$subdir) = @_;
2169: $upload_photo_form = 1;
2170: return &userfileupload($formname,undef,$subdir);
2171: }
2172:
2173: # --------------- Take an uploaded file and put it into the userfiles directory
2174: # input: $formname - the contents of the file are in $env{"form.$formname"}
2175: # the desired filenam is in $env{"form.$formname.filename"}
2176: # $coursedoc - if true up to the current course
2177: # if false
2178: # $subdir - directory in userfile to store the file into
2179: # $parser - instruction to parse file for objects ($parser = parse)
2180: # $allfiles - reference to hash for embedded objects
2181: # $codebase - reference to hash for codebase of java objects
2182: # $desuname - username for permanent storage of uploaded file
2183: # $dsetudom - domain for permanaent storage of uploaded file
2184: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2185: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2186: #
2187: # output: url of file in userspace, or error: <message>
2188: # or /adm/notfound.html if failure to upload occurse
2189:
2190:
2191: sub userfileupload {
2192: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2193: $destudom,$thumbwidth,$thumbheight)=@_;
2194: if (!defined($subdir)) { $subdir='unknown'; }
2195: my $fname=$env{'form.'.$formname.'.filename'};
2196: $fname=&clean_filename($fname);
2197: # See if there is anything left
2198: unless ($fname) { return 'error: no uploaded file'; }
2199: chop($env{'form.'.$formname});
2200: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2201: my $now = time;
2202: my $filepath = 'tmp/helprequests/'.$now;
2203: my @parts=split(/\//,$filepath);
2204: my $fullpath = $perlvar{'lonDaemons'};
2205: for (my $i=0;$i<@parts;$i++) {
2206: $fullpath .= '/'.$parts[$i];
2207: if ((-e $fullpath)!=1) {
2208: mkdir($fullpath,0777);
2209: }
2210: }
2211: open(my $fh,'>'.$fullpath.'/'.$fname);
2212: print $fh $env{'form.'.$formname};
2213: close($fh);
2214: return $fullpath.'/'.$fname;
2215: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2216: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2217: '_'.$env{'user.domain'}.'/pending';
2218: my @parts=split(/\//,$filepath);
2219: my $fullpath = $perlvar{'lonDaemons'};
2220: for (my $i=0;$i<@parts;$i++) {
2221: $fullpath .= '/'.$parts[$i];
2222: if ((-e $fullpath)!=1) {
2223: mkdir($fullpath,0777);
2224: }
2225: }
2226: open(my $fh,'>'.$fullpath.'/'.$fname);
2227: print $fh $env{'form.'.$formname};
2228: close($fh);
2229: return $fullpath.'/'.$fname;
2230: }
2231: if ($subdir eq 'scantron') {
2232: $fname = 'scantron_orig_'.$fname;
2233: } else {
2234: # Create the directory if not present
2235: $fname="$subdir/$fname";
2236: }
2237: if ($coursedoc) {
2238: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2239: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2240: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2241: return &finishuserfileupload($docuname,$docudom,
2242: $formname,$fname,$parser,$allfiles,
2243: $codebase,$thumbwidth,$thumbheight);
2244: } else {
2245: $fname=$env{'form.folder'}.'/'.$fname;
2246: return &process_coursefile('uploaddoc',$docuname,$docudom,
2247: $fname,$formname,$parser,
2248: $allfiles,$codebase);
2249: }
2250: } elsif (defined($destuname)) {
2251: my $docuname=$destuname;
2252: my $docudom=$destudom;
2253: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2254: $parser,$allfiles,$codebase,
2255: $thumbwidth,$thumbheight);
2256:
2257: } else {
2258: my $docuname=$env{'user.name'};
2259: my $docudom=$env{'user.domain'};
2260: if (exists($env{'form.group'})) {
2261: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2262: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2263: }
2264: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2265: $parser,$allfiles,$codebase,
2266: $thumbwidth,$thumbheight);
2267: }
2268: }
2269:
2270: sub finishuserfileupload {
2271: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2272: $thumbwidth,$thumbheight) = @_;
2273: my $path=$docudom.'/'.$docuname.'/';
2274: my $filepath=$perlvar{'lonDocRoot'};
2275:
2276: my ($fnamepath,$file,$fetchthumb);
2277: $file=$fname;
2278: if ($fname=~m|/|) {
2279: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2280: $path.=$fnamepath.'/';
2281: }
2282: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2283: my $count;
2284: for ($count=4;$count<=$#parts;$count++) {
2285: $filepath.="/$parts[$count]";
2286: if ((-e $filepath)!=1) {
2287: mkdir($filepath,0777);
2288: }
2289: }
2290:
2291: # Save the file
2292: {
2293: if (!open(FH,'>'.$filepath.'/'.$file)) {
2294: &logthis('Failed to create '.$filepath.'/'.$file);
2295: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2296: return '/adm/notfound.html';
2297: }
2298: if (!print FH ($env{'form.'.$formname})) {
2299: &logthis('Failed to write to '.$filepath.'/'.$file);
2300: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2301: return '/adm/notfound.html';
2302: }
2303: close(FH);
2304: if($upload_photo_form==1)
2305: {
2306: resizeImage($filepath.'/'.$file);
2307: $upload_photo_form = 0;
2308: }
2309: }
2310: if ($parser eq 'parse') {
2311: my $mm = new File::MMagic;
2312: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2313: if ($mime_type eq 'text/html') {
2314: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2315: $allfiles,$codebase);
2316: unless ($parse_result eq 'ok') {
2317: &logthis('Failed to parse '.$filepath.$file.
2318: ' for embedded media: '.$parse_result);
2319: }
2320: }
2321: }
2322: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2323: my $input = $filepath.'/'.$file;
2324: my $output = $filepath.'/'.'tn-'.$file;
2325: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2326: system("convert -sample $thumbsize $input $output");
2327: if (-e $filepath.'/'.'tn-'.$file) {
2328: $fetchthumb = 1;
2329: }
2330: }
2331:
2332: # Notify homeserver to grep it
2333: #
2334: my $docuhome=&homeserver($docuname,$docudom);
2335: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2336: if ($fetchresult eq 'ok') {
2337: if ($fetchthumb) {
2338: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2339: if ($thumbresult ne 'ok') {
2340: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2341: $docuhome.': '.$thumbresult);
2342: }
2343: }
2344: #
2345: # Return the URL to it
2346: return '/uploaded/'.$path.$file;
2347: } else {
2348: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2349: ': '.$fetchresult);
2350: return '/adm/notfound.html';
2351: }
2352: }
2353:
2354: sub extract_embedded_items {
2355: my ($fullpath,$allfiles,$codebase,$content) = @_;
2356: my @state = ();
2357: my %javafiles = (
2358: codebase => '',
2359: code => '',
2360: archive => ''
2361: );
2362: my %mediafiles = (
2363: src => '',
2364: movie => '',
2365: );
2366: my $p;
2367: if ($content) {
2368: $p = HTML::LCParser->new($content);
2369: } else {
2370: $p = HTML::LCParser->new($fullpath);
2371: }
2372: while (my $t=$p->get_token()) {
2373: if ($t->[0] eq 'S') {
2374: my ($tagname, $attr) = ($t->[1],$t->[2]);
2375: push(@state, $tagname);
2376: if (lc($tagname) eq 'allow') {
2377: &add_filetype($allfiles,$attr->{'src'},'src');
2378: }
2379: if (lc($tagname) eq 'img') {
2380: &add_filetype($allfiles,$attr->{'src'},'src');
2381: }
2382: if (lc($tagname) eq 'a') {
2383: &add_filetype($allfiles,$attr->{'href'},'href');
2384: }
2385: if (lc($tagname) eq 'script') {
2386: if ($attr->{'archive'} =~ /\.jar$/i) {
2387: &add_filetype($allfiles,$attr->{'archive'},'archive');
2388: } else {
2389: &add_filetype($allfiles,$attr->{'src'},'src');
2390: }
2391: }
2392: if (lc($tagname) eq 'link') {
2393: if (lc($attr->{'rel'}) eq 'stylesheet') {
2394: &add_filetype($allfiles,$attr->{'href'},'href');
2395: }
2396: }
2397: if (lc($tagname) eq 'object' ||
2398: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2399: foreach my $item (keys(%javafiles)) {
2400: $javafiles{$item} = '';
2401: }
2402: }
2403: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2404: my $name = lc($attr->{'name'});
2405: foreach my $item (keys(%javafiles)) {
2406: if ($name eq $item) {
2407: $javafiles{$item} = $attr->{'value'};
2408: last;
2409: }
2410: }
2411: foreach my $item (keys(%mediafiles)) {
2412: if ($name eq $item) {
2413: &add_filetype($allfiles, $attr->{'value'}, 'value');
2414: last;
2415: }
2416: }
2417: }
2418: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2419: foreach my $item (keys(%javafiles)) {
2420: if ($attr->{$item}) {
2421: $javafiles{$item} = $attr->{$item};
2422: last;
2423: }
2424: }
2425: foreach my $item (keys(%mediafiles)) {
2426: if ($attr->{$item}) {
2427: &add_filetype($allfiles,$attr->{$item},$item);
2428: last;
2429: }
2430: }
2431: }
2432: } elsif ($t->[0] eq 'E') {
2433: my ($tagname) = ($t->[1]);
2434: if ($javafiles{'codebase'} ne '') {
2435: $javafiles{'codebase'} .= '/';
2436: }
2437: if (lc($tagname) eq 'applet' ||
2438: lc($tagname) eq 'object' ||
2439: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2440: ) {
2441: foreach my $item (keys(%javafiles)) {
2442: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2443: my $file=$javafiles{'codebase'}.$javafiles{$item};
2444: &add_filetype($allfiles,$file,$item);
2445: }
2446: }
2447: }
2448: pop @state;
2449: }
2450: }
2451: return 'ok';
2452: }
2453:
2454: sub add_filetype {
2455: my ($allfiles,$file,$type)=@_;
2456: if (exists($allfiles->{$file})) {
2457: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2458: push(@{$allfiles->{$file}}, &escape($type));
2459: }
2460: } else {
2461: @{$allfiles->{$file}} = (&escape($type));
2462: }
2463: }
2464:
2465: sub removeuploadedurl {
2466: my ($url)=@_;
2467: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
2468: return &removeuserfile($uname,$udom,$fname);
2469: }
2470:
2471: sub removeuserfile {
2472: my ($docuname,$docudom,$fname)=@_;
2473: my $home=&homeserver($docuname,$docudom);
2474: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2475: if ($result eq 'ok') {
2476: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2477: my $metafile = $fname.'.meta';
2478: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
2479: my $url = "/uploaded/$docudom/$docuname/$fname";
2480: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2481: my $sqlresult =
2482: &update_portfolio_table($docuname,$docudom,$file,
2483: 'portfolio_metadata',$group,
2484: 'delete');
2485: }
2486: }
2487: return $result;
2488: }
2489:
2490: sub mkdiruserfile {
2491: my ($docuname,$docudom,$dir)=@_;
2492: my $home=&homeserver($docuname,$docudom);
2493: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2494: }
2495:
2496: sub renameuserfile {
2497: my ($docuname,$docudom,$old,$new)=@_;
2498: my $home=&homeserver($docuname,$docudom);
2499: my $result = &reply("renameuserfile:$docudom:$docuname:".
2500: &escape("$old").':'.&escape("$new"),$home);
2501: if ($result eq 'ok') {
2502: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2503: my $oldmeta = $old.'.meta';
2504: my $newmeta = $new.'.meta';
2505: my $metaresult =
2506: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
2507: my $url = "/uploaded/$docudom/$docuname/$old";
2508: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2509: my $sqlresult =
2510: &update_portfolio_table($docuname,$docudom,$file,
2511: 'portfolio_metadata',$group,
2512: 'delete');
2513: }
2514: }
2515: return $result;
2516: }
2517:
2518: # ------------------------------------------------------------------------- Log
2519:
2520: sub log {
2521: my ($dom,$nam,$hom,$what)=@_;
2522: return critical("log:$dom:$nam:$what",$hom);
2523: }
2524:
2525: # ------------------------------------------------------------------ Course Log
2526: #
2527: # This routine flushes several buffers of non-mission-critical nature
2528: #
2529:
2530: sub flushcourselogs {
2531: &logthis('Flushing log buffers');
2532: #
2533: # course logs
2534: # This is a log of all transactions in a course, which can be used
2535: # for data mining purposes
2536: #
2537: # It also collects the courseid database, which lists last transaction
2538: # times and course titles for all courseids
2539: #
2540: my %courseidbuffer=();
2541: foreach my $crsid (keys(%courselogs)) {
2542: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
2543: &escape($courselogs{$crsid}),
2544: $coursehombuf{$crsid}) eq 'ok') {
2545: delete $courselogs{$crsid};
2546: } else {
2547: &logthis('Failed to flush log buffer for '.$crsid);
2548: if (length($courselogs{$crsid})>40000) {
2549: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
2550: " exceeded maximum size, deleting.</font>");
2551: delete $courselogs{$crsid};
2552: }
2553: }
2554: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
2555: 'description' => $coursedescrbuf{$crsid},
2556: 'inst_code' => $courseinstcodebuf{$crsid},
2557: 'type' => $coursetypebuf{$crsid},
2558: 'owner' => $courseownerbuf{$crsid},
2559: };
2560: }
2561: #
2562: # Write course id database (reverse lookup) to homeserver of courses
2563: # Is used in pickcourse
2564: #
2565: foreach my $crs_home (keys(%courseidbuffer)) {
2566: my $response = &courseidput(&host_domain($crs_home),
2567: $courseidbuffer{$crs_home},
2568: $crs_home,'timeonly');
2569: }
2570: #
2571: # File accesses
2572: # Writes to the dynamic metadata of resources to get hit counts, etc.
2573: #
2574: foreach my $entry (keys(%accesshash)) {
2575: if ($entry =~ /___count$/) {
2576: my ($dom,$name);
2577: ($dom,$name,undef)=
2578: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
2579: if (! defined($dom) || $dom eq '' ||
2580: ! defined($name) || $name eq '') {
2581: my $cid = $env{'request.course.id'};
2582: $dom = $env{'request.'.$cid.'.domain'};
2583: $name = $env{'request.'.$cid.'.num'};
2584: }
2585: my $value = $accesshash{$entry};
2586: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2587: my %temphash=($url => $value);
2588: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2589: if ($result eq 'ok') {
2590: delete $accesshash{$entry};
2591: } elsif ($result eq 'unknown_cmd') {
2592: # Target server has old code running on it.
2593: my %temphash=($entry => $value);
2594: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2595: delete $accesshash{$entry};
2596: }
2597: }
2598: } else {
2599: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
2600: my %temphash=($entry => $accesshash{$entry});
2601: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2602: delete $accesshash{$entry};
2603: }
2604: }
2605: }
2606: #
2607: # Roles
2608: # Reverse lookup of user roles for course faculty/staff and co-authorship
2609: #
2610: foreach my $entry (keys(%userrolehash)) {
2611: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
2612: split(/\:/,$entry);
2613: if (&Apache::lonnet::put('nohist_userroles',
2614: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
2615: $rudom,$runame) eq 'ok') {
2616: delete $userrolehash{$entry};
2617: }
2618: }
2619: #
2620: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2621: #
2622: my %domrolebuffer = ();
2623: foreach my $entry (keys(%domainrolehash)) {
2624: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
2625: if ($domrolebuffer{$rudom}) {
2626: $domrolebuffer{$rudom}.='&'.&escape($entry).
2627: '='.&escape($domainrolehash{$entry});
2628: } else {
2629: $domrolebuffer{$rudom}.=&escape($entry).
2630: '='.&escape($domainrolehash{$entry});
2631: }
2632: delete $domainrolehash{$entry};
2633: }
2634: foreach my $dom (keys(%domrolebuffer)) {
2635: my %servers = &get_servers($dom,'library');
2636: foreach my $tryserver (keys(%servers)) {
2637: unless (&reply('domroleput:'.$dom.':'.
2638: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2639: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2640: }
2641: }
2642: }
2643: $dumpcount++;
2644: }
2645:
2646: sub courselog {
2647: my $what=shift;
2648: $what=time.':'.$what;
2649: unless ($env{'request.course.id'}) { return ''; }
2650: $coursedombuf{$env{'request.course.id'}}=
2651: $env{'course.'.$env{'request.course.id'}.'.domain'};
2652: $coursenumbuf{$env{'request.course.id'}}=
2653: $env{'course.'.$env{'request.course.id'}.'.num'};
2654: $coursehombuf{$env{'request.course.id'}}=
2655: $env{'course.'.$env{'request.course.id'}.'.home'};
2656: $coursedescrbuf{$env{'request.course.id'}}=
2657: $env{'course.'.$env{'request.course.id'}.'.description'};
2658: $courseinstcodebuf{$env{'request.course.id'}}=
2659: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2660: $courseownerbuf{$env{'request.course.id'}}=
2661: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
2662: $coursetypebuf{$env{'request.course.id'}}=
2663: $env{'course.'.$env{'request.course.id'}.'.type'};
2664: if (defined $courselogs{$env{'request.course.id'}}) {
2665: $courselogs{$env{'request.course.id'}}.='&'.$what;
2666: } else {
2667: $courselogs{$env{'request.course.id'}}.=$what;
2668: }
2669: if (length($courselogs{$env{'request.course.id'}})>4048) {
2670: &flushcourselogs();
2671: }
2672: }
2673:
2674: sub courseacclog {
2675: my $fnsymb=shift;
2676: unless ($env{'request.course.id'}) { return ''; }
2677: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2678: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2679: $what.=':POST';
2680: # FIXME: Probably ought to escape things....
2681: foreach my $key (keys(%env)) {
2682: if ($key=~/^form\.(.*)/) {
2683: my $formitem = $1;
2684: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2685: $what.=':'.$formitem.'='.$env{$key};
2686: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2687: $what.=':'.$formitem.'='.$env{$key};
2688: }
2689: }
2690: }
2691: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2692: # FIXME: We should not be depending on a form parameter that someone
2693: # editing lonsearchcat.pm might change in the future.
2694: if ($env{'form.phase'} eq 'course_search') {
2695: $what.= ':POST';
2696: # FIXME: Probably ought to escape things....
2697: foreach my $element ('courseexp','crsfulltext','crsrelated',
2698: 'crsdiscuss') {
2699: $what.=':'.$element.'='.$env{'form.'.$element};
2700: }
2701: }
2702: }
2703: &courselog($what);
2704: }
2705:
2706: sub countacc {
2707: my $url=&declutter(shift);
2708: return if (! defined($url) || $url eq '');
2709: unless ($env{'request.course.id'}) { return ''; }
2710: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2711: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2712: $accesshash{$key}++;
2713: }
2714:
2715: sub linklog {
2716: my ($from,$to)=@_;
2717: $from=&declutter($from);
2718: $to=&declutter($to);
2719: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2720: $accesshash{$to.'___'.$from.'___goto'}=1;
2721: }
2722:
2723: sub userrolelog {
2724: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2725: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2726: ($trole=~/^in/) || ($trole=~/^cc/) ||
2727: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2728: ($trole=~/^ta/)) {
2729: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2730: $userrolehash
2731: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2732: =$tend.':'.$tstart;
2733: }
2734: if (($env{'request.role'} =~ /dc\./) &&
2735: (($trole=~/^au/) || ($trole=~/^in/) ||
2736: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2737: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2738: $userrolehash
2739: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2740: =$tend.':'.$tstart;
2741: }
2742: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2743: ($trole=~/^li/) || ($trole=~/^li/) ||
2744: ($trole=~/^au/) || ($trole=~/^dg/) ||
2745: ($trole=~/^sc/)) {
2746: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2747: $domainrolehash
2748: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2749: = $tend.':'.$tstart;
2750: }
2751: }
2752:
2753: sub courserolelog {
2754: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2755: if (($trole eq 'cc') || ($trole eq 'in') ||
2756: ($trole eq 'ep') || ($trole eq 'ad') ||
2757: ($trole eq 'ta') || ($trole eq 'st') ||
2758: ($trole=~/^cr/) || ($trole eq 'gr')) {
2759: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2760: my $cdom = $1;
2761: my $cnum = $2;
2762: my $sec = $3;
2763: my $namespace = 'rolelog';
2764: my %storehash = (
2765: role => $trole,
2766: start => $tstart,
2767: end => $tend,
2768: selfenroll => $selfenroll,
2769: context => $context,
2770: );
2771: if ($trole eq 'gr') {
2772: $namespace = 'groupslog';
2773: $storehash{'group'} = $sec;
2774: } else {
2775: $storehash{'section'} = $sec;
2776: }
2777: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2778: if (($trole ne 'st') || ($sec ne '')) {
2779: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2780: }
2781: }
2782: }
2783: return;
2784: }
2785:
2786: sub get_course_adv_roles {
2787: my ($cid,$codes) = @_;
2788: $cid=$env{'request.course.id'} unless (defined($cid));
2789: my %coursehash=&coursedescription($cid);
2790: my $crstype = &Apache::loncommon::course_type($cid);
2791: my %nothide=();
2792: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2793: if ($user !~ /:/) {
2794: $nothide{join(':',split(/[\@]/,$user))}=1;
2795: } else {
2796: $nothide{$user}=1;
2797: }
2798: }
2799: my %returnhash=();
2800: my %dumphash=
2801: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2802: my $now=time;
2803: my %privileged;
2804: foreach my $entry (keys(%dumphash)) {
2805: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2806: if (($tstart) && ($tstart<0)) { next; }
2807: if (($tend) && ($tend<$now)) { next; }
2808: if (($tstart) && ($now<$tstart)) { next; }
2809: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2810: if ($username eq '' || $domain eq '') { next; }
2811: unless (ref($privileged{$domain}) eq 'HASH') {
2812: my %dompersonnel =
2813: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2814: $privileged{$domain} = {};
2815: foreach my $server (keys(%dompersonnel)) {
2816: if (ref($dompersonnel{$server}) eq 'HASH') {
2817: foreach my $user (keys(%{$dompersonnel{$server}})) {
2818: my ($trole,$uname,$udom) = split(/:/,$user);
2819: $privileged{$udom}{$uname} = 1;
2820: }
2821: }
2822: }
2823: }
2824: if ((exists($privileged{$domain}{$username})) &&
2825: (!$nothide{$username.':'.$domain})) { next; }
2826: if ($role eq 'cr') { next; }
2827: if ($codes) {
2828: if ($section) { $role .= ':'.$section; }
2829: if ($returnhash{$role}) {
2830: $returnhash{$role}.=','.$username.':'.$domain;
2831: } else {
2832: $returnhash{$role}=$username.':'.$domain;
2833: }
2834: } else {
2835: my $key=&plaintext($role,$crstype);
2836: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
2837: if ($returnhash{$key}) {
2838: $returnhash{$key}.=','.$username.':'.$domain;
2839: } else {
2840: $returnhash{$key}=$username.':'.$domain;
2841: }
2842: }
2843: }
2844: return %returnhash;
2845: }
2846:
2847: sub get_my_roles {
2848: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
2849: unless (defined($uname)) { $uname=$env{'user.name'}; }
2850: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2851: my (%dumphash,%nothide);
2852: if ($context eq 'userroles') {
2853: %dumphash = &dump('roles',$udom,$uname);
2854: } else {
2855: %dumphash=
2856: &dump('nohist_userroles',$udom,$uname);
2857: if ($hidepriv) {
2858: my %coursehash=&coursedescription($udom.'_'.$uname);
2859: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2860: if ($user !~ /:/) {
2861: $nothide{join(':',split(/[\@]/,$user))} = 1;
2862: } else {
2863: $nothide{$user} = 1;
2864: }
2865: }
2866: }
2867: }
2868: my %returnhash=();
2869: my $now=time;
2870: my %privileged;
2871: foreach my $entry (keys(%dumphash)) {
2872: my ($role,$tend,$tstart);
2873: if ($context eq 'userroles') {
2874: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2875: } else {
2876: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2877: }
2878: if (($tstart) && ($tstart<0)) { next; }
2879: my $status = 'active';
2880: if (($tend) && ($tend<=$now)) {
2881: $status = 'previous';
2882: }
2883: if (($tstart) && ($now<$tstart)) {
2884: $status = 'future';
2885: }
2886: if (ref($types) eq 'ARRAY') {
2887: if (!grep(/^\Q$status\E$/,@{$types})) {
2888: next;
2889: }
2890: } else {
2891: if ($status ne 'active') {
2892: next;
2893: }
2894: }
2895: my ($rolecode,$username,$domain,$section,$area);
2896: if ($context eq 'userroles') {
2897: ($area,$rolecode) = split(/_/,$entry);
2898: (undef,$domain,$username,$section) = split(/\//,$area);
2899: } else {
2900: ($role,$username,$domain,$section) = split(/\:/,$entry);
2901: }
2902: if (ref($roledoms) eq 'ARRAY') {
2903: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2904: next;
2905: }
2906: }
2907: if (ref($roles) eq 'ARRAY') {
2908: if (!grep(/^\Q$role\E$/,@{$roles})) {
2909: if ($role =~ /^cr\//) {
2910: if (!grep(/^cr$/,@{$roles})) {
2911: next;
2912: }
2913: } else {
2914: next;
2915: }
2916: }
2917: }
2918: if ($hidepriv) {
2919: if ($context eq 'userroles') {
2920: if ((&privileged($username,$domain)) &&
2921: (!$nothide{$username.':'.$domain})) {
2922: next;
2923: }
2924: } else {
2925: unless (ref($privileged{$domain}) eq 'HASH') {
2926: my %dompersonnel =
2927: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2928: $privileged{$domain} = {};
2929: if (keys(%dompersonnel)) {
2930: foreach my $server (keys(%dompersonnel)) {
2931: if (ref($dompersonnel{$server}) eq 'HASH') {
2932: foreach my $user (keys(%{$dompersonnel{$server}})) {
2933: my ($trole,$uname,$udom) = split(/:/,$user);
2934: $privileged{$udom}{$uname} = $trole;
2935: }
2936: }
2937: }
2938: }
2939: }
2940: if (exists($privileged{$domain}{$username})) {
2941: if (!$nothide{$username.':'.$domain}) {
2942: next;
2943: }
2944: }
2945: }
2946: }
2947: if ($withsec) {
2948: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2949: $tstart.':'.$tend;
2950: } else {
2951: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2952: }
2953: }
2954: return %returnhash;
2955: }
2956:
2957: # ----------------------------------------------------- Frontpage Announcements
2958: #
2959: #
2960:
2961: sub postannounce {
2962: my ($server,$text)=@_;
2963: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
2964: unless ($text=~/\w/) { $text=''; }
2965: return &reply('setannounce:'.&escape($text),$server);
2966: }
2967:
2968: sub getannounce {
2969:
2970: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2971: my $announcement='';
2972: while (my $line = <$fh>) { $announcement .= $line; }
2973: close($fh);
2974: if ($announcement=~/\w/) {
2975: return
2976: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2977: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2978: } else {
2979: return '';
2980: }
2981: } else {
2982: return '';
2983: }
2984: }
2985:
2986: # ---------------------------------------------------------- Course ID routines
2987: # Deal with domain's nohist_courseid.db files
2988: #
2989:
2990: sub courseidput {
2991: my ($domain,$storehash,$coursehome,$caller) = @_;
2992: my $outcome;
2993: if ($caller eq 'timeonly') {
2994: my $cids = '';
2995: foreach my $item (keys(%$storehash)) {
2996: $cids.=&escape($item).'&';
2997: }
2998: $cids=~s/\&$//;
2999: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3000: $coursehome);
3001: } else {
3002: my $items = '';
3003: foreach my $item (keys(%$storehash)) {
3004: $items.= &escape($item).'='.
3005: &freeze_escape($$storehash{$item}).'&';
3006: }
3007: $items=~s/\&$//;
3008: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3009: $coursehome);
3010: }
3011: if ($outcome eq 'unknown_cmd') {
3012: my $what;
3013: foreach my $cid (keys(%$storehash)) {
3014: $what .= &escape($cid).'=';
3015: foreach my $item ('description','inst_code','owner','type') {
3016: $what .= &escape($storehash->{$cid}{$item}).':';
3017: }
3018: $what =~ s/\:$/&/;
3019: }
3020: $what =~ s/\&$//;
3021: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3022: } else {
3023: return $outcome;
3024: }
3025: }
3026:
3027: sub courseiddump {
3028: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3029: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3030: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3031: $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
3032: my $as_hash = 1;
3033: my %returnhash;
3034: if (!$domfilter) { $domfilter=''; }
3035: my %libserv = &all_library();
3036: foreach my $tryserver (keys(%libserv)) {
3037: if ( ( $hostidflag == 1
3038: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3039: || (!defined($hostidflag)) ) {
3040:
3041: if (($domfilter eq '') ||
3042: (&host_domain($tryserver) eq $domfilter)) {
3043: my $rep =
3044: &reply('courseiddump:'.&host_domain($tryserver).':'.
3045: $sincefilter.':'.&escape($descfilter).':'.
3046: &escape($instcodefilter).':'.&escape($ownerfilter).
3047: ':'.&escape($coursefilter).':'.&escape($typefilter).
3048: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3049: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3050: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3051: &escape($cc_clone).':'.$cloneonly.':'.
3052: &escape($createdbefore).':'.&escape($createdafter).':'.
3053: &escape($creationcontext),$tryserver);
3054: my @pairs=split(/\&/,$rep);
3055: foreach my $item (@pairs) {
3056: my ($key,$value)=split(/\=/,$item,2);
3057: $key = &unescape($key);
3058: next if ($key =~ /^error: 2 /);
3059: my $result = &thaw_unescape($value);
3060: if (ref($result) eq 'HASH') {
3061: $returnhash{$key}=$result;
3062: } else {
3063: my @responses = split(/:/,$value);
3064: my @items = ('description','inst_code','owner','type');
3065: for (my $i=0; $i<@responses; $i++) {
3066: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3067: }
3068: }
3069: }
3070: }
3071: }
3072: }
3073: return %returnhash;
3074: }
3075:
3076: # ---------------------------------------------------------- DC e-mail
3077:
3078: sub dcmailput {
3079: my ($domain,$msgid,$message,$server)=@_;
3080: my $status = &Apache::lonnet::critical(
3081: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3082: &escape($message),$server);
3083: return $status;
3084: }
3085:
3086: sub dcmaildump {
3087: my ($dom,$startdate,$enddate,$senders) = @_;
3088: my %returnhash=();
3089:
3090: if (defined(&domain($dom,'primary'))) {
3091: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3092: &escape($enddate).':';
3093: my @esc_senders=map { &escape($_)} @$senders;
3094: $cmd.=&escape(join('&',@esc_senders));
3095: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3096: my ($key,$value) = split(/\=/,$line,2);
3097: if (($key) && ($value)) {
3098: $returnhash{&unescape($key)} = &unescape($value);
3099: }
3100: }
3101: }
3102: return %returnhash;
3103: }
3104: # ---------------------------------------------------------- Domain roles
3105:
3106: sub get_domain_roles {
3107: my ($dom,$roles,$startdate,$enddate)=@_;
3108: if ((!defined($startdate)) || ($startdate eq '')) {
3109: $startdate = '.';
3110: }
3111: if ((!defined($enddate)) || ($enddate eq '')) {
3112: $enddate = '.';
3113: }
3114: my $rolelist;
3115: if (ref($roles) eq 'ARRAY') {
3116: $rolelist = join(':',@{$roles});
3117: }
3118: my %personnel = ();
3119:
3120: my %servers = &get_servers($dom,'library');
3121: foreach my $tryserver (keys(%servers)) {
3122: %{$personnel{$tryserver}}=();
3123: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3124: &escape($startdate).':'.
3125: &escape($enddate).':'.
3126: &escape($rolelist), $tryserver))) {
3127: my ($key,$value) = split(/\=/,$line,2);
3128: if (($key) && ($value)) {
3129: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3130: }
3131: }
3132: }
3133: return %personnel;
3134: }
3135:
3136: # ----------------------------------------------------------- Check out an item
3137:
3138: sub get_first_access {
3139: my ($type,$argsymb)=@_;
3140: my ($symb,$courseid,$udom,$uname)=&whichuser();
3141: if ($argsymb) { $symb=$argsymb; }
3142: my ($map,$id,$res)=&decode_symb($symb);
3143: if ($type eq 'course') {
3144: $res='course';
3145: } elsif ($type eq 'map') {
3146: $res=&symbread($map);
3147: } else {
3148: $res=$symb;
3149: }
3150: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3151: return $times{"$courseid\0$res"};
3152: }
3153:
3154: sub set_first_access {
3155: my ($type)=@_;
3156: my ($symb,$courseid,$udom,$uname)=&whichuser();
3157: my ($map,$id,$res)=&decode_symb($symb);
3158: if ($type eq 'course') {
3159: $res='course';
3160: } elsif ($type eq 'map') {
3161: $res=&symbread($map);
3162: } else {
3163: $res=$symb;
3164: }
3165: my $firstaccess=&get_first_access($type,$symb);
3166: if (!$firstaccess) {
3167: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3168: }
3169: return 'already_set';
3170: }
3171:
3172: sub checkout {
3173: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3174: my $now=time;
3175: my $lonhost=$perlvar{'lonHostID'};
3176: my $infostr=&escape(
3177: 'CHECKOUTTOKEN&'.
3178: $tuname.'&'.
3179: $tudom.'&'.
3180: $tcrsid.'&'.
3181: $symb.'&'.
3182: $now.'&'.$ENV{'REMOTE_ADDR'});
3183: my $token=&reply('tmpput:'.$infostr,$lonhost);
3184: if ($token=~/^error\:/) {
3185: &logthis("<font color=\"blue\">WARNING: ".
3186: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3187: "</font>");
3188: return '';
3189: }
3190:
3191: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3192: $token=~tr/a-z/A-Z/;
3193:
3194: my %infohash=('resource.0.outtoken' => $token,
3195: 'resource.0.checkouttime' => $now,
3196: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
3197:
3198: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3199: return '';
3200: } else {
3201: &logthis("<font color=\"blue\">WARNING: ".
3202: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3203: "</font>");
3204: }
3205:
3206: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3207: &escape('Checkout '.$infostr.' - '.
3208: $token)) ne 'ok') {
3209: return '';
3210: } else {
3211: &logthis("<font color=\"blue\">WARNING: ".
3212: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3213: "</font>");
3214: }
3215: return $token;
3216: }
3217:
3218: # ------------------------------------------------------------ Check in an item
3219:
3220: sub checkin {
3221: my $token=shift;
3222: my $now=time;
3223: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3224: $lonhost=~tr/A-Z/a-z/;
3225: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
3226: $dtoken=~s/\W/\_/g;
3227: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
3228: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3229:
3230: unless (($tuname) && ($tudom)) {
3231: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3232: return '';
3233: }
3234:
3235: unless (&allowed('mgr',$tcrsid)) {
3236: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
3237: $env{'user.name'}.' - '.$env{'user.domain'});
3238: return '';
3239: }
3240:
3241: my %infohash=('resource.0.intoken' => $token,
3242: 'resource.0.checkintime' => $now,
3243: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
3244:
3245: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3246: return '';
3247: }
3248:
3249: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3250: &escape('Checkin - '.$token)) ne 'ok') {
3251: return '';
3252: }
3253:
3254: return ($symb,$tuname,$tudom,$tcrsid);
3255: }
3256:
3257: # --------------------------------------------- Set Expire Date for Spreadsheet
3258:
3259: sub expirespread {
3260: my ($uname,$udom,$stype,$usymb)=@_;
3261: my $cid=$env{'request.course.id'};
3262: if ($cid) {
3263: my $now=time;
3264: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3265: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3266: $env{'course.'.$cid.'.num'}.
3267: ':nohist_expirationdates:'.
3268: &escape($key).'='.$now,
3269: $env{'course.'.$cid.'.home'})
3270: }
3271: return 'ok';
3272: }
3273:
3274: # ----------------------------------------------------- Devalidate Spreadsheets
3275:
3276: sub devalidate {
3277: my ($symb,$uname,$udom)=@_;
3278: my $cid=$env{'request.course.id'};
3279: if ($cid) {
3280: # delete the stored spreadsheets for
3281: # - the student level sheet of this user in course's homespace
3282: # - the assessment level sheet for this resource
3283: # for this user in user's homespace
3284: # - current conditional state info
3285: my $key=$uname.':'.$udom.':';
3286: my $status=
3287: &del('nohist_calculatedsheets',
3288: [$key.'studentcalc:'],
3289: $env{'course.'.$cid.'.domain'},
3290: $env{'course.'.$cid.'.num'})
3291: .' '.
3292: &del('nohist_calculatedsheets_'.$cid,
3293: [$key.'assesscalc:'.$symb],$udom,$uname);
3294: unless ($status eq 'ok ok') {
3295: &logthis('Could not devalidate spreadsheet '.
3296: $uname.' at '.$udom.' for '.
3297: $symb.': '.$status);
3298: }
3299: &delenv('user.state.'.$cid);
3300: }
3301: }
3302:
3303: sub get_scalar {
3304: my ($string,$end) = @_;
3305: my $value;
3306: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3307: $value = $1;
3308: } elsif ($$string =~ s/^([^&]*?)&//) {
3309: $value = $1;
3310: }
3311: return &unescape($value);
3312: }
3313:
3314: sub array2str {
3315: my (@array) = @_;
3316: my $result=&arrayref2str(\@array);
3317: $result=~s/^__ARRAY_REF__//;
3318: $result=~s/__END_ARRAY_REF__$//;
3319: return $result;
3320: }
3321:
3322: sub arrayref2str {
3323: my ($arrayref) = @_;
3324: my $result='__ARRAY_REF__';
3325: foreach my $elem (@$arrayref) {
3326: if(ref($elem) eq 'ARRAY') {
3327: $result.=&arrayref2str($elem).'&';
3328: } elsif(ref($elem) eq 'HASH') {
3329: $result.=&hashref2str($elem).'&';
3330: } elsif(ref($elem)) {
3331: #print("Got a ref of ".(ref($elem))." skipping.");
3332: } else {
3333: $result.=&escape($elem).'&';
3334: }
3335: }
3336: $result=~s/\&$//;
3337: $result .= '__END_ARRAY_REF__';
3338: return $result;
3339: }
3340:
3341: sub hash2str {
3342: my (%hash) = @_;
3343: my $result=&hashref2str(\%hash);
3344: $result=~s/^__HASH_REF__//;
3345: $result=~s/__END_HASH_REF__$//;
3346: return $result;
3347: }
3348:
3349: sub hashref2str {
3350: my ($hashref)=@_;
3351: my $result='__HASH_REF__';
3352: foreach my $key (sort(keys(%$hashref))) {
3353: if (ref($key) eq 'ARRAY') {
3354: $result.=&arrayref2str($key).'=';
3355: } elsif (ref($key) eq 'HASH') {
3356: $result.=&hashref2str($key).'=';
3357: } elsif (ref($key)) {
3358: $result.='=';
3359: #print("Got a ref of ".(ref($key))." skipping.");
3360: } else {
3361: if ($key) {$result.=&escape($key).'=';} else { last; }
3362: }
3363:
3364: if(ref($hashref->{$key}) eq 'ARRAY') {
3365: $result.=&arrayref2str($hashref->{$key}).'&';
3366: } elsif(ref($hashref->{$key}) eq 'HASH') {
3367: $result.=&hashref2str($hashref->{$key}).'&';
3368: } elsif(ref($hashref->{$key})) {
3369: $result.='&';
3370: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3371: } else {
3372: $result.=&escape($hashref->{$key}).'&';
3373: }
3374: }
3375: $result=~s/\&$//;
3376: $result .= '__END_HASH_REF__';
3377: return $result;
3378: }
3379:
3380: sub str2hash {
3381: my ($string)=@_;
3382: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3383: return %$hash;
3384: }
3385:
3386: sub str2hashref {
3387: my ($string) = @_;
3388:
3389: my %hash;
3390:
3391: if($string !~ /^__HASH_REF__/) {
3392: if (! ($string eq '' || !defined($string))) {
3393: $hash{'error'}='Not hash reference';
3394: }
3395: return (\%hash, $string);
3396: }
3397:
3398: $string =~ s/^__HASH_REF__//;
3399:
3400: while($string !~ /^__END_HASH_REF__/) {
3401: #key
3402: my $key='';
3403: if($string =~ /^__HASH_REF__/) {
3404: ($key, $string)=&str2hashref($string);
3405: if(defined($key->{'error'})) {
3406: $hash{'error'}='Bad data';
3407: return (\%hash, $string);
3408: }
3409: } elsif($string =~ /^__ARRAY_REF__/) {
3410: ($key, $string)=&str2arrayref($string);
3411: if($key->[0] eq 'Array reference error') {
3412: $hash{'error'}='Bad data';
3413: return (\%hash, $string);
3414: }
3415: } else {
3416: $string =~ s/^(.*?)=//;
3417: $key=&unescape($1);
3418: }
3419: $string =~ s/^=//;
3420:
3421: #value
3422: my $value='';
3423: if($string =~ /^__HASH_REF__/) {
3424: ($value, $string)=&str2hashref($string);
3425: if(defined($value->{'error'})) {
3426: $hash{'error'}='Bad data';
3427: return (\%hash, $string);
3428: }
3429: } elsif($string =~ /^__ARRAY_REF__/) {
3430: ($value, $string)=&str2arrayref($string);
3431: if($value->[0] eq 'Array reference error') {
3432: $hash{'error'}='Bad data';
3433: return (\%hash, $string);
3434: }
3435: } else {
3436: $value=&get_scalar(\$string,'__END_HASH_REF__');
3437: }
3438: $string =~ s/^&//;
3439:
3440: $hash{$key}=$value;
3441: }
3442:
3443: $string =~ s/^__END_HASH_REF__//;
3444:
3445: return (\%hash, $string);
3446: }
3447:
3448: sub str2array {
3449: my ($string)=@_;
3450: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3451: return @$array;
3452: }
3453:
3454: sub str2arrayref {
3455: my ($string) = @_;
3456: my @array;
3457:
3458: if($string !~ /^__ARRAY_REF__/) {
3459: if (! ($string eq '' || !defined($string))) {
3460: $array[0]='Array reference error';
3461: }
3462: return (\@array, $string);
3463: }
3464:
3465: $string =~ s/^__ARRAY_REF__//;
3466:
3467: while($string !~ /^__END_ARRAY_REF__/) {
3468: my $value='';
3469: if($string =~ /^__HASH_REF__/) {
3470: ($value, $string)=&str2hashref($string);
3471: if(defined($value->{'error'})) {
3472: $array[0] ='Array reference error';
3473: return (\@array, $string);
3474: }
3475: } elsif($string =~ /^__ARRAY_REF__/) {
3476: ($value, $string)=&str2arrayref($string);
3477: if($value->[0] eq 'Array reference error') {
3478: $array[0] ='Array reference error';
3479: return (\@array, $string);
3480: }
3481: } else {
3482: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3483: }
3484: $string =~ s/^&//;
3485:
3486: push(@array, $value);
3487: }
3488:
3489: $string =~ s/^__END_ARRAY_REF__//;
3490:
3491: return (\@array, $string);
3492: }
3493:
3494: # -------------------------------------------------------------------Temp Store
3495:
3496: sub tmpreset {
3497: my ($symb,$namespace,$domain,$stuname) = @_;
3498: if (!$symb) {
3499: $symb=&symbread();
3500: if (!$symb) { $symb= $env{'request.url'}; }
3501: }
3502: $symb=escape($symb);
3503:
3504: if (!$namespace) { $namespace=$env{'request.state'}; }
3505: $namespace=~s/\//\_/g;
3506: $namespace=~s/\W//g;
3507:
3508: if (!$domain) { $domain=$env{'user.domain'}; }
3509: if (!$stuname) { $stuname=$env{'user.name'}; }
3510: if ($domain eq 'public' && $stuname eq 'public') {
3511: $stuname=$ENV{'REMOTE_ADDR'};
3512: }
3513: my $path=$perlvar{'lonDaemons'}.'/tmp';
3514: my %hash;
3515: if (tie(%hash,'GDBM_File',
3516: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3517: &GDBM_WRCREAT(),0640)) {
3518: foreach my $key (keys(%hash)) {
3519: if ($key=~ /:$symb/) {
3520: delete($hash{$key});
3521: }
3522: }
3523: }
3524: }
3525:
3526: sub tmpstore {
3527: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3528:
3529: if (!$symb) {
3530: $symb=&symbread();
3531: if (!$symb) { $symb= $env{'request.url'}; }
3532: }
3533: $symb=escape($symb);
3534:
3535: if (!$namespace) {
3536: # I don't think we would ever want to store this for a course.
3537: # it seems this will only be used if we don't have a course.
3538: #$namespace=$env{'request.course.id'};
3539: #if (!$namespace) {
3540: $namespace=$env{'request.state'};
3541: #}
3542: }
3543: $namespace=~s/\//\_/g;
3544: $namespace=~s/\W//g;
3545: if (!$domain) { $domain=$env{'user.domain'}; }
3546: if (!$stuname) { $stuname=$env{'user.name'}; }
3547: if ($domain eq 'public' && $stuname eq 'public') {
3548: $stuname=$ENV{'REMOTE_ADDR'};
3549: }
3550: my $now=time;
3551: my %hash;
3552: my $path=$perlvar{'lonDaemons'}.'/tmp';
3553: if (tie(%hash,'GDBM_File',
3554: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3555: &GDBM_WRCREAT(),0640)) {
3556: $hash{"version:$symb"}++;
3557: my $version=$hash{"version:$symb"};
3558: my $allkeys='';
3559: foreach my $key (keys(%$storehash)) {
3560: $allkeys.=$key.':';
3561: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
3562: }
3563: $hash{"$version:$symb:timestamp"}=$now;
3564: $allkeys.='timestamp';
3565: $hash{"$version:keys:$symb"}=$allkeys;
3566: if (untie(%hash)) {
3567: return 'ok';
3568: } else {
3569: return "error:$!";
3570: }
3571: } else {
3572: return "error:$!";
3573: }
3574: }
3575:
3576: # -----------------------------------------------------------------Temp Restore
3577:
3578: sub tmprestore {
3579: my ($symb,$namespace,$domain,$stuname) = @_;
3580:
3581: if (!$symb) {
3582: $symb=&symbread();
3583: if (!$symb) { $symb= $env{'request.url'}; }
3584: }
3585: $symb=escape($symb);
3586:
3587: if (!$namespace) { $namespace=$env{'request.state'}; }
3588:
3589: if (!$domain) { $domain=$env{'user.domain'}; }
3590: if (!$stuname) { $stuname=$env{'user.name'}; }
3591: if ($domain eq 'public' && $stuname eq 'public') {
3592: $stuname=$ENV{'REMOTE_ADDR'};
3593: }
3594: my %returnhash;
3595: $namespace=~s/\//\_/g;
3596: $namespace=~s/\W//g;
3597: my %hash;
3598: my $path=$perlvar{'lonDaemons'}.'/tmp';
3599: if (tie(%hash,'GDBM_File',
3600: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3601: &GDBM_READER(),0640)) {
3602: my $version=$hash{"version:$symb"};
3603: $returnhash{'version'}=$version;
3604: my $scope;
3605: for ($scope=1;$scope<=$version;$scope++) {
3606: my $vkeys=$hash{"$scope:keys:$symb"};
3607: my @keys=split(/:/,$vkeys);
3608: my $key;
3609: $returnhash{"$scope:keys"}=$vkeys;
3610: foreach $key (@keys) {
3611: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3612: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3613: }
3614: }
3615: if (!(untie(%hash))) {
3616: return "error:$!";
3617: }
3618: } else {
3619: return "error:$!";
3620: }
3621: return %returnhash;
3622: }
3623:
3624: # ----------------------------------------------------------------------- Store
3625:
3626: sub store {
3627: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3628: my $home='';
3629:
3630: if ($stuname) { $home=&homeserver($stuname,$domain); }
3631:
3632: $symb=&symbclean($symb);
3633: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3634:
3635: if (!$domain) { $domain=$env{'user.domain'}; }
3636: if (!$stuname) { $stuname=$env{'user.name'}; }
3637:
3638: &devalidate($symb,$stuname,$domain);
3639:
3640: $symb=escape($symb);
3641: if (!$namespace) {
3642: unless ($namespace=$env{'request.course.id'}) {
3643: return '';
3644: }
3645: }
3646: if (!$home) { $home=$env{'user.home'}; }
3647:
3648: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3649: $$storehash{'host'}=$perlvar{'lonHostID'};
3650:
3651: my $namevalue='';
3652: foreach my $key (keys(%$storehash)) {
3653: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3654: }
3655: $namevalue=~s/\&$//;
3656: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
3657: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3658: }
3659:
3660: # -------------------------------------------------------------- Critical Store
3661:
3662: sub cstore {
3663: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3664: my $home='';
3665:
3666: if ($stuname) { $home=&homeserver($stuname,$domain); }
3667:
3668: $symb=&symbclean($symb);
3669: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3670:
3671: if (!$domain) { $domain=$env{'user.domain'}; }
3672: if (!$stuname) { $stuname=$env{'user.name'}; }
3673:
3674: &devalidate($symb,$stuname,$domain);
3675:
3676: $symb=escape($symb);
3677: if (!$namespace) {
3678: unless ($namespace=$env{'request.course.id'}) {
3679: return '';
3680: }
3681: }
3682: if (!$home) { $home=$env{'user.home'}; }
3683:
3684: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3685: $$storehash{'host'}=$perlvar{'lonHostID'};
3686:
3687: my $namevalue='';
3688: foreach my $key (keys(%$storehash)) {
3689: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3690: }
3691: $namevalue=~s/\&$//;
3692: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
3693: return critical
3694: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3695: }
3696:
3697: # --------------------------------------------------------------------- Restore
3698:
3699: sub restore {
3700: my ($symb,$namespace,$domain,$stuname) = @_;
3701: my $home='';
3702:
3703: if ($stuname) { $home=&homeserver($stuname,$domain); }
3704:
3705: if (!$symb) {
3706: unless ($symb=escape(&symbread())) { return ''; }
3707: } else {
3708: $symb=&escape(&symbclean($symb));
3709: }
3710: if (!$namespace) {
3711: unless ($namespace=$env{'request.course.id'}) {
3712: return '';
3713: }
3714: }
3715: if (!$domain) { $domain=$env{'user.domain'}; }
3716: if (!$stuname) { $stuname=$env{'user.name'}; }
3717: if (!$home) { $home=$env{'user.home'}; }
3718: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3719:
3720: my %returnhash=();
3721: foreach my $line (split(/\&/,$answer)) {
3722: my ($name,$value)=split(/\=/,$line);
3723: $returnhash{&unescape($name)}=&thaw_unescape($value);
3724: }
3725: my $version;
3726: for ($version=1;$version<=$returnhash{'version'};$version++) {
3727: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3728: $returnhash{$item}=$returnhash{$version.':'.$item};
3729: }
3730: }
3731: return %returnhash;
3732: }
3733:
3734: # ---------------------------------------------------------- Course Description
3735:
3736: sub coursedescription {
3737: my ($courseid,$args)=@_;
3738: $courseid=~s/^\///;
3739: $courseid=~s/\_/\//g;
3740: my ($cdomain,$cnum)=split(/\//,$courseid);
3741: my $chome=&homeserver($cnum,$cdomain);
3742: my $normalid=$cdomain.'_'.$cnum;
3743: # need to always cache even if we get errors otherwise we keep
3744: # trying and trying and trying to get the course description.
3745: my %envhash=();
3746: my %returnhash=();
3747:
3748: my $expiretime=600;
3749: if ($env{'request.course.id'} eq $normalid) {
3750: $expiretime=120;
3751: }
3752:
3753: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3754: if (!$args->{'freshen_cache'}
3755: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3756: foreach my $key (keys(%env)) {
3757: next if ($key !~ /^\Q$prefix\E(.*)/);
3758: my ($setting) = $1;
3759: $returnhash{$setting} = $env{$key};
3760: }
3761: return %returnhash;
3762: }
3763:
3764: # get the data agin
3765: if (!$args->{'one_time'}) {
3766: $envhash{'course.'.$normalid.'.last_cache'}=time;
3767: }
3768:
3769: if ($chome ne 'no_host') {
3770: %returnhash=&dump('environment',$cdomain,$cnum);
3771: if (!exists($returnhash{'con_lost'})) {
3772: $returnhash{'home'}= $chome;
3773: $returnhash{'domain'} = $cdomain;
3774: $returnhash{'num'} = $cnum;
3775: if (!defined($returnhash{'type'})) {
3776: $returnhash{'type'} = 'Course';
3777: }
3778: while (my ($name,$value) = each %returnhash) {
3779: $envhash{'course.'.$normalid.'.'.$name}=$value;
3780: }
3781: $returnhash{'url'}=&clutter($returnhash{'url'});
3782: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
3783: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
3784: $envhash{'course.'.$normalid.'.home'}=$chome;
3785: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3786: $envhash{'course.'.$normalid.'.num'}=$cnum;
3787: }
3788: }
3789: if (!$args->{'one_time'}) {
3790: &appenv(\%envhash);
3791: }
3792: return %returnhash;
3793: }
3794:
3795: # -------------------------------------------------See if a user is privileged
3796:
3797: sub privileged {
3798: my ($username,$domain)=@_;
3799: my $rolesdump=&reply("dump:$domain:$username:roles",
3800: &homeserver($username,$domain));
3801: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3802: my $now=time;
3803: if ($rolesdump ne '') {
3804: foreach my $entry (split(/&/,$rolesdump)) {
3805: if ($entry!~/^rolesdef_/) {
3806: my ($area,$role)=split(/=/,$entry);
3807: $area=~s/\_\w\w$//;
3808: my ($trole,$tend,$tstart)=split(/_/,$role);
3809: if (($trole eq 'dc') || ($trole eq 'su')) {
3810: my $active=1;
3811: if ($tend) {
3812: if ($tend<$now) { $active=0; }
3813: }
3814: if ($tstart) {
3815: if ($tstart>$now) { $active=0; }
3816: }
3817: if ($active) { return 1; }
3818: }
3819: }
3820: }
3821: }
3822: return 0;
3823: }
3824:
3825: # -------------------------------------------------------- Get user privileges
3826:
3827: sub rolesinit {
3828: my ($domain,$username,$authhost)=@_;
3829: my %userroles;
3830: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
3831: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
3832: my %allroles=();
3833: my %allgroups=();
3834: my $now=time;
3835: %userroles = ('user.login.time' => $now);
3836: my $group_privs;
3837:
3838: if ($rolesdump ne '') {
3839: foreach my $entry (split(/&/,$rolesdump)) {
3840: if ($entry!~/^rolesdef_/) {
3841: my ($area,$role)=split(/=/,$entry);
3842: $area=~s/\_\w\w$//;
3843: my ($trole,$tend,$tstart,$group_privs);
3844: if ($role=~/^cr/) {
3845: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3846: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
3847: ($tend,$tstart)=split('_',$trest);
3848: } else {
3849: $trole=$role;
3850: }
3851: } elsif ($role =~ m|^gr/|) {
3852: ($trole,$tend,$tstart) = split(/_/,$role);
3853: ($trole,$group_privs) = split(/\//,$trole);
3854: $group_privs = &unescape($group_privs);
3855: } else {
3856: ($trole,$tend,$tstart)=split(/_/,$role);
3857: }
3858: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3859: $username);
3860: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
3861: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3862: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
3863: if (($area ne '') && ($trole ne '')) {
3864: my $spec=$trole.'.'.$area;
3865: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3866: if ($trole =~ /^cr\//) {
3867: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
3868: } elsif ($trole eq 'gr') {
3869: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
3870: } else {
3871: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
3872: }
3873: }
3874: }
3875: }
3876: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3877: $userroles{'user.adv'} = $adv;
3878: $userroles{'user.author'} = $author;
3879: $env{'user.adv'}=$adv;
3880: }
3881: return \%userroles;
3882: }
3883:
3884: sub set_arearole {
3885: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3886: # log the associated role with the area
3887: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
3888: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
3889: }
3890:
3891: sub custom_roleprivs {
3892: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3893: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3894: my $homsvr=homeserver($rauthor,$rdomain);
3895: if (&hostname($homsvr) ne '') {
3896: my ($rdummy,$roledef)=
3897: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3898: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3899: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3900: if (defined($syspriv)) {
3901: $$allroles{'cm./'}.=':'.$syspriv;
3902: $$allroles{$spec.'./'}.=':'.$syspriv;
3903: }
3904: if ($tdomain ne '') {
3905: if (defined($dompriv)) {
3906: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3907: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3908: }
3909: if (($trest ne '') && (defined($coursepriv))) {
3910: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3911: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3912: }
3913: }
3914: }
3915: }
3916: }
3917:
3918: sub group_roleprivs {
3919: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3920: my $access = 1;
3921: my $now = time;
3922: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3923: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3924: if ($access) {
3925: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3926: $$allgroups{$course}{$group} .=':'.$group_privs;
3927: }
3928: }
3929:
3930: sub standard_roleprivs {
3931: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3932: if (defined($pr{$trole.':s'})) {
3933: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3934: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3935: }
3936: if ($tdomain ne '') {
3937: if (defined($pr{$trole.':d'})) {
3938: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3939: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3940: }
3941: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3942: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3943: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3944: }
3945: }
3946: }
3947:
3948: sub set_userprivs {
3949: my ($userroles,$allroles,$allgroups) = @_;
3950: my $author=0;
3951: my $adv=0;
3952: my %grouproles = ();
3953: if (keys(%{$allgroups}) > 0) {
3954: foreach my $role (keys(%{$allroles})) {
3955: my ($trole,$area,$sec,$extendedarea);
3956: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
3957: $trole = $1;
3958: $area = $2;
3959: $sec = $3;
3960: $extendedarea = $area.$sec;
3961: if (exists($$allgroups{$area})) {
3962: foreach my $group (keys(%{$$allgroups{$area}})) {
3963: my $spec = $trole.'.'.$extendedarea;
3964: $grouproles{$spec.'.'.$area.'/'.$group} =
3965: $$allgroups{$area}{$group};
3966: }
3967: }
3968: }
3969: }
3970: }
3971: foreach my $group (keys(%grouproles)) {
3972: $$allroles{$group} = $grouproles{$group};
3973: }
3974: foreach my $role (keys(%{$allroles})) {
3975: my %thesepriv;
3976: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
3977: foreach my $item (split(/:/,$$allroles{$role})) {
3978: if ($item ne '') {
3979: my ($privilege,$restrictions)=split(/&/,$item);
3980: if ($restrictions eq '') {
3981: $thesepriv{$privilege}='F';
3982: } elsif ($thesepriv{$privilege} ne 'F') {
3983: $thesepriv{$privilege}.=$restrictions;
3984: }
3985: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3986: }
3987: }
3988: my $thesestr='';
3989: foreach my $priv (keys(%thesepriv)) {
3990: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3991: }
3992: $userroles->{'user.priv.'.$role} = $thesestr;
3993: }
3994: return ($author,$adv);
3995: }
3996:
3997: sub role_status {
3998: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
3999: my @pwhere = ();
4000: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4001: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4002: unless (!defined($$role) || $$role eq '') {
4003: $$where=join('.',@pwhere);
4004: $$trolecode=$$role.'.'.$$where;
4005: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4006: $$tstatus='is';
4007: if ($$tstart && $$tstart>$then) {
4008: $$tstatus='future';
4009: if ($$tstart && $$tstart>$refresh) {
4010: if ($$tstart<$now) {
4011: if (($$where ne '') && ($$role ne '')) {
4012: my (%allroles,%allgroups,$group_privs);
4013: my %userroles = (
4014: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4015: );
4016: my $spec=$$role.'.'.$$where;
4017: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4018: if ($$role eq 'gr') {
4019: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4020: $env{'user.name'})=@_;
4021: my ($trole) = split('_',$role,1);
4022: (undef,my $group_privs) = split(/\//,$trole);
4023: $group_privs = &unescape($group_privs);
4024: }
4025: if ($$role =~ /^cr\//) {
4026: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4027: } elsif ($$role eq 'gr') {
4028: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4029: $env{'user.name'});
4030: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
4031: (undef,my $group_privs) = split(/\//,$trole);
4032: $group_privs = &unescape($group_privs);
4033: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4034: } else {
4035: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4036: }
4037: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
4038: &appenv(\%userroles,[$$role,'cm']);
4039: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4040: $$tstatus = 'is';
4041: }
4042: }
4043: }
4044: }
4045: if ($$tend) {
4046: if ($$tend<$then) {
4047: $$tstatus='expired';
4048: } elsif ($$tend<$now) {
4049: $$tstatus='will_not';
4050: }
4051: }
4052: }
4053: }
4054: }
4055:
4056: sub check_adhoc_privs {
4057: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
4058: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4059: if ($env{$cckey}) {
4060: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4061: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4062: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4063: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4064: }
4065: } else {
4066: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4067: }
4068: }
4069:
4070: sub set_adhoc_privileges {
4071: # role can be cc or ca
4072: my ($dcdom,$pickedcourse,$role) = @_;
4073: my $area = '/'.$dcdom.'/'.$pickedcourse;
4074: my $spec = $role.'.'.$area;
4075: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4076: $env{'user.name'});
4077: my %ccrole = ();
4078: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4079: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4080: &appenv(\%userroles,[$role,'cm']);
4081: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4082: &appenv( {'request.role' => $spec,
4083: 'request.role.domain' => $dcdom,
4084: 'request.course.sec' => ''
4085: }
4086: );
4087: my $tadv=0;
4088: if (&allowed('adv') eq 'F') { $tadv=1; }
4089: &appenv({'request.role.adv' => $tadv});
4090: }
4091:
4092: # --------------------------------------------------------------- get interface
4093:
4094: sub get {
4095: my ($namespace,$storearr,$udomain,$uname)=@_;
4096: my $items='';
4097: foreach my $item (@$storearr) {
4098: $items.=&escape($item).'&';
4099: }
4100: $items=~s/\&$//;
4101: if (!$udomain) { $udomain=$env{'user.domain'}; }
4102: if (!$uname) { $uname=$env{'user.name'}; }
4103: my $uhome=&homeserver($uname,$udomain);
4104:
4105: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4106: my @pairs=split(/\&/,$rep);
4107: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4108: return @pairs;
4109: }
4110: my %returnhash=();
4111: my $i=0;
4112: foreach my $item (@$storearr) {
4113: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4114: $i++;
4115: }
4116: return %returnhash;
4117: }
4118:
4119: # --------------------------------------------------------------- del interface
4120:
4121: sub del {
4122: my ($namespace,$storearr,$udomain,$uname)=@_;
4123: my $items='';
4124: foreach my $item (@$storearr) {
4125: $items.=&escape($item).'&';
4126: }
4127:
4128: $items=~s/\&$//;
4129: if (!$udomain) { $udomain=$env{'user.domain'}; }
4130: if (!$uname) { $uname=$env{'user.name'}; }
4131: my $uhome=&homeserver($uname,$udomain);
4132: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4133: }
4134:
4135: # -------------------------------------------------------------- dump interface
4136:
4137: sub dump {
4138: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4139: if (!$udomain) { $udomain=$env{'user.domain'}; }
4140: if (!$uname) { $uname=$env{'user.name'}; }
4141: my $uhome=&homeserver($uname,$udomain);
4142: if ($regexp) {
4143: $regexp=&escape($regexp);
4144: } else {
4145: $regexp='.';
4146: }
4147: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4148: my @pairs=split(/\&/,$rep);
4149: my %returnhash=();
4150: foreach my $item (@pairs) {
4151: my ($key,$value)=split(/=/,$item,2);
4152: $key = &unescape($key);
4153: next if ($key =~ /^error: 2 /);
4154: $returnhash{$key}=&thaw_unescape($value);
4155: }
4156: return %returnhash;
4157: }
4158:
4159: # --------------------------------------------------------- dumpstore interface
4160:
4161: sub dumpstore {
4162: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4163: if (!$udomain) { $udomain=$env{'user.domain'}; }
4164: if (!$uname) { $uname=$env{'user.name'}; }
4165: my $uhome=&homeserver($uname,$udomain);
4166: if ($regexp) {
4167: $regexp=&escape($regexp);
4168: } else {
4169: $regexp='.';
4170: }
4171: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4172: my @pairs=split(/\&/,$rep);
4173: my %returnhash=();
4174: foreach my $item (@pairs) {
4175: my ($key,$value)=split(/=/,$item,2);
4176: next if ($key =~ /^error: 2 /);
4177: $returnhash{$key}=&thaw_unescape($value);
4178: }
4179: return %returnhash;
4180: }
4181:
4182: # -------------------------------------------------------------- keys interface
4183:
4184: sub getkeys {
4185: my ($namespace,$udomain,$uname)=@_;
4186: if (!$udomain) { $udomain=$env{'user.domain'}; }
4187: if (!$uname) { $uname=$env{'user.name'}; }
4188: my $uhome=&homeserver($uname,$udomain);
4189: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4190: my @keyarray=();
4191: foreach my $key (split(/\&/,$rep)) {
4192: next if ($key =~ /^error: 2 /);
4193: push(@keyarray,&unescape($key));
4194: }
4195: return @keyarray;
4196: }
4197:
4198: # --------------------------------------------------------------- currentdump
4199: sub currentdump {
4200: my ($courseid,$sdom,$sname)=@_;
4201: $courseid = $env{'request.course.id'} if (! defined($courseid));
4202: $sdom = $env{'user.domain'} if (! defined($sdom));
4203: $sname = $env{'user.name'} if (! defined($sname));
4204: my $uhome = &homeserver($sname,$sdom);
4205: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4206: return if ($rep =~ /^(error:|no_such_host)/);
4207: #
4208: my %returnhash=();
4209: #
4210: if ($rep eq "unknown_cmd") {
4211: # an old lond will not know currentdump
4212: # Do a dump and make it look like a currentdump
4213: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4214: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4215: my %hash = @tmp;
4216: @tmp=();
4217: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4218: } else {
4219: my @pairs=split(/\&/,$rep);
4220: foreach my $pair (@pairs) {
4221: my ($key,$value)=split(/=/,$pair,2);
4222: my ($symb,$param) = split(/:/,$key);
4223: $returnhash{&unescape($symb)}->{&unescape($param)} =
4224: &thaw_unescape($value);
4225: }
4226: }
4227: return %returnhash;
4228: }
4229:
4230: sub convert_dump_to_currentdump{
4231: my %hash = %{shift()};
4232: my %returnhash;
4233: # Code ripped from lond, essentially. The only difference
4234: # here is the unescaping done by lonnet::dump(). Conceivably
4235: # we might run in to problems with parameter names =~ /^v\./
4236: while (my ($key,$value) = each(%hash)) {
4237: my ($v,$symb,$param) = split(/:/,$key);
4238: $symb = &unescape($symb);
4239: $param = &unescape($param);
4240: next if ($v eq 'version' || $symb eq 'keys');
4241: next if (exists($returnhash{$symb}) &&
4242: exists($returnhash{$symb}->{$param}) &&
4243: $returnhash{$symb}->{'v.'.$param} > $v);
4244: $returnhash{$symb}->{$param}=$value;
4245: $returnhash{$symb}->{'v.'.$param}=$v;
4246: }
4247: #
4248: # Remove all of the keys in the hashes which keep track of
4249: # the version of the parameter.
4250: while (my ($symb,$param_hash) = each(%returnhash)) {
4251: # use a foreach because we are going to delete from the hash.
4252: foreach my $key (keys(%$param_hash)) {
4253: delete($param_hash->{$key}) if ($key =~ /^v\./);
4254: }
4255: }
4256: return \%returnhash;
4257: }
4258:
4259: # ------------------------------------------------------ critical inc interface
4260:
4261: sub cinc {
4262: return &inc(@_,'critical');
4263: }
4264:
4265: # --------------------------------------------------------------- inc interface
4266:
4267: sub inc {
4268: my ($namespace,$store,$udomain,$uname,$critical) = @_;
4269: if (!$udomain) { $udomain=$env{'user.domain'}; }
4270: if (!$uname) { $uname=$env{'user.name'}; }
4271: my $uhome=&homeserver($uname,$udomain);
4272: my $items='';
4273: if (! ref($store)) {
4274: # got a single value, so use that instead
4275: $items = &escape($store).'=&';
4276: } elsif (ref($store) eq 'SCALAR') {
4277: $items = &escape($$store).'=&';
4278: } elsif (ref($store) eq 'ARRAY') {
4279: $items = join('=&',map {&escape($_);} @{$store});
4280: } elsif (ref($store) eq 'HASH') {
4281: while (my($key,$value) = each(%{$store})) {
4282: $items.= &escape($key).'='.&escape($value).'&';
4283: }
4284: }
4285: $items=~s/\&$//;
4286: if ($critical) {
4287: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4288: } else {
4289: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4290: }
4291: }
4292:
4293: # --------------------------------------------------------------- put interface
4294:
4295: sub put {
4296: my ($namespace,$storehash,$udomain,$uname)=@_;
4297: if (!$udomain) { $udomain=$env{'user.domain'}; }
4298: if (!$uname) { $uname=$env{'user.name'}; }
4299: my $uhome=&homeserver($uname,$udomain);
4300: my $items='';
4301: foreach my $item (keys(%$storehash)) {
4302: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4303: }
4304: $items=~s/\&$//;
4305: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4306: }
4307:
4308: # ------------------------------------------------------------ newput interface
4309:
4310: sub newput {
4311: my ($namespace,$storehash,$udomain,$uname)=@_;
4312: if (!$udomain) { $udomain=$env{'user.domain'}; }
4313: if (!$uname) { $uname=$env{'user.name'}; }
4314: my $uhome=&homeserver($uname,$udomain);
4315: my $items='';
4316: foreach my $key (keys(%$storehash)) {
4317: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4318: }
4319: $items=~s/\&$//;
4320: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4321: }
4322:
4323: # --------------------------------------------------------- putstore interface
4324:
4325: sub putstore {
4326: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4327: if (!$udomain) { $udomain=$env{'user.domain'}; }
4328: if (!$uname) { $uname=$env{'user.name'}; }
4329: my $uhome=&homeserver($uname,$udomain);
4330: my $items='';
4331: foreach my $key (keys(%$storehash)) {
4332: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
4333: }
4334: $items=~s/\&$//;
4335: my $esc_symb=&escape($symb);
4336: my $esc_v=&escape($version);
4337: my $reply =
4338: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
4339: $uhome);
4340: if ($reply eq 'unknown_cmd') {
4341: # gfall back to way things use to be done
4342: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4343: $uname);
4344: }
4345: return $reply;
4346: }
4347:
4348: sub old_putstore {
4349: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4350: if (!$udomain) { $udomain=$env{'user.domain'}; }
4351: if (!$uname) { $uname=$env{'user.name'}; }
4352: my $uhome=&homeserver($uname,$udomain);
4353: my %newstorehash;
4354: foreach my $item (keys(%$storehash)) {
4355: my $key = $version.':'.&escape($symb).':'.$item;
4356: $newstorehash{$key} = $storehash->{$item};
4357: }
4358: my $items='';
4359: my %allitems = ();
4360: foreach my $item (keys(%newstorehash)) {
4361: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
4362: my $key = $1.':keys:'.$2;
4363: $allitems{$key} .= $3.':';
4364: }
4365: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
4366: }
4367: foreach my $item (keys(%allitems)) {
4368: $allitems{$item} =~ s/\:$//;
4369: $items.= $item.'='.$allitems{$item}.'&';
4370: }
4371: $items=~s/\&$//;
4372: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4373: }
4374:
4375: # ------------------------------------------------------ critical put interface
4376:
4377: sub cput {
4378: my ($namespace,$storehash,$udomain,$uname)=@_;
4379: if (!$udomain) { $udomain=$env{'user.domain'}; }
4380: if (!$uname) { $uname=$env{'user.name'}; }
4381: my $uhome=&homeserver($uname,$udomain);
4382: my $items='';
4383: foreach my $item (keys(%$storehash)) {
4384: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4385: }
4386: $items=~s/\&$//;
4387: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
4388: }
4389:
4390: # -------------------------------------------------------------- eget interface
4391:
4392: sub eget {
4393: my ($namespace,$storearr,$udomain,$uname)=@_;
4394: my $items='';
4395: foreach my $item (@$storearr) {
4396: $items.=&escape($item).'&';
4397: }
4398: $items=~s/\&$//;
4399: if (!$udomain) { $udomain=$env{'user.domain'}; }
4400: if (!$uname) { $uname=$env{'user.name'}; }
4401: my $uhome=&homeserver($uname,$udomain);
4402: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
4403: my @pairs=split(/\&/,$rep);
4404: my %returnhash=();
4405: my $i=0;
4406: foreach my $item (@$storearr) {
4407: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4408: $i++;
4409: }
4410: return %returnhash;
4411: }
4412:
4413: # ------------------------------------------------------------ tmpput interface
4414: sub tmpput {
4415: my ($storehash,$server,$context)=@_;
4416: my $items='';
4417: foreach my $item (keys(%$storehash)) {
4418: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4419: }
4420: $items=~s/\&$//;
4421: if (defined($context)) {
4422: $items .= ':'.&escape($context);
4423: }
4424: return &reply("tmpput:$items",$server);
4425: }
4426:
4427: # ------------------------------------------------------------ tmpget interface
4428: sub tmpget {
4429: my ($token,$server)=@_;
4430: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4431: my $rep=&reply("tmpget:$token",$server);
4432: my %returnhash;
4433: foreach my $item (split(/\&/,$rep)) {
4434: my ($key,$value)=split(/=/,$item);
4435: next if ($key =~ /^error: 2 /);
4436: $returnhash{&unescape($key)}=&thaw_unescape($value);
4437: }
4438: return %returnhash;
4439: }
4440:
4441: # ------------------------------------------------------------ tmpget interface
4442: sub tmpdel {
4443: my ($token,$server)=@_;
4444: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4445: return &reply("tmpdel:$token",$server);
4446: }
4447:
4448: # -------------------------------------------------- portfolio access checking
4449:
4450: sub portfolio_access {
4451: my ($requrl) = @_;
4452: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4453: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
4454: if ($result) {
4455: my %setters;
4456: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4457: my ($startblock,$endblock) =
4458: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4459: if ($startblock && $endblock) {
4460: return 'B';
4461: }
4462: } else {
4463: my ($startblock,$endblock) =
4464: &Apache::loncommon::blockcheck(\%setters,'port');
4465: if ($startblock && $endblock) {
4466: return 'B';
4467: }
4468: }
4469: }
4470: if ($result eq 'ok') {
4471: return 'F';
4472: } elsif ($result =~ /^[^:]+:guest_/) {
4473: return 'A';
4474: }
4475: return '';
4476: }
4477:
4478: sub get_portfolio_access {
4479: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4480:
4481: if (!ref($access_hash)) {
4482: my $current_perms = &get_portfile_permissions($udom,$unum);
4483: my %access_controls = &get_access_controls($current_perms,$group,
4484: $file_name);
4485: $access_hash = $access_controls{$file_name};
4486: }
4487:
4488: my ($public,$guest,@domains,@users,@courses,@groups);
4489: my $now = time;
4490: if (ref($access_hash) eq 'HASH') {
4491: foreach my $key (keys(%{$access_hash})) {
4492: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4493: if ($start > $now) {
4494: next;
4495: }
4496: if ($end && $end<$now) {
4497: next;
4498: }
4499: if ($scope eq 'public') {
4500: $public = $key;
4501: last;
4502: } elsif ($scope eq 'guest') {
4503: $guest = $key;
4504: } elsif ($scope eq 'domains') {
4505: push(@domains,$key);
4506: } elsif ($scope eq 'users') {
4507: push(@users,$key);
4508: } elsif ($scope eq 'course') {
4509: push(@courses,$key);
4510: } elsif ($scope eq 'group') {
4511: push(@groups,$key);
4512: }
4513: }
4514: if ($public) {
4515: return 'ok';
4516: }
4517: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4518: if ($guest) {
4519: return $guest;
4520: }
4521: } else {
4522: if (@domains > 0) {
4523: foreach my $domkey (@domains) {
4524: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4525: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4526: return 'ok';
4527: }
4528: }
4529: }
4530: }
4531: if (@users > 0) {
4532: foreach my $userkey (@users) {
4533: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4534: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4535: if (ref($item) eq 'HASH') {
4536: if (($item->{'uname'} eq $env{'user.name'}) &&
4537: ($item->{'udom'} eq $env{'user.domain'})) {
4538: return 'ok';
4539: }
4540: }
4541: }
4542: }
4543: }
4544: }
4545: my %roleshash;
4546: my @courses_and_groups = @courses;
4547: push(@courses_and_groups,@groups);
4548: if (@courses_and_groups > 0) {
4549: my (%allgroups,%allroles);
4550: my ($start,$end,$role,$sec,$group);
4551: foreach my $envkey (%env) {
4552: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
4553: my $cid = $2.'_'.$3;
4554: if ($1 eq 'gr') {
4555: $group = $4;
4556: $allgroups{$cid}{$group} = $env{$envkey};
4557: } else {
4558: if ($4 eq '') {
4559: $sec = 'none';
4560: } else {
4561: $sec = $4;
4562: }
4563: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4564: }
4565: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
4566: my $cid = $2.'_'.$3;
4567: if ($4 eq '') {
4568: $sec = 'none';
4569: } else {
4570: $sec = $4;
4571: }
4572: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4573: }
4574: }
4575: if (keys(%allroles) == 0) {
4576: return;
4577: }
4578: foreach my $key (@courses_and_groups) {
4579: my %content = %{$$access_hash{$key}};
4580: my $cnum = $content{'number'};
4581: my $cdom = $content{'domain'};
4582: my $cid = $cdom.'_'.$cnum;
4583: if (!exists($allroles{$cid})) {
4584: next;
4585: }
4586: foreach my $role_id (keys(%{$content{'roles'}})) {
4587: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4588: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4589: my @status = @{$content{'roles'}{$role_id}{'access'}};
4590: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4591: foreach my $role (keys(%{$allroles{$cid}})) {
4592: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4593: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4594: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4595: if (grep/^all$/,@sections) {
4596: return 'ok';
4597: } else {
4598: if (grep/^$sec$/,@sections) {
4599: return 'ok';
4600: }
4601: }
4602: }
4603: }
4604: if (keys(%{$allgroups{$cid}}) == 0) {
4605: if (grep/^none$/,@groups) {
4606: return 'ok';
4607: }
4608: } else {
4609: if (grep/^all$/,@groups) {
4610: return 'ok';
4611: }
4612: foreach my $group (keys(%{$allgroups{$cid}})) {
4613: if (grep/^$group$/,@groups) {
4614: return 'ok';
4615: }
4616: }
4617: }
4618: }
4619: }
4620: }
4621: }
4622: }
4623: if ($guest) {
4624: return $guest;
4625: }
4626: }
4627: }
4628: return;
4629: }
4630:
4631: sub course_group_datechecker {
4632: my ($dates,$now,$status) = @_;
4633: my ($start,$end) = split(/\./,$dates);
4634: if (!$start && !$end) {
4635: return 'ok';
4636: }
4637: if (grep/^active$/,@{$status}) {
4638: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4639: return 'ok';
4640: }
4641: }
4642: if (grep/^previous$/,@{$status}) {
4643: if ($end > $now ) {
4644: return 'ok';
4645: }
4646: }
4647: if (grep/^future$/,@{$status}) {
4648: if ($start > $now) {
4649: return 'ok';
4650: }
4651: }
4652: return;
4653: }
4654:
4655: sub parse_portfolio_url {
4656: my ($url) = @_;
4657:
4658: my ($type,$udom,$unum,$group,$file_name);
4659:
4660: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
4661: $type = 1;
4662: $udom = $1;
4663: $unum = $2;
4664: $file_name = $3;
4665: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
4666: $type = 2;
4667: $udom = $1;
4668: $unum = $2;
4669: $group = $3;
4670: $file_name = $3.'/'.$4;
4671: }
4672: if (wantarray) {
4673: return ($type,$udom,$unum,$file_name,$group);
4674: }
4675: return $type;
4676: }
4677:
4678: sub is_portfolio_url {
4679: my ($url) = @_;
4680: return scalar(&parse_portfolio_url($url));
4681: }
4682:
4683: sub is_portfolio_file {
4684: my ($file) = @_;
4685: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
4686: return 1;
4687: }
4688: return;
4689: }
4690:
4691: sub usertools_access {
4692: my ($uname,$udom,$tool,$action,$context) = @_;
4693: my ($access,%tools);
4694: if ($context eq '') {
4695: $context = 'tools';
4696: }
4697: if ($context eq 'requestcourses') {
4698: %tools = (
4699: official => 1,
4700: unofficial => 1,
4701: community => 1,
4702: );
4703: } else {
4704: %tools = (
4705: aboutme => 1,
4706: blog => 1,
4707: portfolio => 1,
4708: );
4709: }
4710: return if (!defined($tools{$tool}));
4711:
4712: if ((!defined($udom)) || (!defined($uname))) {
4713: $udom = $env{'user.domain'};
4714: $uname = $env{'user.name'};
4715: }
4716:
4717: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4718: if ($action ne 'reload') {
4719: if ($context eq 'requestcourses') {
4720: return $env{'environment.canrequest.'.$tool};
4721: } else {
4722: return $env{'environment.availabletools.'.$tool};
4723: }
4724: }
4725: }
4726:
4727: my ($toolstatus,$inststatus);
4728:
4729: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4730: ($action ne 'reload')) {
4731: $toolstatus = $env{'environment.'.$context.'.'.$tool};
4732: $inststatus = $env{'environment.inststatus'};
4733: } else {
4734: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
4735: $toolstatus = $userenv{$context.'.'.$tool};
4736: $inststatus = $userenv{'inststatus'};
4737: }
4738:
4739: if ($toolstatus ne '') {
4740: if ($toolstatus) {
4741: $access = 1;
4742: } else {
4743: $access = 0;
4744: }
4745: return $access;
4746: }
4747:
4748: my $is_adv = &is_advanced_user($udom,$uname);
4749: my %domdef = &get_domain_defaults($udom);
4750: if (ref($domdef{$tool}) eq 'HASH') {
4751: if ($is_adv) {
4752: if ($domdef{$tool}{'_LC_adv'} ne '') {
4753: if ($domdef{$tool}{'_LC_adv'}) {
4754: $access = 1;
4755: } else {
4756: $access = 0;
4757: }
4758: return $access;
4759: }
4760: }
4761: if ($inststatus ne '') {
4762: my ($hasaccess,$hasnoaccess);
4763: foreach my $affiliation (split(/:/,$inststatus)) {
4764: if ($domdef{$tool}{$affiliation} ne '') {
4765: if ($domdef{$tool}{$affiliation}) {
4766: $hasaccess = 1;
4767: } else {
4768: $hasnoaccess = 1;
4769: }
4770: }
4771: }
4772: if ($hasaccess || $hasnoaccess) {
4773: if ($hasaccess) {
4774: $access = 1;
4775: } elsif ($hasnoaccess) {
4776: $access = 0;
4777: }
4778: return $access;
4779: }
4780: } else {
4781: if ($domdef{$tool}{'default'} ne '') {
4782: if ($domdef{$tool}{'default'}) {
4783: $access = 1;
4784: } elsif ($domdef{$tool}{'default'} == 0) {
4785: $access = 0;
4786: }
4787: return $access;
4788: }
4789: }
4790: } else {
4791: if ($context eq 'tools') {
4792: $access = 1;
4793: } else {
4794: $access = 0;
4795: }
4796: return $access;
4797: }
4798: }
4799:
4800: sub is_advanced_user {
4801: my ($udom,$uname) = @_;
4802: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4803: my %allroles;
4804: my $is_adv;
4805: foreach my $role (keys(%roleshash)) {
4806: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4807: my $area = '/'.$tdomain.'/'.$trest;
4808: if ($sec ne '') {
4809: $area .= '/'.$sec;
4810: }
4811: if (($area ne '') && ($trole ne '')) {
4812: my $spec=$trole.'.'.$area;
4813: if ($trole =~ /^cr\//) {
4814: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4815: } elsif ($trole ne 'gr') {
4816: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4817: }
4818: }
4819: }
4820: foreach my $role (keys(%allroles)) {
4821: last if ($is_adv);
4822: foreach my $item (split(/:/,$allroles{$role})) {
4823: if ($item ne '') {
4824: my ($privilege,$restrictions)=split(/&/,$item);
4825: if ($privilege eq 'adv') {
4826: $is_adv = 1;
4827: last;
4828: }
4829: }
4830: }
4831: }
4832: return $is_adv;
4833: }
4834:
4835: # ---------------------------------------------- Custom access rule evaluation
4836:
4837: sub customaccess {
4838: my ($priv,$uri)=@_;
4839: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
4840: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
4841: $udom = &LONCAPA::clean_domain($udom);
4842: $ucrs = &LONCAPA::clean_username($ucrs);
4843: my $access=0;
4844: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
4845: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4846: if ($type eq 'user') {
4847: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4848: my ($tdom,$tuname)=split(m{/},$scope);
4849: if ($tdom) {
4850: if ($tdom ne $env{'user.domain'}) { next; }
4851: }
4852: if ($tuname) {
4853: if ($tuname ne $env{'user.name'}) { next; }
4854: }
4855: $access=($effect eq 'allow');
4856: last;
4857: }
4858: } else {
4859: if ($role) {
4860: if ($role ne $urole) { next; }
4861: }
4862: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4863: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4864: if ($tdom) {
4865: if ($tdom ne $udom) { next; }
4866: }
4867: if ($tcrs) {
4868: if ($tcrs ne $ucrs) { next; }
4869: }
4870: if ($tsec) {
4871: if ($tsec ne $usec) { next; }
4872: }
4873: $access=($effect eq 'allow');
4874: last;
4875: }
4876: if ($realm eq '' && $role eq '') {
4877: $access=($effect eq 'allow');
4878: }
4879: }
4880: }
4881: return $access;
4882: }
4883:
4884: # ------------------------------------------------- Check for a user privilege
4885:
4886: sub allowed {
4887: my ($priv,$uri,$symb,$role)=@_;
4888: my $ver_orguri=$uri;
4889: $uri=&deversion($uri);
4890: my $orguri=$uri;
4891: $uri=&declutter($uri);
4892:
4893: if ($priv eq 'evb') {
4894: # Evade communication block restrictions for specified role in a course
4895: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4896: return $1;
4897: } else {
4898: return;
4899: }
4900: }
4901:
4902: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
4903: # Free bre access to adm and meta resources
4904: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
4905: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4906: && ($priv eq 'bre')) {
4907: return 'F';
4908: }
4909:
4910: # Free bre access to user's own portfolio contents
4911: my ($space,$domain,$name,@dir)=split('/',$uri);
4912: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
4913: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
4914: my %setters;
4915: my ($startblock,$endblock) =
4916: &Apache::loncommon::blockcheck(\%setters,'port');
4917: if ($startblock && $endblock) {
4918: return 'B';
4919: } else {
4920: return 'F';
4921: }
4922: }
4923:
4924: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
4925: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4926: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4927: if (exists($env{'request.course.id'})) {
4928: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4929: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4930: if (($domain eq $cdom) && ($name eq $cnum)) {
4931: my $courseprivid=$env{'request.course.id'};
4932: $courseprivid=~s/\_/\//;
4933: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4934: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4935: return $1;
4936: } else {
4937: if ($env{'request.course.sec'}) {
4938: $courseprivid.='/'.$env{'request.course.sec'};
4939: }
4940: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4941: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4942: return $2;
4943: }
4944: }
4945: }
4946: }
4947: }
4948:
4949: # Free bre to public access
4950:
4951: if ($priv eq 'bre') {
4952: my $copyright=&metadata($uri,'copyright');
4953: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
4954: return 'F';
4955: }
4956: if ($copyright eq 'priv') {
4957: $uri=~/([^\/]+)\/([^\/]+)\//;
4958: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
4959: return '';
4960: }
4961: }
4962: if ($copyright eq 'domain') {
4963: $uri=~/([^\/]+)\/([^\/]+)\//;
4964: unless (($env{'user.domain'} eq $1) ||
4965: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
4966: return '';
4967: }
4968: }
4969: if ($env{'request.role'}=~ /li\.\//) {
4970: # Library role, so allow browsing of resources in this domain.
4971: return 'F';
4972: }
4973: if ($copyright eq 'custom') {
4974: unless (&customaccess($priv,$uri)) { return ''; }
4975: }
4976: }
4977: # Domain coordinator is trying to create a course
4978: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
4979: # uri is the requested domain in this case.
4980: # comparison to 'request.role.domain' shows if the user has selected
4981: # a role of dc for the domain in question.
4982: return 'F' if ($uri eq $env{'request.role.domain'});
4983: }
4984:
4985: my $thisallowed='';
4986: my $statecond=0;
4987: my $courseprivid='';
4988:
4989: # Course
4990:
4991: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
4992: $thisallowed.=$1;
4993: }
4994:
4995: # Domain
4996:
4997: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
4998: =~/\Q$priv\E\&([^\:]*)/) {
4999: $thisallowed.=$1;
5000: }
5001:
5002: # Course: uri itself is a course
5003: my $courseuri=$uri;
5004: $courseuri=~s/\_(\d)/\/$1/;
5005: $courseuri=~s/^([^\/])/\/$1/;
5006:
5007: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5008: =~/\Q$priv\E\&([^\:]*)/) {
5009: $thisallowed.=$1;
5010: }
5011:
5012: # URI is an uploaded document for this course, default permissions don't matter
5013: # not allowing 'edit' access (editupload) to uploaded course docs
5014: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5015: $thisallowed='';
5016: my ($match)=&is_on_map($uri);
5017: if ($match) {
5018: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5019: =~/\Q$priv\E\&([^\:]*)/) {
5020: $thisallowed.=$1;
5021: }
5022: } else {
5023: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5024: if ($refuri) {
5025: if ($refuri =~ m|^/adm/|) {
5026: $thisallowed='F';
5027: } else {
5028: $refuri=&declutter($refuri);
5029: my ($match) = &is_on_map($refuri);
5030: if ($match) {
5031: $thisallowed='F';
5032: }
5033: }
5034: }
5035: }
5036: }
5037:
5038: if ($priv eq 'bre'
5039: && $thisallowed ne 'F'
5040: && $thisallowed ne '2'
5041: && &is_portfolio_url($uri)) {
5042: $thisallowed = &portfolio_access($uri);
5043: }
5044:
5045: # Full access at system, domain or course-wide level? Exit.
5046: if ($thisallowed=~/F/) {
5047: return 'F';
5048: }
5049:
5050: # If this is generating or modifying users, exit with special codes
5051:
5052: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5053: if (($priv eq 'cca') || ($priv eq 'caa')) {
5054: my ($audom,$auname)=split('/',$uri);
5055: # no author name given, so this just checks on the general right to make a co-author in this domain
5056: unless ($auname) { return $thisallowed; }
5057: # an author name is given, so we are about to actually make a co-author for a certain account
5058: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5059: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5060: ($audom ne $env{'request.role.domain'}))) { return ''; }
5061: }
5062: return $thisallowed;
5063: }
5064: #
5065: # Gathered so far: system, domain and course wide privileges
5066: #
5067: # Course: See if uri or referer is an individual resource that is part of
5068: # the course
5069:
5070: if ($env{'request.course.id'}) {
5071:
5072: $courseprivid=$env{'request.course.id'};
5073: if ($env{'request.course.sec'}) {
5074: $courseprivid.='/'.$env{'request.course.sec'};
5075: }
5076: $courseprivid=~s/\_/\//;
5077: my $checkreferer=1;
5078: my ($match,$cond)=&is_on_map($uri);
5079: if ($match) {
5080: $statecond=$cond;
5081: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5082: =~/\Q$priv\E\&([^\:]*)/) {
5083: $thisallowed.=$1;
5084: $checkreferer=0;
5085: }
5086: }
5087:
5088: if ($checkreferer) {
5089: my $refuri=$env{'httpref.'.$orguri};
5090: unless ($refuri) {
5091: foreach my $key (keys(%env)) {
5092: if ($key=~/^httpref\..*\*/) {
5093: my $pattern=$key;
5094: $pattern=~s/^httpref\.\/res\///;
5095: $pattern=~s/\*/\[\^\/\]\+/g;
5096: $pattern=~s/\//\\\//g;
5097: if ($orguri=~/$pattern/) {
5098: $refuri=$env{$key};
5099: }
5100: }
5101: }
5102: }
5103:
5104: if ($refuri) {
5105: $refuri=&declutter($refuri);
5106: my ($match,$cond)=&is_on_map($refuri);
5107: if ($match) {
5108: my $refstatecond=$cond;
5109: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5110: =~/\Q$priv\E\&([^\:]*)/) {
5111: $thisallowed.=$1;
5112: $uri=$refuri;
5113: $statecond=$refstatecond;
5114: }
5115: }
5116: }
5117: }
5118: }
5119:
5120: #
5121: # Gathered now: all privileges that could apply, and condition number
5122: #
5123: #
5124: # Full or no access?
5125: #
5126:
5127: if ($thisallowed=~/F/) {
5128: return 'F';
5129: }
5130:
5131: unless ($thisallowed) {
5132: return '';
5133: }
5134:
5135: # Restrictions exist, deal with them
5136: #
5137: # C:according to course preferences
5138: # R:according to resource settings
5139: # L:unless locked
5140: # X:according to user session state
5141: #
5142:
5143: # Possibly locked functionality, check all courses
5144: # Locks might take effect only after 10 minutes cache expiration for other
5145: # courses, and 2 minutes for current course
5146:
5147: my $envkey;
5148: if ($thisallowed=~/L/) {
5149: foreach $envkey (keys(%env)) {
5150: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5151: my $courseid=$2;
5152: my $roleid=$1.'.'.$2;
5153: $courseid=~s/^\///;
5154: my $expiretime=600;
5155: if ($env{'request.role'} eq $roleid) {
5156: $expiretime=120;
5157: }
5158: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5159: my $prefix='course.'.$cdom.'_'.$cnum.'.';
5160: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
5161: &coursedescription($courseid,{'freshen_cache' => 1});
5162: }
5163: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5164: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5165: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5166: &log($env{'user.domain'},$env{'user.name'},
5167: $env{'user.home'},
5168: 'Locked by res: '.$priv.' for '.$uri.' due to '.
5169: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5170: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5171: return '';
5172: }
5173: }
5174: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5175: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5176: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5177: &log($env{'user.domain'},$env{'user.name'},
5178: $env{'user.home'},
5179: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
5180: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5181: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5182: return '';
5183: }
5184: }
5185: }
5186: }
5187: }
5188:
5189: #
5190: # Rest of the restrictions depend on selected course
5191: #
5192:
5193: unless ($env{'request.course.id'}) {
5194: if ($thisallowed eq 'A') {
5195: return 'A';
5196: } elsif ($thisallowed eq 'B') {
5197: return 'B';
5198: } else {
5199: return '1';
5200: }
5201: }
5202:
5203: #
5204: # Now user is definitely in a course
5205: #
5206:
5207:
5208: # Course preferences
5209:
5210: if ($thisallowed=~/C/) {
5211: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5212: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5213: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
5214: =~/\Q$rolecode\E/) {
5215: if ($priv ne 'pch') {
5216: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5217: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5218: $env{'request.course.id'});
5219: }
5220: return '';
5221: }
5222:
5223: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
5224: =~/\Q$unamedom\E/) {
5225: if ($priv ne 'pch') {
5226: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5227: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5228: $env{'request.course.id'});
5229: }
5230: return '';
5231: }
5232: }
5233:
5234: # Resource preferences
5235:
5236: if ($thisallowed=~/R/) {
5237: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5238: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
5239: if ($priv ne 'pch') {
5240: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5241: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5242: }
5243: return '';
5244: }
5245: }
5246:
5247: # Restricted by state or randomout?
5248:
5249: if ($thisallowed=~/X/) {
5250: if ($env{'acc.randomout'}) {
5251: if (!$symb) { $symb=&symbread($uri,1); }
5252: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
5253: return '';
5254: }
5255: }
5256: if (&condval($statecond)) {
5257: return '2';
5258: } else {
5259: return '';
5260: }
5261: }
5262:
5263: if ($thisallowed eq 'A') {
5264: return 'A';
5265: } elsif ($thisallowed eq 'B') {
5266: return 'B';
5267: }
5268: return 'F';
5269: }
5270:
5271: sub split_uri_for_cond {
5272: my $uri=&deversion(&declutter(shift));
5273: my @uriparts=split(/\//,$uri);
5274: my $filename=pop(@uriparts);
5275: my $pathname=join('/',@uriparts);
5276: return ($pathname,$filename);
5277: }
5278: # --------------------------------------------------- Is a resource on the map?
5279:
5280: sub is_on_map {
5281: my ($pathname,$filename) = &split_uri_for_cond(shift);
5282: #Trying to find the conditional for the file
5283: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
5284: /\&\Q$filename\E\:([\d\|]+)\&/);
5285: if ($match) {
5286: return (1,$1);
5287: } else {
5288: return (0,0);
5289: }
5290: }
5291:
5292: # --------------------------------------------------------- Get symb from alias
5293:
5294: sub get_symb_from_alias {
5295: my $symb=shift;
5296: my ($map,$resid,$url)=&decode_symb($symb);
5297: # Already is a symb
5298: if ($url) { return $symb; }
5299: # Must be an alias
5300: my $aliassymb='';
5301: my %bighash;
5302: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5303: &GDBM_READER(),0640)) {
5304: my $rid=$bighash{'mapalias_'.$symb};
5305: if ($rid) {
5306: my ($mapid,$resid)=split(/\./,$rid);
5307: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5308: $resid,$bighash{'src_'.$rid});
5309: }
5310: untie %bighash;
5311: }
5312: return $aliassymb;
5313: }
5314:
5315: # ----------------------------------------------------------------- Define Role
5316:
5317: sub definerole {
5318: if (allowed('mcr','/')) {
5319: my ($rolename,$sysrole,$domrole,$courole)=@_;
5320: foreach my $role (split(':',$sysrole)) {
5321: my ($crole,$cqual)=split(/\&/,$role);
5322: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5323: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5324: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5325: return "refused:s:$crole&$cqual";
5326: }
5327: }
5328: }
5329: foreach my $role (split(':',$domrole)) {
5330: my ($crole,$cqual)=split(/\&/,$role);
5331: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5332: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5333: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
5334: return "refused:d:$crole&$cqual";
5335: }
5336: }
5337: }
5338: foreach my $role (split(':',$courole)) {
5339: my ($crole,$cqual)=split(/\&/,$role);
5340: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5341: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5342: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5343: return "refused:c:$crole&$cqual";
5344: }
5345: }
5346: }
5347: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5348: "$env{'user.domain'}:$env{'user.name'}:".
5349: "rolesdef_$rolename=".
5350: escape($sysrole.'_'.$domrole.'_'.$courole);
5351: return reply($command,$env{'user.home'});
5352: } else {
5353: return 'refused';
5354: }
5355: }
5356:
5357: # ---------------- Make a metadata query against the network of library servers
5358:
5359: sub metadata_query {
5360: my ($query,$custom,$customshow,$server_array)=@_;
5361: my %rhash;
5362: my %libserv = &all_library();
5363: my @server_list = (defined($server_array) ? @$server_array
5364: : keys(%libserv) );
5365: for my $server (@server_list) {
5366: unless ($custom or $customshow) {
5367: my $reply=&reply("querysend:".&escape($query),$server);
5368: $rhash{$server}=$reply;
5369: }
5370: else {
5371: my $reply=&reply("querysend:".&escape($query).':'.
5372: &escape($custom).':'.&escape($customshow),
5373: $server);
5374: $rhash{$server}=$reply;
5375: }
5376: }
5377: return \%rhash;
5378: }
5379:
5380: # ----------------------------------------- Send log queries and wait for reply
5381:
5382: sub log_query {
5383: my ($uname,$udom,$query,%filters)=@_;
5384: my $uhome=&homeserver($uname,$udom);
5385: if ($uhome eq 'no_host') { return 'error: no_host'; }
5386: my $uhost=&hostname($uhome);
5387: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
5388: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5389: $uhome);
5390: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
5391: return get_query_reply($queryid);
5392: }
5393:
5394: # -------------------------- Update MySQL table for portfolio file
5395:
5396: sub update_portfolio_table {
5397: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
5398: if ($group ne '') {
5399: $file_name =~s /^\Q$group\E//;
5400: }
5401: my $homeserver = &homeserver($uname,$udom);
5402: my $queryid=
5403: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5404: ':'.&escape($file_name).':'.$action,$homeserver);
5405: my $reply = &get_query_reply($queryid);
5406: return $reply;
5407: }
5408:
5409: # -------------------------- Update MySQL allusers table
5410:
5411: sub update_allusers_table {
5412: my ($uname,$udom,$names) = @_;
5413: my $homeserver = &homeserver($uname,$udom);
5414: my $queryid=
5415: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5416: 'lastname='.&escape($names->{'lastname'}).'%%'.
5417: 'firstname='.&escape($names->{'firstname'}).'%%'.
5418: 'middlename='.&escape($names->{'middlename'}).'%%'.
5419: 'generation='.&escape($names->{'generation'}).'%%'.
5420: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5421: 'id='.&escape($names->{'id'}),$homeserver);
5422: my $reply = &get_query_reply($queryid);
5423: return $reply;
5424: }
5425:
5426: # ------- Request retrieval of institutional classlists for course(s)
5427:
5428: sub fetch_enrollment_query {
5429: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
5430: my $homeserver;
5431: my $maxtries = 1;
5432: if ($context eq 'automated') {
5433: $homeserver = $perlvar{'lonHostID'};
5434: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
5435: } else {
5436: $homeserver = &homeserver($cnum,$dom);
5437: }
5438: my $host=&hostname($homeserver);
5439: my $cmd = '';
5440: foreach my $affiliate (keys(%{$affiliatesref})) {
5441: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5442: }
5443: $cmd =~ s/%%$//;
5444: $cmd = &escape($cmd);
5445: my $query = 'fetchenrollment';
5446: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
5447: unless ($queryid=~/^\Q$host\E\_/) {
5448: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5449: return 'error: '.$queryid;
5450: }
5451: my $reply = &get_query_reply($queryid);
5452: my $tries = 1;
5453: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5454: $reply = &get_query_reply($queryid);
5455: $tries ++;
5456: }
5457: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5458: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5459: } else {
5460: my @responses = split(/:/,$reply);
5461: if ($homeserver eq $perlvar{'lonHostID'}) {
5462: foreach my $line (@responses) {
5463: my ($key,$value) = split(/=/,$line,2);
5464: $$replyref{$key} = $value;
5465: }
5466: } else {
5467: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
5468: foreach my $line (@responses) {
5469: my ($key,$value) = split(/=/,$line);
5470: $$replyref{$key} = $value;
5471: if ($value > 0) {
5472: foreach my $item (@{$$affiliatesref{$key}}) {
5473: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
5474: my $destname = $pathname.'/'.$filename;
5475: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
5476: if ($xml_classlist =~ /^error/) {
5477: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5478: } else {
5479: if ( open(FILE,">$destname") ) {
5480: print FILE &unescape($xml_classlist);
5481: close(FILE);
5482: } else {
5483: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
5484: }
5485: }
5486: }
5487: }
5488: }
5489: }
5490: return 'ok';
5491: }
5492: return 'error';
5493: }
5494:
5495: sub get_query_reply {
5496: my $queryid=shift;
5497: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5498: my $reply='';
5499: for (1..100) {
5500: sleep 2;
5501: if (-e $replyfile.'.end') {
5502: if (open(my $fh,$replyfile)) {
5503: $reply = join('',<$fh>);
5504: close($fh);
5505: } else { return 'error: reply_file_error'; }
5506: return &unescape($reply);
5507: }
5508: }
5509: return 'timeout:'.$queryid;
5510: }
5511:
5512: sub courselog_query {
5513: #
5514: # possible filters:
5515: # url: url or symb
5516: # username
5517: # domain
5518: # action: view, submit, grade
5519: # start: timestamp
5520: # end: timestamp
5521: #
5522: my (%filters)=@_;
5523: unless ($env{'request.course.id'}) { return 'no_course'; }
5524: if ($filters{'url'}) {
5525: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5526: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5527: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5528: }
5529: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5530: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5531: return &log_query($cname,$cdom,'courselog',%filters);
5532: }
5533:
5534: sub userlog_query {
5535: #
5536: # possible filters:
5537: # action: log check role
5538: # start: timestamp
5539: # end: timestamp
5540: #
5541: my ($uname,$udom,%filters)=@_;
5542: return &log_query($uname,$udom,'userlog',%filters);
5543: }
5544:
5545: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5546:
5547: sub auto_run {
5548: my ($cnum,$cdom) = @_;
5549: my $response = 0;
5550: my $settings;
5551: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5552: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5553: $settings = $domconfig{'autoenroll'};
5554: if ($settings->{'run'} eq '1') {
5555: $response = 1;
5556: }
5557: } else {
5558: my $homeserver;
5559: if (&is_course($cdom,$cnum)) {
5560: $homeserver = &homeserver($cnum,$cdom);
5561: } else {
5562: $homeserver = &domain($cdom,'primary');
5563: }
5564: if ($homeserver ne 'no_host') {
5565: $response = &reply('autorun:'.$cdom,$homeserver);
5566: }
5567: }
5568: return $response;
5569: }
5570:
5571: sub auto_get_sections {
5572: my ($cnum,$cdom,$inst_coursecode) = @_;
5573: my $homeserver;
5574: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5575: $homeserver = &homeserver($cnum,$cdom);
5576: }
5577: if (!defined($homeserver)) {
5578: if ($cdom =~ /^$match_domain$/) {
5579: $homeserver = &domain($cdom,'primary');
5580: }
5581: }
5582: my @secs;
5583: if (defined($homeserver)) {
5584: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5585: unless ($response eq 'refused') {
5586: @secs = split(/:/,$response);
5587: }
5588: }
5589: return @secs;
5590: }
5591:
5592: sub auto_new_course {
5593: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5594: my $homeserver = &homeserver($cnum,$cdom);
5595: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
5596: return $response;
5597: }
5598:
5599: sub auto_validate_courseID {
5600: my ($cnum,$cdom,$inst_course_id) = @_;
5601: my $homeserver = &homeserver($cnum,$cdom);
5602: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
5603: return $response;
5604: }
5605:
5606: sub auto_validate_instcode {
5607: my ($cnum,$cdom,$instcode,$owner) = @_;
5608: my ($homeserver,$response);
5609: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5610: $homeserver = &homeserver($cnum,$cdom);
5611: }
5612: if (!defined($homeserver)) {
5613: if ($cdom =~ /^$match_domain$/) {
5614: $homeserver = &domain($cdom,'primary');
5615: }
5616: }
5617: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5618: &escape($instcode).':'.&escape($owner),$homeserver));
5619: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5620: return ($outcome,$description);
5621: }
5622:
5623: sub auto_create_password {
5624: my ($cnum,$cdom,$authparam,$udom) = @_;
5625: my ($homeserver,$response);
5626: my $create_passwd = 0;
5627: my $authchk = '';
5628: if ($udom =~ /^$match_domain$/) {
5629: $homeserver = &domain($udom,'primary');
5630: }
5631: if ($homeserver eq '') {
5632: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5633: $homeserver = &homeserver($cnum,$cdom);
5634: }
5635: }
5636: if ($homeserver eq '') {
5637: $authchk = 'nodomain';
5638: } else {
5639: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5640: if ($response eq 'refused') {
5641: $authchk = 'refused';
5642: } else {
5643: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
5644: }
5645: }
5646: return ($authparam,$create_passwd,$authchk);
5647: }
5648:
5649: sub auto_photo_permission {
5650: my ($cnum,$cdom,$students) = @_;
5651: my $homeserver = &homeserver($cnum,$cdom);
5652: my ($outcome,$perm_reqd,$conditions) =
5653: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
5654: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5655: return (undef,undef);
5656: }
5657: return ($outcome,$perm_reqd,$conditions);
5658: }
5659:
5660: sub auto_checkphotos {
5661: my ($uname,$udom,$pid) = @_;
5662: my $homeserver = &homeserver($uname,$udom);
5663: my ($result,$resulttype);
5664: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
5665: &escape($uname).':'.&escape($pid),
5666: $homeserver));
5667: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5668: return (undef,undef);
5669: }
5670: if ($outcome) {
5671: ($result,$resulttype) = split(/:/,$outcome);
5672: }
5673: return ($result,$resulttype);
5674: }
5675:
5676: sub auto_photochoice {
5677: my ($cnum,$cdom) = @_;
5678: my $homeserver = &homeserver($cnum,$cdom);
5679: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
5680: &escape($cdom),
5681: $homeserver)));
5682: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5683: return (undef,undef);
5684: }
5685: return ($update,$comment);
5686: }
5687:
5688: sub auto_photoupdate {
5689: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5690: my $homeserver = &homeserver($cnum,$dom);
5691: my $host=&hostname($homeserver);
5692: my $cmd = '';
5693: my $maxtries = 1;
5694: foreach my $affiliate (keys(%{$affiliatesref})) {
5695: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5696: }
5697: $cmd =~ s/%%$//;
5698: $cmd = &escape($cmd);
5699: my $query = 'institutionalphotos';
5700: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5701: unless ($queryid=~/^\Q$host\E\_/) {
5702: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5703: return 'error: '.$queryid;
5704: }
5705: my $reply = &get_query_reply($queryid);
5706: my $tries = 1;
5707: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5708: $reply = &get_query_reply($queryid);
5709: $tries ++;
5710: }
5711: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5712: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5713: } else {
5714: my @responses = split(/:/,$reply);
5715: my $outcome = shift(@responses);
5716: foreach my $item (@responses) {
5717: my ($key,$value) = split(/=/,$item);
5718: $$photo{$key} = $value;
5719: }
5720: return $outcome;
5721: }
5722: return 'error';
5723: }
5724:
5725: sub auto_instcode_format {
5726: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5727: $cat_order) = @_;
5728: my $courses = '';
5729: my @homeservers;
5730: if ($caller eq 'global') {
5731: my %servers = &get_servers($codedom,'library');
5732: foreach my $tryserver (keys(%servers)) {
5733: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5734: push(@homeservers,$tryserver);
5735: }
5736: }
5737: } elsif ($caller eq 'requests') {
5738: if ($codedom =~ /^$match_domain$/) {
5739: my $chome = &domain($codedom,'primary');
5740: unless ($chome eq 'no_host') {
5741: push(@homeservers,$chome);
5742: }
5743: }
5744: } else {
5745: push(@homeservers,&homeserver($caller,$codedom));
5746: }
5747: foreach my $code (keys(%{$instcodes})) {
5748: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
5749: }
5750: chop($courses);
5751: my $ok_response = 0;
5752: my $response;
5753: while (@homeservers > 0 && $ok_response == 0) {
5754: my $server = shift(@homeservers);
5755: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5756: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5757: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
5758: split(/:/,$response);
5759: %{$codes} = (%{$codes},&str2hash($codes_str));
5760: push(@{$codetitles},&str2array($codetitles_str));
5761: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5762: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5763: $ok_response = 1;
5764: }
5765: }
5766: if ($ok_response) {
5767: return 'ok';
5768: } else {
5769: return $response;
5770: }
5771: }
5772:
5773: sub auto_instcode_defaults {
5774: my ($domain,$returnhash,$code_order) = @_;
5775: my @homeservers;
5776:
5777: my %servers = &get_servers($domain,'library');
5778: foreach my $tryserver (keys(%servers)) {
5779: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5780: push(@homeservers,$tryserver);
5781: }
5782: }
5783:
5784: my $response;
5785: foreach my $server (@homeservers) {
5786: $response=&reply('autoinstcodedefaults:'.$domain,$server);
5787: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5788:
5789: foreach my $pair (split(/\&/,$response)) {
5790: my ($name,$value)=split(/\=/,$pair);
5791: if ($name eq 'code_order') {
5792: @{$code_order} = split(/\&/,&unescape($value));
5793: } else {
5794: $returnhash->{&unescape($name)}=&unescape($value);
5795: }
5796: }
5797: return 'ok';
5798: }
5799:
5800: return $response;
5801: }
5802:
5803: sub auto_possible_instcodes {
5804: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5805: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5806: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5807: return;
5808: }
5809: my (@homeservers,$uhome);
5810: if (defined(&domain($domain,'primary'))) {
5811: $uhome=&domain($domain,'primary');
5812: push(@homeservers,&domain($domain,'primary'));
5813: } else {
5814: my %servers = &get_servers($domain,'library');
5815: foreach my $tryserver (keys(%servers)) {
5816: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5817: push(@homeservers,$tryserver);
5818: }
5819: }
5820: }
5821: my $response;
5822: foreach my $server (@homeservers) {
5823: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5824: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5825: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5826: split(':',$response);
5827: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5828: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
5829: foreach my $item (split('&',$cat_title)) {
5830: my ($name,$value)=split('=',$item);
5831: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
5832: }
5833: foreach my $item (split('&',$cat_order)) {
5834: my ($name,$value)=split('=',$item);
5835: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
5836: }
5837: return 'ok';
5838: }
5839: return $response;
5840: }
5841:
5842: sub auto_courserequest_checks {
5843: my ($dom) = @_;
5844: my ($homeserver,%validations);
5845: if ($dom =~ /^$match_domain$/) {
5846: $homeserver = &domain($dom,'primary');
5847: }
5848: unless ($homeserver eq 'no_host') {
5849: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5850: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5851: my @items = split(/&/,$response);
5852: foreach my $item (@items) {
5853: my ($key,$value) = split('=',$item);
5854: $validations{&unescape($key)} = &thaw_unescape($value);
5855: }
5856: }
5857: }
5858: return %validations;
5859: }
5860:
5861: sub auto_courserequest_validation {
5862: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5863: my ($homeserver,$response);
5864: if ($dom =~ /^$match_domain$/) {
5865: $homeserver = &domain($dom,'primary');
5866: }
5867: unless ($homeserver eq 'no_host') {
5868:
5869: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
5870: ':'.&escape($crstype).':'.&escape($inststatuslist).
5871: ':'.&escape($instcode).':'.&escape($instseclist),
5872: $homeserver));
5873: }
5874: return $response;
5875: }
5876:
5877: sub auto_validate_class_sec {
5878: my ($cdom,$cnum,$owners,$inst_class) = @_;
5879: my $homeserver = &homeserver($cnum,$cdom);
5880: my $ownerlist;
5881: if (ref($owners) eq 'ARRAY') {
5882: $ownerlist = join(',',@{$owners});
5883: } else {
5884: $ownerlist = $owners;
5885: }
5886: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
5887: &escape($ownerlist).':'.$cdom,$homeserver);
5888: return $response;
5889: }
5890:
5891: # ------------------------------------------------------- Course Group routines
5892:
5893: sub get_coursegroups {
5894: my ($cdom,$cnum,$group,$namespace) = @_;
5895: return(&dump($namespace,$cdom,$cnum,$group));
5896: }
5897:
5898: sub modify_coursegroup {
5899: my ($cdom,$cnum,$groupsettings) = @_;
5900: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5901: }
5902:
5903: sub toggle_coursegroup_status {
5904: my ($cdom,$cnum,$group,$action) = @_;
5905: my ($from_namespace,$to_namespace);
5906: if ($action eq 'delete') {
5907: $from_namespace = 'coursegroups';
5908: $to_namespace = 'deleted_groups';
5909: } else {
5910: $from_namespace = 'deleted_groups';
5911: $to_namespace = 'coursegroups';
5912: }
5913: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
5914: if (my $tmp = &error(%curr_group)) {
5915: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5916: return ('read error',$tmp);
5917: } else {
5918: my %savedsettings = %curr_group;
5919: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
5920: my $deloutcome;
5921: if ($result eq 'ok') {
5922: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
5923: } else {
5924: return ('write error',$result);
5925: }
5926: if ($deloutcome eq 'ok') {
5927: return 'ok';
5928: } else {
5929: return ('delete error',$deloutcome);
5930: }
5931: }
5932: }
5933:
5934: sub modify_group_roles {
5935: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
5936: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5937: my $role = 'gr/'.&escape($userprivs);
5938: my ($uname,$udom) = split(/:/,$user);
5939: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
5940: if ($result eq 'ok') {
5941: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5942: }
5943: return $result;
5944: }
5945:
5946: sub modify_coursegroup_membership {
5947: my ($cdom,$cnum,$membership) = @_;
5948: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5949: return $result;
5950: }
5951:
5952: sub get_active_groups {
5953: my ($udom,$uname,$cdom,$cnum) = @_;
5954: my $now = time;
5955: my %groups = ();
5956: foreach my $key (keys(%env)) {
5957: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
5958: my ($start,$end) = split(/\./,$env{$key});
5959: if (($end!=0) && ($end<$now)) { next; }
5960: if (($start!=0) && ($start>$now)) { next; }
5961: if ($1 eq $cdom && $2 eq $cnum) {
5962: $groups{$3} = $env{$key} ;
5963: }
5964: }
5965: }
5966: return %groups;
5967: }
5968:
5969: sub get_group_membership {
5970: my ($cdom,$cnum,$group) = @_;
5971: return(&dump('groupmembership',$cdom,$cnum,$group));
5972: }
5973:
5974: sub get_users_groups {
5975: my ($udom,$uname,$courseid) = @_;
5976: my @usersgroups;
5977: my $cachetime=1800;
5978:
5979: my $hashid="$udom:$uname:$courseid";
5980: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5981: if (defined($cached)) {
5982: @usersgroups = split(/:/,$grouplist);
5983: } else {
5984: $grouplist = '';
5985: my $courseurl = &courseid_to_courseurl($courseid);
5986: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
5987: my $access_end = $env{'course.'.$courseid.
5988: '.default_enrollment_end_date'};
5989: my $now = time;
5990: foreach my $key (keys(%roleshash)) {
5991: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5992: my $group = $1;
5993: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5994: my $start = $2;
5995: my $end = $1;
5996: if ($start == -1) { next; } # deleted from group
5997: if (($start!=0) && ($start>$now)) { next; }
5998: if (($end!=0) && ($end<$now)) {
5999: if ($access_end && $access_end < $now) {
6000: if ($access_end - $end < 86400) {
6001: push(@usersgroups,$group);
6002: }
6003: }
6004: next;
6005: }
6006: push(@usersgroups,$group);
6007: }
6008: }
6009: }
6010: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6011: $grouplist = join(':',@usersgroups);
6012: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6013: }
6014: return @usersgroups;
6015: }
6016:
6017: sub devalidate_getgroups_cache {
6018: my ($udom,$uname,$cdom,$cnum)=@_;
6019: my $courseid = $cdom.'_'.$cnum;
6020:
6021: my $hashid="$udom:$uname:$courseid";
6022: &devalidate_cache_new('getgroups',$hashid);
6023: }
6024:
6025: # ------------------------------------------------------------------ Plain Text
6026:
6027: sub plaintext {
6028: my ($short,$type,$cid,$forcedefault) = @_;
6029: if ($short =~ /^cr/) {
6030: return (split('/',$short))[-1];
6031: }
6032: if (!defined($cid)) {
6033: $cid = $env{'request.course.id'};
6034: }
6035: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
6036: unless ($forcedefault) {
6037: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6038: &Apache::lonlocal::mt_escape(\$roletext);
6039: return &Apache::lonlocal::mt($roletext);
6040: }
6041: }
6042: my %rolenames = (
6043: Course => 'std',
6044: Community => 'alt1',
6045: );
6046: if (defined($type) &&
6047: defined($rolenames{$type}) &&
6048: defined($prp{$short}{$rolenames{$type}})) {
6049: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6050: } else {
6051: return &Apache::lonlocal::mt($prp{$short}{'std'});
6052: }
6053: }
6054:
6055: # ----------------------------------------------------------------- Assign Role
6056:
6057: sub assignrole {
6058: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6059: $context)=@_;
6060: my $mrole;
6061: if ($role =~ /^cr\//) {
6062: my $cwosec=$url;
6063: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6064: unless (&allowed('ccr',$cwosec)) {
6065: my $refused = 1;
6066: if ($context eq 'requestcourses') {
6067: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6068: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6069: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6070: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6071: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6072: if ($crsenv{'internal.courseowner'} eq
6073: $env{'user.name'}.':'.$env{'user.domain'}) {
6074: $refused = '';
6075: }
6076: }
6077: }
6078: }
6079: }
6080: if ($refused) {
6081: &logthis('Refused custom assignrole: '.
6082: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6083: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6084: return 'refused';
6085: }
6086: }
6087: $mrole='cr';
6088: } elsif ($role =~ /^gr\//) {
6089: my $cwogrp=$url;
6090: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
6091: unless (&allowed('mdg',$cwogrp)) {
6092: &logthis('Refused group assignrole: '.
6093: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6094: $env{'user.name'}.' at '.$env{'user.domain'});
6095: return 'refused';
6096: }
6097: $mrole='gr';
6098: } else {
6099: my $cwosec=$url;
6100: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6101: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6102: my $refused;
6103: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6104: if (!(&allowed('c'.$role,$url))) {
6105: $refused = 1;
6106: }
6107: } else {
6108: $refused = 1;
6109: }
6110: if ($refused) {
6111: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6112: $refused = '';
6113: } elsif ($context eq 'requestcourses') {
6114: my @possroles = ('st','ta','ep','in','cc');
6115: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
6116: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6117: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6118: if ($crsenv{'internal.courseowner'} eq
6119: $env{'user.name'}.':'.$env{'user.domain'}) {
6120: $refused = '';
6121: }
6122: }
6123: }
6124: if ($refused) {
6125: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6126: ' '.$role.' '.$end.' '.$start.' by '.
6127: $env{'user.name'}.' at '.$env{'user.domain'});
6128: return 'refused';
6129: }
6130: }
6131: }
6132: $mrole=$role;
6133: }
6134: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6135: "$udom:$uname:$url".'_'."$mrole=$role";
6136: if ($end) { $command.='_'.$end; }
6137: if ($start) {
6138: if ($end) {
6139: $command.='_'.$start;
6140: } else {
6141: $command.='_0_'.$start;
6142: }
6143: }
6144: my $origstart = $start;
6145: my $origend = $end;
6146: my $delflag;
6147: # actually delete
6148: if ($deleteflag) {
6149: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
6150: # modify command to delete the role
6151: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
6152: "$udom:$uname:$url".'_'."$mrole";
6153: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
6154: # set start and finish to negative values for userrolelog
6155: $start=-1;
6156: $end=-1;
6157: $delflag = 1;
6158: }
6159: }
6160: # send command
6161: my $answer=&reply($command,&homeserver($uname,$udom));
6162: # log new user role if status is ok
6163: if ($answer eq 'ok') {
6164: &userrolelog($role,$uname,$udom,$url,$start,$end);
6165: # for course roles, perform group memberships changes triggered by role change.
6166: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
6167: unless ($role =~ /^gr/) {
6168: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
6169: $origstart,$selfenroll,$context);
6170: }
6171: }
6172: return $answer;
6173: }
6174:
6175: # -------------------------------------------------- Modify user authentication
6176: # Overrides without validation
6177:
6178: sub modifyuserauth {
6179: my ($udom,$uname,$umode,$upass)=@_;
6180: my $uhome=&homeserver($uname,$udom);
6181: unless (&allowed('mau',$udom)) { return 'refused'; }
6182: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
6183: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6184: ' in domain '.$env{'request.role.domain'});
6185: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6186: &escape($upass),$uhome);
6187: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
6188: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6189: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6190: &log($udom,,$uname,$uhome,
6191: 'Authentication changed by '.$env{'user.domain'}.', '.
6192: $env{'user.name'}.', '.$umode.
6193: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6194: unless ($reply eq 'ok') {
6195: &logthis('Authentication mode error: '.$reply);
6196: return 'error: '.$reply;
6197: }
6198: return 'ok';
6199: }
6200:
6201: # --------------------------------------------------------------- Modify a user
6202:
6203: sub modifyuser {
6204: my ($udom, $uname, $uid,
6205: $umode, $upass, $first,
6206: $middle, $last, $gene,
6207: $forceid, $desiredhome, $email, $inststatus)=@_;
6208: $udom= &LONCAPA::clean_domain($udom);
6209: $uname=&LONCAPA::clean_username($uname);
6210: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
6211: $umode.', '.$first.', '.$middle.', '.
6212: $last.', '.$gene.'(forceid: '.$forceid.')'.
6213: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6214: ' desiredhome not specified').
6215: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6216: ' in domain '.$env{'request.role.domain'});
6217: my $uhome=&homeserver($uname,$udom,'true');
6218: # ----------------------------------------------------------------- Create User
6219: if (($uhome eq 'no_host') &&
6220: (($umode && $upass) || ($umode eq 'localauth'))) {
6221: my $unhome='';
6222: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
6223: $unhome = $desiredhome;
6224: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6225: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
6226: } else { # load balancing routine for determining $unhome
6227: my $loadm=10000000;
6228: my %servers = &get_servers($udom,'library');
6229: foreach my $tryserver (keys(%servers)) {
6230: my $answer=reply('load',$tryserver);
6231: if (($answer=~/\d+/) && ($answer<$loadm)) {
6232: $loadm=$answer;
6233: $unhome=$tryserver;
6234: }
6235: }
6236: }
6237: if (($unhome eq '') || ($unhome eq 'no_host')) {
6238: return 'error: unable to find a home server for '.$uname.
6239: ' in domain '.$udom;
6240: }
6241: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6242: &escape($upass),$unhome);
6243: unless ($reply eq 'ok') {
6244: return 'error: '.$reply;
6245: }
6246: $uhome=&homeserver($uname,$udom,'true');
6247: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
6248: return 'error: unable verify users home machine.';
6249: }
6250: } # End of creation of new user
6251: # ---------------------------------------------------------------------- Add ID
6252: if ($uid) {
6253: $uid=~tr/A-Z/a-z/;
6254: my %uidhash=&idrget($udom,$uname);
6255: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6256: && (!$forceid)) {
6257: unless ($uid eq $uidhash{$uname}) {
6258: return 'error: user id "'.$uid.'" does not match '.
6259: 'current user id "'.$uidhash{$uname}.'".';
6260: }
6261: } else {
6262: &idput($udom,($uname => $uid));
6263: }
6264: }
6265: # -------------------------------------------------------------- Add names, etc
6266: my @tmp=&get('environment',
6267: ['firstname','middlename','lastname','generation','id',
6268: 'permanentemail','inststatus'],
6269: $udom,$uname);
6270: my %names;
6271: if ($tmp[0] =~ m/^error:.*/) {
6272: %names=();
6273: } else {
6274: %names = @tmp;
6275: }
6276: #
6277: # Make sure to not trash student environment if instructor does not bother
6278: # to supply name and email information
6279: #
6280: if ($first) { $names{'firstname'} = $first; }
6281: if (defined($middle)) { $names{'middlename'} = $middle; }
6282: if ($last) { $names{'lastname'} = $last; }
6283: if (defined($gene)) { $names{'generation'} = $gene; }
6284: if ($email) {
6285: $email=~s/[^\w\@\.\-\,]//gs;
6286: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
6287: }
6288: if ($uid) { $names{'id'} = $uid; }
6289: if (defined($inststatus)) {
6290: $names{'inststatus'} = '';
6291: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6292: if (ref($usertypes) eq 'HASH') {
6293: my @okstatuses;
6294: foreach my $item (split(/:/,$inststatus)) {
6295: if (defined($usertypes->{$item})) {
6296: push(@okstatuses,$item);
6297: }
6298: }
6299: if (@okstatuses) {
6300: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6301: }
6302: }
6303: }
6304: my $reply = &put('environment', \%names, $udom,$uname);
6305: if ($reply ne 'ok') { return 'error: '.$reply; }
6306: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6307: &devalidate_cache_new('namescache',$uname.':'.$udom);
6308: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6309: $umode.', '.$first.', '.$middle.', '.
6310: $last.', '.$gene.', '.$email.', '.$inststatus;
6311: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6312: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6313: } else {
6314: $logmsg .= ' during self creation';
6315: }
6316: &logthis($logmsg);
6317: return 'ok';
6318: }
6319:
6320: # -------------------------------------------------------------- Modify student
6321:
6322: sub modifystudent {
6323: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
6324: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
6325: $selfenroll,$context,$inststatus)=@_;
6326: if (!$cid) {
6327: unless ($cid=$env{'request.course.id'}) {
6328: return 'not_in_class';
6329: }
6330: }
6331: # --------------------------------------------------------------- Make the user
6332: my $reply=&modifyuser
6333: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
6334: $desiredhome,$email,$inststatus);
6335: unless ($reply eq 'ok') { return $reply; }
6336: # This will cause &modify_student_enrollment to get the uid from the
6337: # students environment
6338: $uid = undef if (!$forceid);
6339: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
6340: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
6341: return $reply;
6342: }
6343:
6344: sub modify_student_enrollment {
6345: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
6346: my ($cdom,$cnum,$chome);
6347: if (!$cid) {
6348: unless ($cid=$env{'request.course.id'}) {
6349: return 'not_in_class';
6350: }
6351: $cdom=$env{'course.'.$cid.'.domain'};
6352: $cnum=$env{'course.'.$cid.'.num'};
6353: } else {
6354: ($cdom,$cnum)=split(/_/,$cid);
6355: }
6356: $chome=$env{'course.'.$cid.'.home'};
6357: if (!$chome) {
6358: $chome=&homeserver($cnum,$cdom);
6359: }
6360: if (!$chome) { return 'unknown_course'; }
6361: # Make sure the user exists
6362: my $uhome=&homeserver($uname,$udom);
6363: if (($uhome eq '') || ($uhome eq 'no_host')) {
6364: return 'error: no such user';
6365: }
6366: # Get student data if we were not given enough information
6367: if (!defined($first) || $first eq '' ||
6368: !defined($last) || $last eq '' ||
6369: !defined($uid) || $uid eq '' ||
6370: !defined($middle) || $middle eq '' ||
6371: !defined($gene) || $gene eq '') {
6372: # They did not supply us with enough data to enroll the student, so
6373: # we need to pick up more information.
6374: my %tmp = &get('environment',
6375: ['firstname','middlename','lastname', 'generation','id']
6376: ,$udom,$uname);
6377:
6378: #foreach my $key (keys(%tmp)) {
6379: # &logthis("key $key = ".$tmp{$key});
6380: #}
6381: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6382: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6383: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
6384: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
6385: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6386: }
6387: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
6388: my $reply=cput('classlist',
6389: {"$uname:$udom" =>
6390: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
6391: $cdom,$cnum);
6392: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6393: return 'error: '.$reply;
6394: } else {
6395: &devalidate_getsection_cache($udom,$uname,$cid);
6396: }
6397: # Add student role to user
6398: my $uurl='/'.$cid;
6399: $uurl=~s/\_/\//g;
6400: if ($usec) {
6401: $uurl.='/'.$usec;
6402: }
6403: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
6404: }
6405:
6406: sub format_name {
6407: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6408: my $name;
6409: if ($first ne 'lastname') {
6410: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6411: } else {
6412: if ($lastname=~/\S/) {
6413: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6414: $name=~s/\s+,/,/;
6415: } else {
6416: $name.= $firstname.' '.$middlename.' '.$generation;
6417: }
6418: }
6419: $name=~s/^\s+//;
6420: $name=~s/\s+$//;
6421: $name=~s/\s+/ /g;
6422: return $name;
6423: }
6424:
6425: # ------------------------------------------------- Write to course preferences
6426:
6427: sub writecoursepref {
6428: my ($courseid,%prefs)=@_;
6429: $courseid=~s/^\///;
6430: $courseid=~s/\_/\//g;
6431: my ($cdomain,$cnum)=split(/\//,$courseid);
6432: my $chome=homeserver($cnum,$cdomain);
6433: if (($chome eq '') || ($chome eq 'no_host')) {
6434: return 'error: no such course';
6435: }
6436: my $cstring='';
6437: foreach my $pref (keys(%prefs)) {
6438: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
6439: }
6440: $cstring=~s/\&$//;
6441: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6442: }
6443:
6444: # ---------------------------------------------------------- Make/modify course
6445:
6446: sub createcourse {
6447: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6448: $course_owner,$crstype,$cnum,$context,$category)=@_;
6449: $url=&declutter($url);
6450: my $cid='';
6451: if ($context eq 'requestcourses') {
6452: my $can_create = 0;
6453: my ($ownername,$ownerdom) = split(':',$course_owner);
6454: if ($udom eq $ownerdom) {
6455: if (&usertools_access($ownername,$ownerdom,$category,undef,
6456: $context)) {
6457: $can_create = 1;
6458: }
6459: } else {
6460: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6461: $category);
6462: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6463: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6464: if (@curr > 0) {
6465: my @options = qw(approval validate autolimit);
6466: my $optregex = join('|',@options);
6467: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6468: $can_create = 1;
6469: }
6470: }
6471: }
6472: }
6473: if ($can_create) {
6474: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6475: unless (&allowed('ccc',$udom)) {
6476: return 'refused';
6477: }
6478: }
6479: } else {
6480: return 'refused';
6481: }
6482: } elsif (!&allowed('ccc',$udom)) {
6483: return 'refused';
6484: }
6485: # --------------------------------------------------------------- Get Unique ID
6486: my $uname;
6487: if ($cnum =~ /^$match_courseid$/) {
6488: my $chome=&homeserver($cnum,$udom,'true');
6489: if (($chome eq '') || ($chome eq 'no_host')) {
6490: $uname = $cnum;
6491: } else {
6492: $uname = &generate_coursenum($udom);
6493: }
6494: } else {
6495: $uname = &generate_coursenum($udom);
6496: }
6497: return $uname if ($uname =~ /^error/);
6498: # -------------------------------------------------- Check supplied server name
6499: $course_server = $env{'user.homeserver'} if (! defined($course_server));
6500: if (! &is_library($course_server)) {
6501: return 'error:bad server name '.$course_server;
6502: }
6503: # ------------------------------------------------------------- Make the course
6504: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
6505: $course_server);
6506: unless ($reply eq 'ok') { return 'error: '.$reply; }
6507: my $uhome=&homeserver($uname,$udom,'true');
6508: if (($uhome eq '') || ($uhome eq 'no_host')) {
6509: return 'error: no such course';
6510: }
6511: # ----------------------------------------------------------------- Course made
6512: # log existence
6513: my $now = time;
6514: my $newcourse = {
6515: $udom.'_'.$uname => {
6516: description => $description,
6517: inst_code => $inst_code,
6518: owner => $course_owner,
6519: type => $crstype,
6520: creator => $env{'user.name'}.':'.
6521: $env{'user.domain'},
6522: created => $now,
6523: context => $context,
6524: },
6525: };
6526: &courseidput($udom,$newcourse,$uhome,'notime');
6527: # set toplevel url
6528: my $topurl=$url;
6529: unless ($nonstandard) {
6530: # ------------------------------------------ For standard courses, make top url
6531: my $mapurl=&clutter($url);
6532: if ($mapurl eq '/res/') { $mapurl=''; }
6533: $env{'form.initmap'}=(<<ENDINITMAP);
6534: <map>
6535: <resource id="1" type="start"></resource>
6536: <resource id="2" src="$mapurl"></resource>
6537: <resource id="3" type="finish"></resource>
6538: <link index="1" from="1" to="2"></link>
6539: <link index="2" from="2" to="3"></link>
6540: </map>
6541: ENDINITMAP
6542: $topurl=&declutter(
6543: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
6544: );
6545: }
6546: # ----------------------------------------------------------- Write preferences
6547: &writecoursepref($udom.'_'.$uname,
6548: ('description' => $description,
6549: 'url' => $topurl));
6550: return '/'.$udom.'/'.$uname;
6551: }
6552:
6553: # ------------------------------------------------------------------- Create ID
6554: sub generate_coursenum {
6555: my ($udom) = @_;
6556: my $domdesc = &domain($udom);
6557: return 'error: invalid domain' if ($domdesc eq '');
6558: my $uname=int(1+rand(9)).
6559: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6560: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6561: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6562: # ----------------------------------------------- Make sure that does not exist
6563: my $uhome=&homeserver($uname,$udom,'true');
6564: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6565: $uname=int(1+rand(9)).
6566: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6567: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6568: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6569: $uhome=&homeserver($uname,$udom,'true');
6570: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6571: return 'error: unable to generate unique course-ID';
6572: }
6573: }
6574: return $uname;
6575: }
6576:
6577: sub is_course {
6578: my ($cdom,$cnum) = @_;
6579: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
6580: undef,'.');
6581: if (exists($courses{$cdom.'_'.$cnum})) {
6582: return 1;
6583: }
6584: return 0;
6585: }
6586:
6587: sub store_userdata {
6588: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
6589: my $result;
6590: if ($datakey ne '') {
6591: if (ref($storehash) eq 'HASH') {
6592: if ($udom eq '' || $uname eq '') {
6593: $udom = $env{'user.domain'};
6594: $uname = $env{'user.name'};
6595: }
6596: my $uhome=&homeserver($uname,$udom);
6597: if (($uhome eq '') || ($uhome eq 'no_host')) {
6598: $result = 'error: no_host';
6599: } else {
6600: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6601: $storehash->{'host'} = $perlvar{'lonHostID'};
6602:
6603: my $namevalue='';
6604: foreach my $key (keys(%{$storehash})) {
6605: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6606: }
6607: $namevalue=~s/\&$//;
6608: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
6609: "$namespace:$datakey:$namevalue",$uhome);
6610: }
6611: } else {
6612: $result = 'error: data to store was not a hash reference';
6613: }
6614: } else {
6615: $result= 'error: invalid requestkey';
6616: }
6617: return $result;
6618: }
6619:
6620: # ---------------------------------------------------------- Assign Custom Role
6621:
6622: sub assigncustomrole {
6623: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
6624: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
6625: $end,$start,$deleteflag,$selfenroll,$context);
6626: }
6627:
6628: # ----------------------------------------------------------------- Revoke Role
6629:
6630: sub revokerole {
6631: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
6632: my $now=time;
6633: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
6634: }
6635:
6636: # ---------------------------------------------------------- Revoke Custom Role
6637:
6638: sub revokecustomrole {
6639: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
6640: my $now=time;
6641: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
6642: $deleteflag,$selfenroll,$context);
6643: }
6644:
6645: # ------------------------------------------------------------ Disk usage
6646: sub diskusage {
6647: my ($udom,$uname,$directorypath,$getpropath)=@_;
6648: $directorypath =~ s/\/$//;
6649: my $listing=&reply('du2:'.&escape($directorypath).':'
6650: .&escape($getpropath).':'.&escape($uname).':'
6651: .&escape($udom),homeserver($uname,$udom));
6652: if ($listing eq 'unknown_cmd') {
6653: if ($getpropath) {
6654: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6655: }
6656: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6657: }
6658: return $listing;
6659: }
6660:
6661: sub is_locked {
6662: my ($file_name, $domain, $user) = @_;
6663: my @check;
6664: my $is_locked;
6665: push @check, $file_name;
6666: my %locked = &get('file_permissions',\@check,
6667: $env{'user.domain'},$env{'user.name'});
6668: my ($tmp)=keys(%locked);
6669: if ($tmp=~/^error:/) { undef(%locked); }
6670:
6671: if (ref($locked{$file_name}) eq 'ARRAY') {
6672: $is_locked = 'false';
6673: foreach my $entry (@{$locked{$file_name}}) {
6674: if (ref($entry) eq 'ARRAY') {
6675: $is_locked = 'true';
6676: last;
6677: }
6678: }
6679: } else {
6680: $is_locked = 'false';
6681: }
6682: }
6683:
6684: sub declutter_portfile {
6685: my ($file) = @_;
6686: $file =~ s{^(/portfolio/|portfolio/)}{/};
6687: return $file;
6688: }
6689:
6690: # ------------------------------------------------------------- Mark as Read Only
6691:
6692: sub mark_as_readonly {
6693: my ($domain,$user,$files,$what) = @_;
6694: my %current_permissions = &dump('file_permissions',$domain,$user);
6695: my ($tmp)=keys(%current_permissions);
6696: if ($tmp=~/^error:/) { undef(%current_permissions); }
6697: foreach my $file (@{$files}) {
6698: $file = &declutter_portfile($file);
6699: push(@{$current_permissions{$file}},$what);
6700: }
6701: &put('file_permissions',\%current_permissions,$domain,$user);
6702: return;
6703: }
6704:
6705: # ------------------------------------------------------------Save Selected Files
6706:
6707: sub save_selected_files {
6708: my ($user, $path, @files) = @_;
6709: my $filename = $user."savedfiles";
6710: my @other_files = &files_not_in_path($user, $path);
6711: open (OUT, '>'.$tmpdir.$filename);
6712: foreach my $file (@files) {
6713: print (OUT $env{'form.currentpath'}.$file."\n");
6714: }
6715: foreach my $file (@other_files) {
6716: print (OUT $file."\n");
6717: }
6718: close (OUT);
6719: return 'ok';
6720: }
6721:
6722: sub clear_selected_files {
6723: my ($user) = @_;
6724: my $filename = $user."savedfiles";
6725: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6726: print (OUT undef);
6727: close (OUT);
6728: return ("ok");
6729: }
6730:
6731: sub files_in_path {
6732: my ($user, $path) = @_;
6733: my $filename = $user."savedfiles";
6734: my %return_files;
6735: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6736: while (my $line_in = <IN>) {
6737: chomp ($line_in);
6738: my @paths_and_file = split (m!/!, $line_in);
6739: my $file_part = pop (@paths_and_file);
6740: my $path_part = join ('/', @paths_and_file);
6741: $path_part.='/';
6742: my $path_and_file = $path_part.$file_part;
6743: if ($path_part eq $path) {
6744: $return_files{$file_part}= 'selected';
6745: }
6746: }
6747: close (IN);
6748: return (\%return_files);
6749: }
6750:
6751: # called in portfolio select mode, to show files selected NOT in current directory
6752: sub files_not_in_path {
6753: my ($user, $path) = @_;
6754: my $filename = $user."savedfiles";
6755: my @return_files;
6756: my $path_part;
6757: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6758: while (my $line = <IN>) {
6759: #ok, I know it's clunky, but I want it to work
6760: my @paths_and_file = split(m|/|, $line);
6761: my $file_part = pop(@paths_and_file);
6762: chomp($file_part);
6763: my $path_part = join('/', @paths_and_file);
6764: $path_part .= '/';
6765: my $path_and_file = $path_part.$file_part;
6766: if ($path_part ne $path) {
6767: push(@return_files, ($path_and_file));
6768: }
6769: }
6770: close(OUT);
6771: return (@return_files);
6772: }
6773:
6774: #----------------------------------------------Get portfolio file permissions
6775:
6776: sub get_portfile_permissions {
6777: my ($domain,$user) = @_;
6778: my %current_permissions = &dump('file_permissions',$domain,$user);
6779: my ($tmp)=keys(%current_permissions);
6780: if ($tmp=~/^error:/) { undef(%current_permissions); }
6781: return \%current_permissions;
6782: }
6783:
6784: #---------------------------------------------Get portfolio file access controls
6785:
6786: sub get_access_controls {
6787: my ($current_permissions,$group,$file) = @_;
6788: my %access;
6789: my $real_file = $file;
6790: $file =~ s/\.meta$//;
6791: if (defined($file)) {
6792: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6793: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
6794: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
6795: }
6796: }
6797: } else {
6798: foreach my $key (keys(%{$current_permissions})) {
6799: if ($key =~ /\0accesscontrol$/) {
6800: if (defined($group)) {
6801: if ($key !~ m-^\Q$group\E/-) {
6802: next;
6803: }
6804: }
6805: my ($fullpath) = split(/\0/,$key);
6806: if (ref($$current_permissions{$key}) eq 'HASH') {
6807: foreach my $control (keys(%{$$current_permissions{$key}})) {
6808: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6809: }
6810: }
6811: }
6812: }
6813: }
6814: return %access;
6815: }
6816:
6817: sub modify_access_controls {
6818: my ($file_name,$changes,$domain,$user)=@_;
6819: my ($outcome,$deloutcome);
6820: my %store_permissions;
6821: my %new_values;
6822: my %new_control;
6823: my %translation;
6824: my @deletions = ();
6825: my $now = time;
6826: if (exists($$changes{'activate'})) {
6827: if (ref($$changes{'activate'}) eq 'HASH') {
6828: my @newitems = sort(keys(%{$$changes{'activate'}}));
6829: my $numnew = scalar(@newitems);
6830: for (my $i=0; $i<$numnew; $i++) {
6831: my $newkey = $newitems[$i];
6832: my $newid = &Apache::loncommon::get_cgi_id();
6833: if ($newkey =~ /^\d+:/) {
6834: $newkey =~ s/^(\d+)/$newid/;
6835: $translation{$1} = $newid;
6836: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6837: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6838: $translation{$1} = $newid;
6839: }
6840: $new_values{$file_name."\0".$newkey} =
6841: $$changes{'activate'}{$newitems[$i]};
6842: $new_control{$newkey} = $now;
6843: }
6844: }
6845: }
6846: my %todelete;
6847: my %changed_items;
6848: foreach my $action ('delete','update') {
6849: if (exists($$changes{$action})) {
6850: if (ref($$changes{$action}) eq 'HASH') {
6851: foreach my $key (keys(%{$$changes{$action}})) {
6852: my ($itemnum) = ($key =~ /^([^:]+):/);
6853: if ($action eq 'delete') {
6854: $todelete{$itemnum} = 1;
6855: } else {
6856: $changed_items{$itemnum} = $key;
6857: }
6858: }
6859: }
6860: }
6861: }
6862: # get lock on access controls for file.
6863: my $lockhash = {
6864: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6865: ':'.$env{'user.domain'},
6866: };
6867: my $tries = 0;
6868: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6869:
6870: while (($gotlock ne 'ok') && $tries <3) {
6871: $tries ++;
6872: sleep 1;
6873: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6874: }
6875: if ($gotlock eq 'ok') {
6876: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6877: my ($tmp)=keys(%curr_permissions);
6878: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6879: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6880: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6881: if (ref($curr_controls) eq 'HASH') {
6882: foreach my $control_item (keys(%{$curr_controls})) {
6883: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6884: if (defined($todelete{$itemnum})) {
6885: push(@deletions,$file_name."\0".$control_item);
6886: } else {
6887: if (defined($changed_items{$itemnum})) {
6888: $new_control{$changed_items{$itemnum}} = $now;
6889: push(@deletions,$file_name."\0".$control_item);
6890: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6891: } else {
6892: $new_control{$control_item} = $$curr_controls{$control_item};
6893: }
6894: }
6895: }
6896: }
6897: }
6898: my ($group);
6899: if (&is_course($domain,$user)) {
6900: ($group,my $file) = split(/\//,$file_name,2);
6901: }
6902: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6903: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6904: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6905: # remove lock
6906: my @del_lock = ($file_name."\0".'locked_access_records');
6907: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
6908: my $sqlresult =
6909: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
6910: $group);
6911: } else {
6912: $outcome = "error: could not obtain lockfile\n";
6913: }
6914: return ($outcome,$deloutcome,\%new_values,\%translation);
6915: }
6916:
6917: sub make_public_indefinitely {
6918: my ($requrl) = @_;
6919: my $now = time;
6920: my $action = 'activate';
6921: my $aclnum = 0;
6922: if (&is_portfolio_url($requrl)) {
6923: my (undef,$udom,$unum,$file_name,$group) =
6924: &parse_portfolio_url($requrl);
6925: my $current_perms = &get_portfile_permissions($udom,$unum);
6926: my %access_controls = &get_access_controls($current_perms,
6927: $group,$file_name);
6928: foreach my $key (keys(%{$access_controls{$file_name}})) {
6929: my ($num,$scope,$end,$start) =
6930: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6931: if ($scope eq 'public') {
6932: if ($start <= $now && $end == 0) {
6933: $action = 'none';
6934: } else {
6935: $action = 'update';
6936: $aclnum = $num;
6937: }
6938: last;
6939: }
6940: }
6941: if ($action eq 'none') {
6942: return 'ok';
6943: } else {
6944: my %changes;
6945: my $newend = 0;
6946: my $newstart = $now;
6947: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6948: $changes{$action}{$newkey} = {
6949: type => 'public',
6950: time => {
6951: start => $newstart,
6952: end => $newend,
6953: },
6954: };
6955: my ($outcome,$deloutcome,$new_values,$translation) =
6956: &modify_access_controls($file_name,\%changes,$udom,$unum);
6957: return $outcome;
6958: }
6959: } else {
6960: return 'invalid';
6961: }
6962: }
6963:
6964: #------------------------------------------------------Get Marked as Read Only
6965:
6966: sub get_marked_as_readonly {
6967: my ($domain,$user,$what,$group) = @_;
6968: my $current_permissions = &get_portfile_permissions($domain,$user);
6969: my @readonly_files;
6970: my $cmp1=$what;
6971: if (ref($what)) { $cmp1=join('',@{$what}) };
6972: while (my ($file_name,$value) = each(%{$current_permissions})) {
6973: if (defined($group)) {
6974: if ($file_name !~ m-^\Q$group\E/-) {
6975: next;
6976: }
6977: }
6978: if (ref($value) eq "ARRAY"){
6979: foreach my $stored_what (@{$value}) {
6980: my $cmp2=$stored_what;
6981: if (ref($stored_what) eq 'ARRAY') {
6982: $cmp2=join('',@{$stored_what});
6983: }
6984: if ($cmp1 eq $cmp2) {
6985: push(@readonly_files, $file_name);
6986: last;
6987: } elsif (!defined($what)) {
6988: push(@readonly_files, $file_name);
6989: last;
6990: }
6991: }
6992: }
6993: }
6994: return @readonly_files;
6995: }
6996: #-----------------------------------------------------------Get Marked as Read Only Hash
6997:
6998: sub get_marked_as_readonly_hash {
6999: my ($current_permissions,$group,$what) = @_;
7000: my %readonly_files;
7001: while (my ($file_name,$value) = each(%{$current_permissions})) {
7002: if (defined($group)) {
7003: if ($file_name !~ m-^\Q$group\E/-) {
7004: next;
7005: }
7006: }
7007: if (ref($value) eq "ARRAY"){
7008: foreach my $stored_what (@{$value}) {
7009: if (ref($stored_what) eq 'ARRAY') {
7010: foreach my $lock_descriptor(@{$stored_what}) {
7011: if ($lock_descriptor eq 'graded') {
7012: $readonly_files{$file_name} = 'graded';
7013: } elsif ($lock_descriptor eq 'handback') {
7014: $readonly_files{$file_name} = 'handback';
7015: } else {
7016: if (!exists($readonly_files{$file_name})) {
7017: $readonly_files{$file_name} = 'locked';
7018: }
7019: }
7020: }
7021: }
7022: }
7023: }
7024: }
7025: return %readonly_files;
7026: }
7027: # ------------------------------------------------------------ Unmark as Read Only
7028:
7029: sub unmark_as_readonly {
7030: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7031: # for portfolio submissions, $what contains [$symb,$crsid]
7032: my ($domain,$user,$what,$file_name,$group) = @_;
7033: $file_name = &declutter_portfile($file_name);
7034: my $symb_crs = $what;
7035: if (ref($what)) { $symb_crs=join('',@$what); }
7036: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
7037: my ($tmp)=keys(%current_permissions);
7038: if ($tmp=~/^error:/) { undef(%current_permissions); }
7039: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
7040: foreach my $file (@readonly_files) {
7041: my $clean_file = &declutter_portfile($file);
7042: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
7043: my $current_locks = $current_permissions{$file};
7044: my @new_locks;
7045: my @del_keys;
7046: if (ref($current_locks) eq "ARRAY"){
7047: foreach my $locker (@{$current_locks}) {
7048: my $compare=$locker;
7049: if (ref($locker) eq 'ARRAY') {
7050: $compare=join('',@{$locker});
7051: if ($compare ne $symb_crs) {
7052: push(@new_locks, $locker);
7053: }
7054: }
7055: }
7056: if (scalar(@new_locks) > 0) {
7057: $current_permissions{$file} = \@new_locks;
7058: } else {
7059: push(@del_keys, $file);
7060: &del('file_permissions',\@del_keys, $domain, $user);
7061: delete($current_permissions{$file});
7062: }
7063: }
7064: }
7065: &put('file_permissions',\%current_permissions,$domain,$user);
7066: return;
7067: }
7068:
7069: # ------------------------------------------------------------ Directory lister
7070:
7071: sub dirlist {
7072: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
7073: $uri=~s/^\///;
7074: $uri=~s/\/$//;
7075: my ($udom, $uname);
7076: if ($getuserdir) {
7077: $udom = $userdomain;
7078: $uname = $username;
7079: } else {
7080: (undef,$udom,$uname)=split(/\//,$uri);
7081: if(defined($userdomain)) {
7082: $udom = $userdomain;
7083: }
7084: if(defined($username)) {
7085: $uname = $username;
7086: }
7087: }
7088: my ($dirRoot,$listing,@listing_results);
7089:
7090: $dirRoot = $perlvar{'lonDocRoot'};
7091: if (defined($getpropath)) {
7092: $dirRoot = &propath($udom,$uname);
7093: $dirRoot =~ s/\/$//;
7094: } elsif (defined($getuserdir)) {
7095: my $subdir=$uname.'__';
7096: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7097: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7098: ."/$udom/$subdir/$uname";
7099: } elsif (defined($alternateRoot)) {
7100: $dirRoot = $alternateRoot;
7101: }
7102:
7103: if($udom) {
7104: if($uname) {
7105: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
7106: .$getuserdir.':'.&escape($dirRoot)
7107: .':'.&escape($uname).':'.&escape($udom),
7108: &homeserver($uname,$udom));
7109: if ($listing eq 'unknown_cmd') {
7110: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7111: &homeserver($uname,$udom));
7112: } else {
7113: @listing_results = map { &unescape($_); } split(/:/,$listing);
7114: }
7115: if ($listing eq 'unknown_cmd') {
7116: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7117: &homeserver($uname,$udom));
7118: @listing_results = split(/:/,$listing);
7119: } else {
7120: @listing_results = map { &unescape($_); } split(/:/,$listing);
7121: }
7122: return @listing_results;
7123: } elsif(!$alternateRoot) {
7124: my %allusers;
7125: my %servers = &get_servers($udom,'library');
7126: foreach my $tryserver (keys(%servers)) {
7127: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7128: &escape($udom),$tryserver);
7129: if ($listing eq 'unknown_cmd') {
7130: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7131: $udom, $tryserver);
7132: } else {
7133: @listing_results = map { &unescape($_); } split(/:/,$listing);
7134: }
7135: if ($listing eq 'unknown_cmd') {
7136: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7137: $udom, $tryserver);
7138: @listing_results = split(/:/,$listing);
7139: } else {
7140: @listing_results =
7141: map { &unescape($_); } split(/:/,$listing);
7142: }
7143: if ($listing_results[0] ne 'no_such_dir' &&
7144: $listing_results[0] ne 'empty' &&
7145: $listing_results[0] ne 'con_lost') {
7146: foreach my $line (@listing_results) {
7147: my ($entry) = split(/&/,$line,2);
7148: $allusers{$entry} = 1;
7149: }
7150: }
7151: }
7152: my $alluserstr='';
7153: foreach my $user (sort(keys(%allusers))) {
7154: $alluserstr.=$user.'&user:';
7155: }
7156: $alluserstr=~s/:$//;
7157: return split(/:/,$alluserstr);
7158: } else {
7159: return ('missing user name');
7160: }
7161: } elsif(!defined($getpropath)) {
7162: my @all_domains = sort(&all_domains());
7163: foreach my $domain (@all_domains) {
7164: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7165: }
7166: return @all_domains;
7167: } else {
7168: return ('missing domain');
7169: }
7170: }
7171:
7172: # --------------------------------------------- GetFileTimestamp
7173: # This function utilizes dirlist and returns the date stamp for
7174: # when it was last modified. It will also return an error of -1
7175: # if an error occurs
7176:
7177: sub GetFileTimestamp {
7178: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
7179: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7180: $studentName = &LONCAPA::clean_username($studentName);
7181: my ($fileStat) =
7182: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7183: undef,$getuserdir);
7184: my @stats = split('&', $fileStat);
7185: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7186: # @stats contains first the filename, then the stat output
7187: return $stats[10]; # so this is 10 instead of 9.
7188: } else {
7189: return -1;
7190: }
7191: }
7192:
7193: sub stat_file {
7194: my ($uri) = @_;
7195: $uri = &clutter_with_no_wrapper($uri);
7196:
7197: my ($udom,$uname,$file);
7198: if ($uri =~ m-^/(uploaded|editupload)/-) {
7199: ($udom,$uname,$file) =
7200: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
7201: $file = 'userfiles/'.$file;
7202: }
7203: if ($uri =~ m-^/res/-) {
7204: ($udom,$uname) =
7205: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
7206: $file = $uri;
7207: }
7208:
7209: if (!$udom || !$uname || !$file) {
7210: # unable to handle the uri
7211: return ();
7212: }
7213: my $getpropath;
7214: if ($file =~ /^userfiles\//) {
7215: $getpropath = 1;
7216: }
7217: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
7218: my @stats = split('&', $result);
7219:
7220: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7221: shift(@stats); #filename is first
7222: return @stats;
7223: }
7224: return ();
7225: }
7226:
7227: # -------------------------------------------------------- Value of a Condition
7228:
7229: # gets the value of a specific preevaluated condition
7230: # stored in the string $env{user.state.<cid>}
7231: # or looks up a condition reference in the bighash and if if hasn't
7232: # already been evaluated recurses into docondval to get the value of
7233: # the condition, then memoizing it to
7234: # $env{user.state.<cid>.<condition>}
7235: sub directcondval {
7236: my $number=shift;
7237: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
7238: &Apache::lonuserstate::evalstate();
7239: }
7240: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7241: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7242: } elsif ($number =~ /^_/) {
7243: my $sub_condition;
7244: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7245: &GDBM_READER(),0640)) {
7246: $sub_condition=$bighash{'conditions'.$number};
7247: untie(%bighash);
7248: }
7249: my $value = &docondval($sub_condition);
7250: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
7251: return $value;
7252: }
7253: if ($env{'user.state.'.$env{'request.course.id'}}) {
7254: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
7255: } else {
7256: return 2;
7257: }
7258: }
7259:
7260: # get the collection of conditions for this resource
7261: sub condval {
7262: my $condidx=shift;
7263: my $allpathcond='';
7264: foreach my $cond (split(/\|/,$condidx)) {
7265: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7266: $allpathcond.=
7267: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7268: }
7269: }
7270: $allpathcond=~s/\|$//;
7271: return &docondval($allpathcond);
7272: }
7273:
7274: #evaluates an expression of conditions
7275: sub docondval {
7276: my ($allpathcond) = @_;
7277: my $result=0;
7278: if ($env{'request.course.id'}
7279: && defined($allpathcond)) {
7280: my $operand='|';
7281: my @stack;
7282: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7283: if ($chunk eq '(') {
7284: push @stack,($operand,$result);
7285: } elsif ($chunk eq ')') {
7286: my $before=pop @stack;
7287: if (pop @stack eq '&') {
7288: $result=$result>$before?$before:$result;
7289: } else {
7290: $result=$result>$before?$result:$before;
7291: }
7292: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7293: $operand=$chunk;
7294: } else {
7295: my $new=directcondval($chunk);
7296: if ($operand eq '&') {
7297: $result=$result>$new?$new:$result;
7298: } else {
7299: $result=$result>$new?$result:$new;
7300: }
7301: }
7302: }
7303: }
7304: return $result;
7305: }
7306:
7307: # ---------------------------------------------------- Devalidate courseresdata
7308:
7309: sub devalidatecourseresdata {
7310: my ($coursenum,$coursedomain)=@_;
7311: my $hashid=$coursenum.':'.$coursedomain;
7312: &devalidate_cache_new('courseres',$hashid);
7313: }
7314:
7315:
7316: # --------------------------------------------------- Course Resourcedata Query
7317: #
7318: # Parameters:
7319: # $coursenum - Number of the course.
7320: # $coursedomain - Domain at which the course was created.
7321: # Returns:
7322: # A hash of the course parameters along (I think) with timestamps
7323: # and version info.
7324:
7325: sub get_courseresdata {
7326: my ($coursenum,$coursedomain)=@_;
7327: my $coursehom=&homeserver($coursenum,$coursedomain);
7328: my $hashid=$coursenum.':'.$coursedomain;
7329: my ($result,$cached)=&is_cached_new('courseres',$hashid);
7330: my %dumpreply;
7331: unless (defined($cached)) {
7332: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
7333: $result=\%dumpreply;
7334: my ($tmp) = keys(%dumpreply);
7335: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7336: &do_cache_new('courseres',$hashid,$result,600);
7337: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7338: return $tmp;
7339: } elsif ($tmp =~ /^(error)/) {
7340: $result=undef;
7341: &do_cache_new('courseres',$hashid,$result,600);
7342: }
7343: }
7344: return $result;
7345: }
7346:
7347: sub devalidateuserresdata {
7348: my ($uname,$udom)=@_;
7349: my $hashid="$udom:$uname";
7350: &devalidate_cache_new('userres',$hashid);
7351: }
7352:
7353: sub get_userresdata {
7354: my ($uname,$udom)=@_;
7355: #most student don\'t have any data set, check if there is some data
7356: if (&EXT_cache_status($udom,$uname)) { return undef; }
7357:
7358: my $hashid="$udom:$uname";
7359: my ($result,$cached)=&is_cached_new('userres',$hashid);
7360: if (!defined($cached)) {
7361: my %resourcedata=&dump('resourcedata',$udom,$uname);
7362: $result=\%resourcedata;
7363: &do_cache_new('userres',$hashid,$result,600);
7364: }
7365: my ($tmp)=keys(%$result);
7366: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7367: return $result;
7368: }
7369: #error 2 occurs when the .db doesn't exist
7370: if ($tmp!~/error: 2 /) {
7371: &logthis("<font color=\"blue\">WARNING:".
7372: " Trying to get resource data for ".
7373: $uname." at ".$udom.": ".
7374: $tmp."</font>");
7375: } elsif ($tmp=~/error: 2 /) {
7376: #&EXT_cache_set($udom,$uname);
7377: &do_cache_new('userres',$hashid,undef,600);
7378: undef($tmp); # not really an error so don't send it back
7379: }
7380: return $tmp;
7381: }
7382: #----------------------------------------------- resdata - return resource data
7383: # Purpose:
7384: # Return resource data for either users or for a course.
7385: # Parameters:
7386: # $name - Course/user name.
7387: # $domain - Name of the domain the user/course is registered on.
7388: # $type - Type of thing $name is (must be 'course' or 'user'
7389: # @which - Array of names of resources desired.
7390: # Returns:
7391: # The value of the first reasource in @which that is found in the
7392: # resource hash.
7393: # Exceptional Conditions:
7394: # If the $type passed in is not valid (not the string 'course' or
7395: # 'user', an undefined reference is returned.
7396: # If none of the resources are found, an undef is returned
7397: sub resdata {
7398: my ($name,$domain,$type,@which)=@_;
7399: my $result;
7400: if ($type eq 'course') {
7401: $result=&get_courseresdata($name,$domain);
7402: } elsif ($type eq 'user') {
7403: $result=&get_userresdata($name,$domain);
7404: }
7405: if (!ref($result)) { return $result; }
7406: foreach my $item (@which) {
7407: if (defined($result->{$item->[0]})) {
7408: return [$result->{$item->[0]},$item->[1]];
7409: }
7410: }
7411: return undef;
7412: }
7413:
7414: #
7415: # EXT resource caching routines
7416: #
7417:
7418: sub clear_EXT_cache_status {
7419: &delenv('cache.EXT.');
7420: }
7421:
7422: sub EXT_cache_status {
7423: my ($target_domain,$target_user) = @_;
7424: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7425: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
7426: # We know already the user has no data
7427: return 1;
7428: } else {
7429: return 0;
7430: }
7431: }
7432:
7433: sub EXT_cache_set {
7434: my ($target_domain,$target_user) = @_;
7435: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7436: #&appenv({$cachename => time});
7437: }
7438:
7439: # --------------------------------------------------------- Value of a Variable
7440: sub EXT {
7441:
7442: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
7443: unless ($varname) { return ''; }
7444: #get real user name/domain, courseid and symb
7445: my $courseid;
7446: my $publicuser;
7447: if ($symbparm) {
7448: $symbparm=&get_symb_from_alias($symbparm);
7449: }
7450: if (!($uname && $udom)) {
7451: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
7452: if (!$symbparm) { $symbparm=$cursymb; }
7453: } else {
7454: $courseid=$env{'request.course.id'};
7455: }
7456: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7457: my $rest;
7458: if (defined($therest[0])) {
7459: $rest=join('.',@therest);
7460: } else {
7461: $rest='';
7462: }
7463:
7464: my $qualifierrest=$qualifier;
7465: if ($rest) { $qualifierrest.='.'.$rest; }
7466: my $spacequalifierrest=$space;
7467: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
7468: if ($realm eq 'user') {
7469: # --------------------------------------------------------------- user.resource
7470: if ($space eq 'resource') {
7471: if ( (defined($Apache::lonhomework::parsing_a_problem)
7472: || defined($Apache::lonhomework::parsing_a_task))
7473: &&
7474: ($symbparm eq &symbread()) ) {
7475: # if we are in the middle of processing the resource the
7476: # get the value we are planning on committing
7477: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7478: return $Apache::lonhomework::results{$qualifierrest};
7479: } else {
7480: return $Apache::lonhomework::history{$qualifierrest};
7481: }
7482: } else {
7483: my %restored;
7484: if ($publicuser || $env{'request.state'} eq 'construct') {
7485: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7486: } else {
7487: %restored=&restore($symbparm,$courseid,$udom,$uname);
7488: }
7489: return $restored{$qualifierrest};
7490: }
7491: # ----------------------------------------------------------------- user.access
7492: } elsif ($space eq 'access') {
7493: # FIXME - not supporting calls for a specific user
7494: return &allowed($qualifier,$rest);
7495: # ------------------------------------------ user.preferences, user.environment
7496: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
7497: if (($uname eq $env{'user.name'}) &&
7498: ($udom eq $env{'user.domain'})) {
7499: return $env{join('.',('environment',$qualifierrest))};
7500: } else {
7501: my %returnhash;
7502: if (!$publicuser) {
7503: %returnhash=&userenvironment($udom,$uname,
7504: $qualifierrest);
7505: }
7506: return $returnhash{$qualifierrest};
7507: }
7508: # ----------------------------------------------------------------- user.course
7509: } elsif ($space eq 'course') {
7510: # FIXME - not supporting calls for a specific user
7511: return $env{join('.',('request.course',$qualifier))};
7512: # ------------------------------------------------------------------- user.role
7513: } elsif ($space eq 'role') {
7514: # FIXME - not supporting calls for a specific user
7515: my ($role,$where)=split(/\./,$env{'request.role'});
7516: if ($qualifier eq 'value') {
7517: return $role;
7518: } elsif ($qualifier eq 'extent') {
7519: return $where;
7520: }
7521: # ----------------------------------------------------------------- user.domain
7522: } elsif ($space eq 'domain') {
7523: return $udom;
7524: # ------------------------------------------------------------------- user.name
7525: } elsif ($space eq 'name') {
7526: return $uname;
7527: # ---------------------------------------------------- Any other user namespace
7528: } else {
7529: my %reply;
7530: if (!$publicuser) {
7531: %reply=&get($space,[$qualifierrest],$udom,$uname);
7532: }
7533: return $reply{$qualifierrest};
7534: }
7535: } elsif ($realm eq 'query') {
7536: # ---------------------------------------------- pull stuff out of query string
7537: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7538: [$spacequalifierrest]);
7539: return $env{'form.'.$spacequalifierrest};
7540: } elsif ($realm eq 'request') {
7541: # ------------------------------------------------------------- request.browser
7542: if ($space eq 'browser') {
7543: if ($qualifier eq 'textremote') {
7544: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
7545: return 1;
7546: } else {
7547: return 0;
7548: }
7549: } else {
7550: return $env{'browser.'.$qualifier};
7551: }
7552: # ------------------------------------------------------------ request.filename
7553: } else {
7554: return $env{'request.'.$spacequalifierrest};
7555: }
7556: } elsif ($realm eq 'course') {
7557: # ---------------------------------------------------------- course.description
7558: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
7559: } elsif ($realm eq 'resource') {
7560:
7561: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
7562: if (!$symbparm) { $symbparm=&symbread(); }
7563: }
7564:
7565: if ($space eq 'title') {
7566: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7567: return &gettitle($symbparm);
7568: }
7569:
7570: if ($space eq 'map') {
7571: my ($map) = &decode_symb($symbparm);
7572: return &symbread($map);
7573: }
7574: if ($space eq 'filename') {
7575: if ($symbparm) {
7576: return &clutter((&decode_symb($symbparm))[2]);
7577: }
7578: return &hreflocation('',$env{'request.filename'});
7579: }
7580:
7581: my ($section, $group, @groups);
7582: my ($courselevelm,$courselevel);
7583: if ($symbparm && defined($courseid) &&
7584: $courseid eq $env{'request.course.id'}) {
7585:
7586: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
7587:
7588: # ----------------------------------------------------- Cascading lookup scheme
7589: my $symbp=$symbparm;
7590: my $mapp=&deversion((&decode_symb($symbp))[0]);
7591:
7592: my $symbparm=$symbp.'.'.$spacequalifierrest;
7593: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7594:
7595: if (($env{'user.name'} eq $uname) &&
7596: ($env{'user.domain'} eq $udom)) {
7597: $section=$env{'request.course.sec'};
7598: @groups = split(/:/,$env{'request.course.groups'});
7599: @groups=&sort_course_groups($courseid,@groups);
7600: } else {
7601: if (! defined($usection)) {
7602: $section=&getsection($udom,$uname,$courseid);
7603: } else {
7604: $section = $usection;
7605: }
7606: @groups = &get_users_groups($udom,$uname,$courseid);
7607: }
7608:
7609: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7610: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7611: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7612:
7613: $courselevel=$courseid.'.'.$spacequalifierrest;
7614: my $courselevelr=$courseid.'.'.$symbparm;
7615: $courselevelm=$courseid.'.'.$mapparm;
7616:
7617: # ----------------------------------------------------------- first, check user
7618:
7619: my $userreply=&resdata($uname,$udom,'user',
7620: ([$courselevelr,'resource'],
7621: [$courselevelm,'map' ],
7622: [$courselevel, 'course' ]));
7623: if (defined($userreply)) { return &get_reply($userreply); }
7624:
7625: # ------------------------------------------------ second, check some of course
7626: my $coursereply;
7627: if (@groups > 0) {
7628: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7629: $mapparm,$spacequalifierrest);
7630: if (defined($coursereply)) { return &get_reply($coursereply); }
7631: }
7632:
7633: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7634: $env{'course.'.$courseid.'.domain'},
7635: 'course',
7636: ([$seclevelr, 'resource'],
7637: [$seclevelm, 'map' ],
7638: [$seclevel, 'course' ],
7639: [$courselevelr,'resource']));
7640: if (defined($coursereply)) { return &get_reply($coursereply); }
7641:
7642: # ------------------------------------------------------ third, check map parms
7643: my %parmhash=();
7644: my $thisparm='';
7645: if (tie(%parmhash,'GDBM_File',
7646: $env{'request.course.fn'}.'_parms.db',
7647: &GDBM_READER(),0640)) {
7648: $thisparm=$parmhash{$symbparm};
7649: untie(%parmhash);
7650: }
7651: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
7652: }
7653: # ------------------------------------------ fourth, look in resource metadata
7654:
7655: $spacequalifierrest=~s/\./\_/;
7656: my $filename;
7657: if (!$symbparm) { $symbparm=&symbread(); }
7658: if ($symbparm) {
7659: $filename=(&decode_symb($symbparm))[2];
7660: } else {
7661: $filename=$env{'request.filename'};
7662: }
7663: my $metadata=&metadata($filename,$spacequalifierrest);
7664: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7665: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
7666: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7667:
7668: # ---------------------------------------------- fourth, look in rest of course
7669: if ($symbparm && defined($courseid) &&
7670: $courseid eq $env{'request.course.id'}) {
7671: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7672: $env{'course.'.$courseid.'.domain'},
7673: 'course',
7674: ([$courselevelm,'map' ],
7675: [$courselevel, 'course']));
7676: if (defined($coursereply)) { return &get_reply($coursereply); }
7677: }
7678: # ------------------------------------------------------------------ Cascade up
7679: unless ($space eq '0') {
7680: my @parts=split(/_/,$space);
7681: my $id=pop(@parts);
7682: my $part=join('_',@parts);
7683: if ($part eq '') { $part='0'; }
7684: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
7685: $symbparm,$udom,$uname,$section,1);
7686: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
7687: }
7688: if ($recurse) { return undef; }
7689: my $pack_def=&packages_tab_default($filename,$varname);
7690: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
7691: # ---------------------------------------------------- Any other user namespace
7692: } elsif ($realm eq 'environment') {
7693: # ----------------------------------------------------------------- environment
7694: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7695: return $env{'environment.'.$spacequalifierrest};
7696: } else {
7697: if ($uname eq 'anonymous' && $udom eq '') {
7698: return '';
7699: }
7700: my %returnhash=&userenvironment($udom,$uname,
7701: $spacequalifierrest);
7702: return $returnhash{$spacequalifierrest};
7703: }
7704: } elsif ($realm eq 'system') {
7705: # ----------------------------------------------------------------- system.time
7706: if ($space eq 'time') {
7707: return time;
7708: }
7709: } elsif ($realm eq 'server') {
7710: # ----------------------------------------------------------------- system.time
7711: if ($space eq 'name') {
7712: return $ENV{'SERVER_NAME'};
7713: }
7714: }
7715: return '';
7716: }
7717:
7718: sub get_reply {
7719: my ($reply_value) = @_;
7720: if (ref($reply_value) eq 'ARRAY') {
7721: if (wantarray) {
7722: return @$reply_value;
7723: }
7724: return $reply_value->[0];
7725: } else {
7726: return $reply_value;
7727: }
7728: }
7729:
7730: sub check_group_parms {
7731: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7732: my @groupitems = ();
7733: my $resultitem;
7734: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
7735: foreach my $group (@{$groups}) {
7736: foreach my $level (@levels) {
7737: my $item = $courseid.'.['.$group.'].'.$level->[0];
7738: push(@groupitems,[$item,$level->[1]]);
7739: }
7740: }
7741: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7742: $env{'course.'.$courseid.'.domain'},
7743: 'course',@groupitems);
7744: return $coursereply;
7745: }
7746:
7747: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
7748: my ($courseid,@groups) = @_;
7749: @groups = sort(@groups);
7750: return @groups;
7751: }
7752:
7753: sub packages_tab_default {
7754: my ($uri,$varname)=@_;
7755: my (undef,$part,$name)=split(/\./,$varname);
7756:
7757: my (@extension,@specifics,$do_default);
7758: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
7759: my ($pack_type,$pack_part)=split(/_/,$package,2);
7760: if ($pack_type eq 'default') {
7761: $do_default=1;
7762: } elsif ($pack_type eq 'extension') {
7763: push(@extension,[$package,$pack_type,$pack_part]);
7764: } elsif ($pack_part eq $part || $pack_type eq 'part') {
7765: # only look at packages defaults for packages that this id is
7766: push(@specifics,[$package,$pack_type,$pack_part]);
7767: }
7768: }
7769: # first look for a package that matches the requested part id
7770: foreach my $package (@specifics) {
7771: my (undef,$pack_type,$pack_part)=@{$package};
7772: next if ($pack_part ne $part);
7773: if (defined($packagetab{"$pack_type&$name&default"})) {
7774: return $packagetab{"$pack_type&$name&default"};
7775: }
7776: }
7777: # look for any possible matching non extension_ package
7778: foreach my $package (@specifics) {
7779: my (undef,$pack_type,$pack_part)=@{$package};
7780: if (defined($packagetab{"$pack_type&$name&default"})) {
7781: return $packagetab{"$pack_type&$name&default"};
7782: }
7783: if ($pack_type eq 'part') { $pack_part='0'; }
7784: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7785: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
7786: }
7787: }
7788: # look for any posible extension_ match
7789: foreach my $package (@extension) {
7790: my ($package,$pack_type)=@{$package};
7791: if (defined($packagetab{"$pack_type&$name&default"})) {
7792: return $packagetab{"$pack_type&$name&default"};
7793: }
7794: if (defined($packagetab{$package."&$name&default"})) {
7795: return $packagetab{$package."&$name&default"};
7796: }
7797: }
7798: # look for a global default setting
7799: if ($do_default && defined($packagetab{"default&$name&default"})) {
7800: return $packagetab{"default&$name&default"};
7801: }
7802: return undef;
7803: }
7804:
7805: sub add_prefix_and_part {
7806: my ($prefix,$part)=@_;
7807: my $keyroot;
7808: if (defined($prefix) && $prefix !~ /^__/) {
7809: # prefix that has a part already
7810: $keyroot=$prefix;
7811: } elsif (defined($prefix)) {
7812: # prefix that is missing a part
7813: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7814: } else {
7815: # no prefix at all
7816: if (defined($part)) { $keyroot='_'.$part; }
7817: }
7818: return $keyroot;
7819: }
7820:
7821: # ---------------------------------------------------------------- Get metadata
7822:
7823: my %metaentry;
7824: sub metadata {
7825: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
7826: $uri=&declutter($uri);
7827: # if it is a non metadata possible uri return quickly
7828: if (($uri eq '') ||
7829: (($uri =~ m|^/*adm/|) &&
7830: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
7831: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7832: return undef;
7833: }
7834: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7835: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
7836: return undef;
7837: }
7838: my $filename=$uri;
7839: $uri=~s/\.meta$//;
7840: #
7841: # Is the metadata already cached?
7842: # Look at timestamp of caching
7843: # Everything is cached by the main uri, libraries are never directly cached
7844: #
7845: if (!defined($liburi)) {
7846: my ($result,$cached)=&is_cached_new('meta',$uri);
7847: if (defined($cached)) { return $result->{':'.$what}; }
7848: }
7849: {
7850: #
7851: # Is this a recursive call for a library?
7852: #
7853: # if (! exists($metacache{$uri})) {
7854: # $metacache{$uri}={};
7855: # }
7856: my $cachetime = 60*60;
7857: if ($liburi) {
7858: $liburi=&declutter($liburi);
7859: $filename=$liburi;
7860: } else {
7861: &devalidate_cache_new('meta',$uri);
7862: undef(%metaentry);
7863: }
7864: my %metathesekeys=();
7865: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
7866: my $metastring;
7867: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
7868: my $which = &hreflocation('','/'.($liburi || $uri));
7869: $metastring =
7870: &Apache::lonnet::ssi_body($which,
7871: ('grade_target' => 'meta'));
7872: $cachetime = 1; # only want this cached in the child not long term
7873: } elsif ($uri !~ m -^(editupload)/-) {
7874: my $file=&filelocation('',&clutter($filename));
7875: #push(@{$metaentry{$uri.'.file'}},$file);
7876: $metastring=&getfile($file);
7877: }
7878: my $parser=HTML::LCParser->new(\$metastring);
7879: my $token;
7880: undef %metathesekeys;
7881: while ($token=$parser->get_token) {
7882: if ($token->[0] eq 'S') {
7883: if (defined($token->[2]->{'package'})) {
7884: #
7885: # This is a package - get package info
7886: #
7887: my $package=$token->[2]->{'package'};
7888: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7889: if (defined($token->[2]->{'id'})) {
7890: $keyroot.='_'.$token->[2]->{'id'};
7891: }
7892: if ($metaentry{':packages'}) {
7893: $metaentry{':packages'}.=','.$package.$keyroot;
7894: } else {
7895: $metaentry{':packages'}=$package.$keyroot;
7896: }
7897: foreach my $pack_entry (keys(%packagetab)) {
7898: my $part=$keyroot;
7899: $part=~s/^\_//;
7900: if ($pack_entry=~/^\Q$package\E\&/ ||
7901: $pack_entry=~/^\Q$package\E_0\&/) {
7902: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
7903: # ignore package.tab specified default values
7904: # here &package_tab_default() will fetch those
7905: if ($subp eq 'default') { next; }
7906: my $value=$packagetab{$pack_entry};
7907: my $unikey;
7908: if ($pack =~ /_0$/) {
7909: $unikey='parameter_0_'.$name;
7910: $part=0;
7911: } else {
7912: $unikey='parameter'.$keyroot.'_'.$name;
7913: }
7914: if ($subp eq 'display') {
7915: $value.=' [Part: '.$part.']';
7916: }
7917: $metaentry{':'.$unikey.'.part'}=$part;
7918: $metathesekeys{$unikey}=1;
7919: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7920: $metaentry{':'.$unikey.'.'.$subp}=$value;
7921: }
7922: if (defined($metaentry{':'.$unikey.'.default'})) {
7923: $metaentry{':'.$unikey}=
7924: $metaentry{':'.$unikey.'.default'};
7925: }
7926: }
7927: }
7928: } else {
7929: #
7930: # This is not a package - some other kind of start tag
7931: #
7932: my $entry=$token->[1];
7933: my $unikey;
7934: if ($entry eq 'import') {
7935: $unikey='';
7936: } else {
7937: $unikey=$entry;
7938: }
7939: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7940:
7941: if (defined($token->[2]->{'id'})) {
7942: $unikey.='_'.$token->[2]->{'id'};
7943: }
7944:
7945: if ($entry eq 'import') {
7946: #
7947: # Importing a library here
7948: #
7949: if ($depthcount<20) {
7950: my $location=$parser->get_text('/import');
7951: my $dir=$filename;
7952: $dir=~s|[^/]*$||;
7953: $location=&filelocation($dir,$location);
7954: my $metadata =
7955: &metadata($uri,'keys', $location,$unikey,
7956: $depthcount+1);
7957: foreach my $meta (split(',',$metadata)) {
7958: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7959: $metathesekeys{$meta}=1;
7960: }
7961: }
7962: } else {
7963:
7964: if (defined($token->[2]->{'name'})) {
7965: $unikey.='_'.$token->[2]->{'name'};
7966: }
7967: $metathesekeys{$unikey}=1;
7968: foreach my $param (@{$token->[3]}) {
7969: $metaentry{':'.$unikey.'.'.$param} =
7970: $token->[2]->{$param};
7971: }
7972: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
7973: my $default=$metaentry{':'.$unikey.'.default'};
7974: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7975: # only ws inside the tag, and not in default, so use default
7976: # as value
7977: $metaentry{':'.$unikey}=$default;
7978: } elsif ( $internaltext =~ /\S/ ) {
7979: # something interesting inside the tag
7980: $metaentry{':'.$unikey}=$internaltext;
7981: } else {
7982: # no interesting values, don't set a default
7983: }
7984: # end of not-a-package not-a-library import
7985: }
7986: # end of not-a-package start tag
7987: }
7988: # the next is the end of "start tag"
7989: }
7990: }
7991: my ($extension) = ($uri =~ /\.(\w+)$/);
7992: $extension = lc($extension);
7993: if ($extension eq 'htm') { $extension='html'; }
7994:
7995: foreach my $key (keys(%packagetab)) {
7996: #no specific packages #how's our extension
7997: if ($key!~/^extension_\Q$extension\E&/) { next; }
7998: &metadata_create_package_def($uri,$key,'extension_'.$extension,
7999: \%metathesekeys);
8000: }
8001:
8002: if (!exists($metaentry{':packages'})
8003: || $packagetab{"import_defaults&extension_$extension"}) {
8004: foreach my $key (keys(%packagetab)) {
8005: #no specific packages well let's get default then
8006: if ($key!~/^default&/) { next; }
8007: &metadata_create_package_def($uri,$key,'default',
8008: \%metathesekeys);
8009: }
8010: }
8011: # are there custom rights to evaluate
8012: if ($metaentry{':copyright'} eq 'custom') {
8013:
8014: #
8015: # Importing a rights file here
8016: #
8017: unless ($depthcount) {
8018: my $location=$metaentry{':customdistributionfile'};
8019: my $dir=$filename;
8020: $dir=~s|[^/]*$||;
8021: $location=&filelocation($dir,$location);
8022: my $rights_metadata =
8023: &metadata($uri,'keys',$location,'_rights',
8024: $depthcount+1);
8025: foreach my $rights (split(',',$rights_metadata)) {
8026: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8027: $metathesekeys{$rights}=1;
8028: }
8029: }
8030: }
8031: # uniqifiy package listing
8032: my %seen;
8033: my @uniq_packages =
8034: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8035: $metaentry{':packages'} = join(',',@uniq_packages);
8036:
8037: $metaentry{':keys'} = join(',',keys(%metathesekeys));
8038: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8039: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
8040: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
8041: # this is the end of "was not already recently cached
8042: }
8043: return $metaentry{':'.$what};
8044: }
8045:
8046: sub metadata_create_package_def {
8047: my ($uri,$key,$package,$metathesekeys)=@_;
8048: my ($pack,$name,$subp)=split(/\&/,$key);
8049: if ($subp eq 'default') { next; }
8050:
8051: if (defined($metaentry{':packages'})) {
8052: $metaentry{':packages'}.=','.$package;
8053: } else {
8054: $metaentry{':packages'}=$package;
8055: }
8056: my $value=$packagetab{$key};
8057: my $unikey;
8058: $unikey='parameter_0_'.$name;
8059: $metaentry{':'.$unikey.'.part'}=0;
8060: $$metathesekeys{$unikey}=1;
8061: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8062: $metaentry{':'.$unikey.'.'.$subp}=$value;
8063: }
8064: if (defined($metaentry{':'.$unikey.'.default'})) {
8065: $metaentry{':'.$unikey}=
8066: $metaentry{':'.$unikey.'.default'};
8067: }
8068: }
8069:
8070: sub metadata_generate_part0 {
8071: my ($metadata,$metacache,$uri) = @_;
8072: my %allnames;
8073: foreach my $metakey (keys(%$metadata)) {
8074: if ($metakey=~/^parameter\_(.*)/) {
8075: my $part=$$metacache{':'.$metakey.'.part'};
8076: my $name=$$metacache{':'.$metakey.'.name'};
8077: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
8078: $allnames{$name}=$part;
8079: }
8080: }
8081: }
8082: foreach my $name (keys(%allnames)) {
8083: $$metadata{"parameter_0_$name"}=1;
8084: my $key=":parameter_0_$name";
8085: $$metacache{"$key.part"}='0';
8086: $$metacache{"$key.name"}=$name;
8087: $$metacache{"$key.type"}=$$metacache{':parameter_'.
8088: $allnames{$name}.'_'.$name.
8089: '.type'};
8090: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
8091: '.display'};
8092: my $expr='[Part: '.$allnames{$name}.']';
8093: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
8094: $$metacache{"$key.display"}=$olddis;
8095: }
8096: }
8097:
8098: # ------------------------------------------------------ Devalidate title cache
8099:
8100: sub devalidate_title_cache {
8101: my ($url)=@_;
8102: if (!$env{'request.course.id'}) { return; }
8103: my $symb=&symbread($url);
8104: if (!$symb) { return; }
8105: my $key=$env{'request.course.id'}."\0".$symb;
8106: &devalidate_cache_new('title',$key);
8107: }
8108:
8109: # ------------------------------------------------- Get the title of a course
8110:
8111: sub current_course_title {
8112: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8113: }
8114: # ------------------------------------------------- Get the title of a resource
8115:
8116: sub gettitle {
8117: my $urlsymb=shift;
8118: my $symb=&symbread($urlsymb);
8119: if ($symb) {
8120: my $key=$env{'request.course.id'}."\0".$symb;
8121: my ($result,$cached)=&is_cached_new('title',$key);
8122: if (defined($cached)) {
8123: return $result;
8124: }
8125: my ($map,$resid,$url)=&decode_symb($symb);
8126: my $title='';
8127: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8128: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8129: } else {
8130: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8131: &GDBM_READER(),0640)) {
8132: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8133: $title=$bighash{'title_'.$mapid.'.'.$resid};
8134: untie(%bighash);
8135: }
8136: }
8137: $title=~s/\&colon\;/\:/gs;
8138: if ($title) {
8139: return &do_cache_new('title',$key,$title,600);
8140: }
8141: $urlsymb=$url;
8142: }
8143: my $title=&metadata($urlsymb,'title');
8144: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8145: return $title;
8146: }
8147:
8148: sub get_slot {
8149: my ($which,$cnum,$cdom)=@_;
8150: if (!$cnum || !$cdom) {
8151: (undef,my $courseid)=&whichuser();
8152: $cdom=$env{'course.'.$courseid.'.domain'};
8153: $cnum=$env{'course.'.$courseid.'.num'};
8154: }
8155: my $key=join("\0",'slots',$cdom,$cnum,$which);
8156: my %slotinfo;
8157: if (exists($remembered{$key})) {
8158: $slotinfo{$which} = $remembered{$key};
8159: } else {
8160: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8161: &Apache::lonhomework::showhash(%slotinfo);
8162: my ($tmp)=keys(%slotinfo);
8163: if ($tmp=~/^error:/) { return (); }
8164: $remembered{$key} = $slotinfo{$which};
8165: }
8166: if (ref($slotinfo{$which}) eq 'HASH') {
8167: return %{$slotinfo{$which}};
8168: }
8169: return $slotinfo{$which};
8170: }
8171: # ------------------------------------------------- Update symbolic store links
8172:
8173: sub symblist {
8174: my ($mapname,%newhash)=@_;
8175: $mapname=&deversion(&declutter($mapname));
8176: my %hash;
8177: if (($env{'request.course.fn'}) && (%newhash)) {
8178: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8179: &GDBM_WRCREAT(),0640)) {
8180: foreach my $url (keys(%newhash)) {
8181: next if ($url eq 'last_known'
8182: && $env{'form.no_update_last_known'});
8183: $hash{declutter($url)}=&encode_symb($mapname,
8184: $newhash{$url}->[1],
8185: $newhash{$url}->[0]);
8186: }
8187: if (untie(%hash)) {
8188: return 'ok';
8189: }
8190: }
8191: }
8192: return 'error';
8193: }
8194:
8195: # --------------------------------------------------------------- Verify a symb
8196:
8197: sub symbverify {
8198: my ($symb,$thisurl)=@_;
8199: my $thisfn=$thisurl;
8200: $thisfn=&declutter($thisfn);
8201: # direct jump to resource in page or to a sequence - will construct own symbs
8202: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8203: # check URL part
8204: my ($map,$resid,$url)=&decode_symb($symb);
8205:
8206: unless ($url eq $thisfn) { return 0; }
8207:
8208: $symb=&symbclean($symb);
8209: $thisurl=&deversion($thisurl);
8210: $thisfn=&deversion($thisfn);
8211:
8212: my %bighash;
8213: my $okay=0;
8214:
8215: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8216: &GDBM_READER(),0640)) {
8217: my $ids=$bighash{'ids_'.&clutter($thisurl)};
8218: unless ($ids) {
8219: $ids=$bighash{'ids_/'.$thisurl};
8220: }
8221: if ($ids) {
8222: # ------------------------------------------------------------------- Has ID(s)
8223: foreach my $id (split(/\,/,$ids)) {
8224: my ($mapid,$resid)=split(/\./,$id);
8225: if (
8226: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8227: eq $symb) {
8228: if (($env{'request.role.adv'}) ||
8229: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
8230: $okay=1;
8231: }
8232: }
8233: }
8234: }
8235: untie(%bighash);
8236: }
8237: return $okay;
8238: }
8239:
8240: # --------------------------------------------------------------- Clean-up symb
8241:
8242: sub symbclean {
8243: my $symb=shift;
8244: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8245: # remove version from map
8246: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
8247:
8248: # remove version from URL
8249: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
8250:
8251: # remove wrapper
8252:
8253: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
8254: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
8255: return $symb;
8256: }
8257:
8258: # ---------------------------------------------- Split symb to find map and url
8259:
8260: sub encode_symb {
8261: my ($map,$resid,$url)=@_;
8262: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8263: }
8264:
8265: sub decode_symb {
8266: my $symb=shift;
8267: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8268: my ($map,$resid,$url)=split(/___/,$symb);
8269: return (&fixversion($map),$resid,&fixversion($url));
8270: }
8271:
8272: sub fixversion {
8273: my $fn=shift;
8274: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
8275: my %bighash;
8276: my $uri=&clutter($fn);
8277: my $key=$env{'request.course.id'}.'_'.$uri;
8278: # is this cached?
8279: my ($result,$cached)=&is_cached_new('courseresversion',$key);
8280: if (defined($cached)) { return $result; }
8281: # unfortunately not cached, or expired
8282: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8283: &GDBM_READER(),0640)) {
8284: if ($bighash{'version_'.$uri}) {
8285: my $version=$bighash{'version_'.$uri};
8286: unless (($version eq 'mostrecent') ||
8287: ($version==&getversion($uri))) {
8288: $uri=~s/\.(\w+)$/\.$version\.$1/;
8289: }
8290: }
8291: untie %bighash;
8292: }
8293: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
8294: }
8295:
8296: sub deversion {
8297: my $url=shift;
8298: $url=~s/\.\d+\.(\w+)$/\.$1/;
8299: return $url;
8300: }
8301:
8302: # ------------------------------------------------------ Return symb list entry
8303:
8304: sub symbread {
8305: my ($thisfn,$donotrecurse)=@_;
8306: my $cache_str='request.symbread.cached.'.$thisfn;
8307: if (defined($env{$cache_str})) { return $env{$cache_str}; }
8308: # no filename provided? try from environment
8309: unless ($thisfn) {
8310: if ($env{'request.symb'}) {
8311: return $env{$cache_str}=&symbclean($env{'request.symb'});
8312: }
8313: $thisfn=$env{'request.filename'};
8314: }
8315: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
8316: # is that filename actually a symb? Verify, clean, and return
8317: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
8318: if (&symbverify($thisfn,$1)) {
8319: return $env{$cache_str}=&symbclean($thisfn);
8320: }
8321: }
8322: $thisfn=declutter($thisfn);
8323: my %hash;
8324: my %bighash;
8325: my $syval='';
8326: if (($env{'request.course.fn'}) && ($thisfn)) {
8327: my $targetfn = $thisfn;
8328: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
8329: $targetfn = 'adm/wrapper/'.$thisfn;
8330: }
8331: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8332: $targetfn=$1;
8333: }
8334: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8335: &GDBM_READER(),0640)) {
8336: $syval=$hash{$targetfn};
8337: untie(%hash);
8338: }
8339: # ---------------------------------------------------------- There was an entry
8340: if ($syval) {
8341: #unless ($syval=~/\_\d+$/) {
8342: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
8343: #&appenv({'request.ambiguous' => $thisfn});
8344: #return $env{$cache_str}='';
8345: #}
8346: #$syval.=$1;
8347: #}
8348: } else {
8349: # ------------------------------------------------------- Was not in symb table
8350: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8351: &GDBM_READER(),0640)) {
8352: # ---------------------------------------------- Get ID(s) for current resource
8353: my $ids=$bighash{'ids_'.&clutter($thisfn)};
8354: unless ($ids) {
8355: $ids=$bighash{'ids_/'.$thisfn};
8356: }
8357: unless ($ids) {
8358: # alias?
8359: $ids=$bighash{'mapalias_'.$thisfn};
8360: }
8361: if ($ids) {
8362: # ------------------------------------------------------------------- Has ID(s)
8363: my @possibilities=split(/\,/,$ids);
8364: if ($#possibilities==0) {
8365: # ----------------------------------------------- There is only one possibility
8366: my ($mapid,$resid)=split(/\./,$ids);
8367: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8368: $resid,$thisfn);
8369: } elsif (!$donotrecurse) {
8370: # ------------------------------------------ There is more than one possibility
8371: my $realpossible=0;
8372: foreach my $id (@possibilities) {
8373: my $file=$bighash{'src_'.$id};
8374: if (&allowed('bre',$file)) {
8375: my ($mapid,$resid)=split(/\./,$id);
8376: if ($bighash{'map_type_'.$mapid} ne 'page') {
8377: $realpossible++;
8378: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8379: $resid,$thisfn);
8380: }
8381: }
8382: }
8383: if ($realpossible!=1) { $syval=''; }
8384: } else {
8385: $syval='';
8386: }
8387: }
8388: untie(%bighash)
8389: }
8390: }
8391: if ($syval) {
8392: return $env{$cache_str}=$syval;
8393: }
8394: }
8395: &appenv({'request.ambiguous' => $thisfn});
8396: return $env{$cache_str}='';
8397: }
8398:
8399: # ---------------------------------------------------------- Return random seed
8400:
8401: sub numval {
8402: my $txt=shift;
8403: $txt=~tr/A-J/0-9/;
8404: $txt=~tr/a-j/0-9/;
8405: $txt=~tr/K-T/0-9/;
8406: $txt=~tr/k-t/0-9/;
8407: $txt=~tr/U-Z/0-5/;
8408: $txt=~tr/u-z/0-5/;
8409: $txt=~s/\D//g;
8410: if ($_64bit) { if ($txt > 2**32) { return -1; } }
8411: return int($txt);
8412: }
8413:
8414: sub numval2 {
8415: my $txt=shift;
8416: $txt=~tr/A-J/0-9/;
8417: $txt=~tr/a-j/0-9/;
8418: $txt=~tr/K-T/0-9/;
8419: $txt=~tr/k-t/0-9/;
8420: $txt=~tr/U-Z/0-5/;
8421: $txt=~tr/u-z/0-5/;
8422: $txt=~s/\D//g;
8423: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8424: my $total;
8425: foreach my $val (@txts) { $total+=$val; }
8426: if ($_64bit) { if ($total > 2**32) { return -1; } }
8427: return int($total);
8428: }
8429:
8430: sub numval3 {
8431: use integer;
8432: my $txt=shift;
8433: $txt=~tr/A-J/0-9/;
8434: $txt=~tr/a-j/0-9/;
8435: $txt=~tr/K-T/0-9/;
8436: $txt=~tr/k-t/0-9/;
8437: $txt=~tr/U-Z/0-5/;
8438: $txt=~tr/u-z/0-5/;
8439: $txt=~s/\D//g;
8440: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8441: my $total;
8442: foreach my $val (@txts) { $total+=$val; }
8443: if ($_64bit) { $total=(($total<<32)>>32); }
8444: return $total;
8445: }
8446:
8447: sub digest {
8448: my ($data)=@_;
8449: my $digest=&Digest::MD5::md5($data);
8450: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8451: my ($e,$f);
8452: {
8453: use integer;
8454: $e=($a+$b);
8455: $f=($c+$d);
8456: if ($_64bit) {
8457: $e=(($e<<32)>>32);
8458: $f=(($f<<32)>>32);
8459: }
8460: }
8461: if (wantarray) {
8462: return ($e,$f);
8463: } else {
8464: my $g;
8465: {
8466: use integer;
8467: $g=($e+$f);
8468: if ($_64bit) {
8469: $g=(($g<<32)>>32);
8470: }
8471: }
8472: return $g;
8473: }
8474: }
8475:
8476: sub latest_rnd_algorithm_id {
8477: return '64bit5';
8478: }
8479:
8480: sub get_rand_alg {
8481: my ($courseid)=@_;
8482: if (!$courseid) { $courseid=(&whichuser())[1]; }
8483: if ($courseid) {
8484: return $env{"course.$courseid.rndseed"};
8485: }
8486: return &latest_rnd_algorithm_id();
8487: }
8488:
8489: sub validCODE {
8490: my ($CODE)=@_;
8491: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8492: return 0;
8493: }
8494:
8495: sub getCODE {
8496: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
8497: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8498: defined($Apache::lonhomework::parsing_a_task) ) &&
8499: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
8500: return $Apache::lonhomework::history{'resource.CODE'};
8501: }
8502: return undef;
8503: }
8504:
8505: sub rndseed {
8506: my ($symb,$courseid,$domain,$username)=@_;
8507: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
8508: if (!defined($symb)) {
8509: unless ($symb=$wsymb) { return time; }
8510: }
8511: if (!$courseid) { $courseid=$wcourseid; }
8512: if (!$domain) { $domain=$wdomain; }
8513: if (!$username) { $username=$wusername }
8514: my $which=&get_rand_alg();
8515:
8516: if (defined(&getCODE())) {
8517: if ($which eq '64bit5') {
8518: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8519: } elsif ($which eq '64bit4') {
8520: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8521: } else {
8522: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8523: }
8524: } elsif ($which eq '64bit5') {
8525: return &rndseed_64bit5($symb,$courseid,$domain,$username);
8526: } elsif ($which eq '64bit4') {
8527: return &rndseed_64bit4($symb,$courseid,$domain,$username);
8528: } elsif ($which eq '64bit3') {
8529: return &rndseed_64bit3($symb,$courseid,$domain,$username);
8530: } elsif ($which eq '64bit2') {
8531: return &rndseed_64bit2($symb,$courseid,$domain,$username);
8532: } elsif ($which eq '64bit') {
8533: return &rndseed_64bit($symb,$courseid,$domain,$username);
8534: }
8535: return &rndseed_32bit($symb,$courseid,$domain,$username);
8536: }
8537:
8538: sub rndseed_32bit {
8539: my ($symb,$courseid,$domain,$username)=@_;
8540: {
8541: use integer;
8542: my $symbchck=unpack("%32C*",$symb) << 27;
8543: my $symbseed=numval($symb) << 22;
8544: my $namechck=unpack("%32C*",$username) << 17;
8545: my $nameseed=numval($username) << 12;
8546: my $domainseed=unpack("%32C*",$domain) << 7;
8547: my $courseseed=unpack("%32C*",$courseid);
8548: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
8549: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8550: #&logthis("rndseed :$num:$symb");
8551: if ($_64bit) { $num=(($num<<32)>>32); }
8552: return $num;
8553: }
8554: }
8555:
8556: sub rndseed_64bit {
8557: my ($symb,$courseid,$domain,$username)=@_;
8558: {
8559: use integer;
8560: my $symbchck=unpack("%32S*",$symb) << 21;
8561: my $symbseed=numval($symb) << 10;
8562: my $namechck=unpack("%32S*",$username);
8563:
8564: my $nameseed=numval($username) << 21;
8565: my $domainseed=unpack("%32S*",$domain) << 10;
8566: my $courseseed=unpack("%32S*",$courseid);
8567:
8568: my $num1=$symbchck+$symbseed+$namechck;
8569: my $num2=$nameseed+$domainseed+$courseseed;
8570: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8571: #&logthis("rndseed :$num:$symb");
8572: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8573: return "$num1,$num2";
8574: }
8575: }
8576:
8577: sub rndseed_64bit2 {
8578: my ($symb,$courseid,$domain,$username)=@_;
8579: {
8580: use integer;
8581: # strings need to be an even # of cahracters long, it it is odd the
8582: # last characters gets thrown away
8583: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8584: my $symbseed=numval($symb) << 10;
8585: my $namechck=unpack("%32S*",$username.' ');
8586:
8587: my $nameseed=numval($username) << 21;
8588: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8589: my $courseseed=unpack("%32S*",$courseid.' ');
8590:
8591: my $num1=$symbchck+$symbseed+$namechck;
8592: my $num2=$nameseed+$domainseed+$courseseed;
8593: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8594: #&logthis("rndseed :$num:$symb");
8595: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8596: return "$num1,$num2";
8597: }
8598: }
8599:
8600: sub rndseed_64bit3 {
8601: my ($symb,$courseid,$domain,$username)=@_;
8602: {
8603: use integer;
8604: # strings need to be an even # of cahracters long, it it is odd the
8605: # last characters gets thrown away
8606: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8607: my $symbseed=numval2($symb) << 10;
8608: my $namechck=unpack("%32S*",$username.' ');
8609:
8610: my $nameseed=numval2($username) << 21;
8611: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8612: my $courseseed=unpack("%32S*",$courseid.' ');
8613:
8614: my $num1=$symbchck+$symbseed+$namechck;
8615: my $num2=$nameseed+$domainseed+$courseseed;
8616: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8617: #&logthis("rndseed :$num1:$num2:$_64bit");
8618: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8619:
8620: return "$num1:$num2";
8621: }
8622: }
8623:
8624: sub rndseed_64bit4 {
8625: my ($symb,$courseid,$domain,$username)=@_;
8626: {
8627: use integer;
8628: # strings need to be an even # of cahracters long, it it is odd the
8629: # last characters gets thrown away
8630: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8631: my $symbseed=numval3($symb) << 10;
8632: my $namechck=unpack("%32S*",$username.' ');
8633:
8634: my $nameseed=numval3($username) << 21;
8635: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8636: my $courseseed=unpack("%32S*",$courseid.' ');
8637:
8638: my $num1=$symbchck+$symbseed+$namechck;
8639: my $num2=$nameseed+$domainseed+$courseseed;
8640: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8641: #&logthis("rndseed :$num1:$num2:$_64bit");
8642: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8643:
8644: return "$num1:$num2";
8645: }
8646: }
8647:
8648: sub rndseed_64bit5 {
8649: my ($symb,$courseid,$domain,$username)=@_;
8650: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8651: return "$num1:$num2";
8652: }
8653:
8654: sub rndseed_CODE_64bit {
8655: my ($symb,$courseid,$domain,$username)=@_;
8656: {
8657: use integer;
8658: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8659: my $symbseed=numval2($symb);
8660: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8661: my $CODEseed=numval(&getCODE());
8662: my $courseseed=unpack("%32S*",$courseid.' ');
8663: my $num1=$symbseed+$CODEchck;
8664: my $num2=$CODEseed+$courseseed+$symbchck;
8665: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8666: #&logthis("rndseed :$num1:$num2:$symb");
8667: if ($_64bit) { $num1=(($num1<<32)>>32); }
8668: if ($_64bit) { $num2=(($num2<<32)>>32); }
8669: return "$num1:$num2";
8670: }
8671: }
8672:
8673: sub rndseed_CODE_64bit4 {
8674: my ($symb,$courseid,$domain,$username)=@_;
8675: {
8676: use integer;
8677: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8678: my $symbseed=numval3($symb);
8679: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8680: my $CODEseed=numval3(&getCODE());
8681: my $courseseed=unpack("%32S*",$courseid.' ');
8682: my $num1=$symbseed+$CODEchck;
8683: my $num2=$CODEseed+$courseseed+$symbchck;
8684: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8685: #&logthis("rndseed :$num1:$num2:$symb");
8686: if ($_64bit) { $num1=(($num1<<32)>>32); }
8687: if ($_64bit) { $num2=(($num2<<32)>>32); }
8688: return "$num1:$num2";
8689: }
8690: }
8691:
8692: sub rndseed_CODE_64bit5 {
8693: my ($symb,$courseid,$domain,$username)=@_;
8694: my $code = &getCODE();
8695: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8696: return "$num1:$num2";
8697: }
8698:
8699: sub setup_random_from_rndseed {
8700: my ($rndseed)=@_;
8701: if ($rndseed =~/([,:])/) {
8702: my ($num1,$num2)=split(/[,:]/,$rndseed);
8703: &Math::Random::random_set_seed(abs($num1),abs($num2));
8704: } else {
8705: &Math::Random::random_set_seed_from_phrase($rndseed);
8706: }
8707: }
8708:
8709: sub latest_receipt_algorithm_id {
8710: return 'receipt3';
8711: }
8712:
8713: sub recunique {
8714: my $fucourseid=shift;
8715: my $unique;
8716: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8717: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8718: $unique=$env{"course.$fucourseid.internal.encseed"};
8719: } else {
8720: $unique=$perlvar{'lonReceipt'};
8721: }
8722: return unpack("%32C*",$unique);
8723: }
8724:
8725: sub recprefix {
8726: my $fucourseid=shift;
8727: my $prefix;
8728: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8729: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8730: $prefix=$env{"course.$fucourseid.internal.encpref"};
8731: } else {
8732: $prefix=$perlvar{'lonHostID'};
8733: }
8734: return unpack("%32C*",$prefix);
8735: }
8736:
8737: sub ireceipt {
8738: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
8739:
8740: my $return =&recprefix($fucourseid).'-';
8741:
8742: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8743: $env{'request.state'} eq 'construct') {
8744: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8745: return $return;
8746: }
8747:
8748: my $cuname=unpack("%32C*",$funame);
8749: my $cudom=unpack("%32C*",$fudom);
8750: my $cucourseid=unpack("%32C*",$fucourseid);
8751: my $cusymb=unpack("%32C*",$fusymb);
8752: my $cunique=&recunique($fucourseid);
8753: my $cpart=unpack("%32S*",$part);
8754: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8755:
8756: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
8757:
8758: $return.= ($cunique%$cuname+
8759: $cunique%$cudom+
8760: $cusymb%$cuname+
8761: $cusymb%$cudom+
8762: $cucourseid%$cuname+
8763: $cucourseid%$cudom+
8764: $cpart%$cuname+
8765: $cpart%$cudom);
8766: } else {
8767: $return.= ($cunique%$cuname+
8768: $cunique%$cudom+
8769: $cusymb%$cuname+
8770: $cusymb%$cudom+
8771: $cucourseid%$cuname+
8772: $cucourseid%$cudom);
8773: }
8774: return $return;
8775: }
8776:
8777: sub receipt {
8778: my ($part)=@_;
8779: my ($symb,$courseid,$domain,$name) = &whichuser();
8780: return &ireceipt($name,$domain,$courseid,$symb,$part);
8781: }
8782:
8783: sub whichuser {
8784: my ($passedsymb)=@_;
8785: my ($symb,$courseid,$domain,$name,$publicuser);
8786: if (defined($env{'form.grade_symb'})) {
8787: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8788: my $allowed=&allowed('vgr',$tmp_courseid);
8789: if (!$allowed &&
8790: exists($env{'request.course.sec'}) &&
8791: $env{'request.course.sec'} !~ /^\s*$/) {
8792: $allowed=&allowed('vgr',$tmp_courseid.
8793: '/'.$env{'request.course.sec'});
8794: }
8795: if ($allowed) {
8796: ($symb)=&get_env_multiple('form.grade_symb');
8797: $courseid=$tmp_courseid;
8798: ($domain)=&get_env_multiple('form.grade_domain');
8799: ($name)=&get_env_multiple('form.grade_username');
8800: return ($symb,$courseid,$domain,$name,$publicuser);
8801: }
8802: }
8803: if (!$passedsymb) {
8804: $symb=&symbread();
8805: } else {
8806: $symb=$passedsymb;
8807: }
8808: $courseid=$env{'request.course.id'};
8809: $domain=$env{'user.domain'};
8810: $name=$env{'user.name'};
8811: if ($name eq 'public' && $domain eq 'public') {
8812: if (!defined($env{'form.username'})) {
8813: $env{'form.username'}.=time.rand(10000000);
8814: }
8815: $name.=$env{'form.username'};
8816: }
8817: return ($symb,$courseid,$domain,$name,$publicuser);
8818:
8819: }
8820:
8821: # ------------------------------------------------------------ Serves up a file
8822: # returns either the contents of the file or
8823: # -1 if the file doesn't exist
8824: #
8825: # if the target is a file that was uploaded via DOCS,
8826: # a check will be made to see if a current copy exists on the local server,
8827: # if it does this will be served, otherwise a copy will be retrieved from
8828: # the home server for the course and stored in /home/httpd/html/userfiles on
8829: # the local server.
8830:
8831: sub getfile {
8832: my ($file) = @_;
8833: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8834: &repcopy($file);
8835: return &readfile($file);
8836: }
8837:
8838: sub repcopy_userfile {
8839: my ($file)=@_;
8840: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8841: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
8842: my ($cdom,$cnum,$filename) =
8843: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
8844: my $uri="/uploaded/$cdom/$cnum/$filename";
8845: if (-e "$file") {
8846: # we already have a local copy, check it out
8847: my @fileinfo = stat($file);
8848: my $rtncode;
8849: my $info;
8850: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
8851: if ($lwpresp ne 'ok') {
8852: # there is no such file anymore, even though we had a local copy
8853: if ($rtncode eq '404') {
8854: unlink($file);
8855: }
8856: return -1;
8857: }
8858: if ($info < $fileinfo[9]) {
8859: # nice, the file we have is up-to-date, just say okay
8860: return 'ok';
8861: } else {
8862: # the file is outdated, get rid of it
8863: unlink($file);
8864: }
8865: }
8866: # one way or the other, at this point, we don't have the file
8867: # construct the correct path for the file
8868: my @parts = ($cdom,$cnum);
8869: if ($filename =~ m|^(.+)/[^/]+$|) {
8870: push @parts, split(/\//,$1);
8871: }
8872: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8873: foreach my $part (@parts) {
8874: $path .= '/'.$part;
8875: if (!-e $path) {
8876: mkdir($path,0770);
8877: }
8878: }
8879: # now the path exists for sure
8880: # get a user agent
8881: my $ua=new LWP::UserAgent;
8882: my $transferfile=$file.'.in.transfer';
8883: # FIXME: this should flock
8884: if (-e $transferfile) { return 'ok'; }
8885: my $request;
8886: $uri=~s/^\///;
8887: my $homeserver = &homeserver($cnum,$cdom);
8888: my $protocol = $protocol{$homeserver};
8889: $protocol = 'http' if ($protocol ne 'https');
8890: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
8891: my $response=$ua->request($request,$transferfile);
8892: # did it work?
8893: if ($response->is_error()) {
8894: unlink($transferfile);
8895: &logthis("Userfile repcopy failed for $uri");
8896: return -1;
8897: }
8898: # worked, rename the transfer file
8899: rename($transferfile,$file);
8900: return 'ok';
8901: }
8902:
8903: sub tokenwrapper {
8904: my $uri=shift;
8905: $uri=~s|^https?\://([^/]+)||;
8906: $uri=~s|^/||;
8907: $env{'user.environment'}=~/\/([^\/]+)\.id/;
8908: my $token=$1;
8909: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8910: if ($udom && $uname && $file) {
8911: $file=~s|(\?\.*)*$||;
8912: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
8913: my $homeserver = &homeserver($uname,$udom);
8914: my $protocol = $protocol{$homeserver};
8915: $protocol = 'http' if ($protocol ne 'https');
8916: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
8917: (($uri=~/\?/)?'&':'?').'token='.$token.
8918: '&tokenissued='.$perlvar{'lonHostID'};
8919: } else {
8920: return '/adm/notfound.html';
8921: }
8922: }
8923:
8924: # call with reqtype HEAD: get last modification time
8925: # call with reqtype GET: get the file contents
8926: # Do not call this with reqtype GET for large files! It loads everything into memory
8927: #
8928: sub getuploaded {
8929: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8930: $uri=~s/^\///;
8931: my $homeserver = &homeserver($cnum,$cdom);
8932: my $protocol = $protocol{$homeserver};
8933: $protocol = 'http' if ($protocol ne 'https');
8934: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
8935: my $ua=new LWP::UserAgent;
8936: my $request=new HTTP::Request($reqtype,$uri);
8937: my $response=$ua->request($request);
8938: $$rtncode = $response->code;
8939: if (! $response->is_success()) {
8940: return 'failed';
8941: }
8942: if ($reqtype eq 'HEAD') {
8943: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
8944: } elsif ($reqtype eq 'GET') {
8945: $$info = $response->content;
8946: }
8947: return 'ok';
8948: }
8949:
8950: sub readfile {
8951: my $file = shift;
8952: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8953: my $fh;
8954: open($fh,"<$file");
8955: my $a='';
8956: while (my $line = <$fh>) { $a .= $line; }
8957: return $a;
8958: }
8959:
8960: sub filelocation {
8961: my ($dir,$file) = @_;
8962: my $location;
8963: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
8964:
8965: if ($file =~ m-^/adm/-) {
8966: $file=~s-^/adm/wrapper/-/-;
8967: $file=~s-^/adm/coursedocs/showdoc/-/-;
8968: }
8969:
8970: if ($file=~m:^/~:) { # is a contruction space reference
8971: $location = $file;
8972: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
8973: } elsif ($file=~m{^/home/$match_username/public_html/}) {
8974: # is a correct contruction space reference
8975: $location = $file;
8976: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8977: $location = $file;
8978: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
8979: my ($udom,$uname,$filename)=
8980: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
8981: my $home=&homeserver($uname,$udom);
8982: my $is_me=0;
8983: my @ids=¤t_machine_ids();
8984: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8985: if ($is_me) {
8986: $location=&propath($udom,$uname).'/userfiles/'.$filename;
8987: } else {
8988: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8989: $udom.'/'.$uname.'/'.$filename;
8990: }
8991: } elsif ($file =~ m-^/adm/-) {
8992: $location = $perlvar{'lonDocRoot'}.'/'.$file;
8993: } else {
8994: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8995: $file=~s:^/res/:/:;
8996: if ( !( $file =~ m:^/:) ) {
8997: $location = $dir. '/'.$file;
8998: } else {
8999: $location = '/home/httpd/html/res'.$file;
9000: }
9001: }
9002: $location=~s://+:/:g; # remove duplicate /
9003: while ($location=~m{/\.\./}) {
9004: if ($location =~ m{/[^/]+/\.\./}) {
9005: $location=~ s{/[^/]+/\.\./}{/}g;
9006: } else {
9007: $location=~ s{/\.\./}{/}g;
9008: }
9009: } #remove dir/..
9010: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9011: return $location;
9012: }
9013:
9014: sub hreflocation {
9015: my ($dir,$file)=@_;
9016: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
9017: $file=filelocation($dir,$file);
9018: } elsif ($file=~m-^/adm/-) {
9019: $file=~s-^/adm/wrapper/-/-;
9020: $file=~s-^/adm/coursedocs/showdoc/-/-;
9021: }
9022: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9023: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
9024: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9025: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
9026: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
9027: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
9028: -/uploaded/$1/$2/-x;
9029: }
9030: if ($file=~ m{^/userfiles/}) {
9031: $file =~ s{^/userfiles/}{/uploaded/};
9032: }
9033: return $file;
9034: }
9035:
9036: sub current_machine_domains {
9037: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9038: }
9039:
9040: sub machine_domains {
9041: my ($hostname) = @_;
9042: my @domains;
9043: my %hostname = &all_hostnames();
9044: while( my($id, $name) = each(%hostname)) {
9045: # &logthis("-$id-$name-$hostname-");
9046: if ($hostname eq $name) {
9047: push(@domains,&host_domain($id));
9048: }
9049: }
9050: return @domains;
9051: }
9052:
9053: sub current_machine_ids {
9054: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9055: }
9056:
9057: sub machine_ids {
9058: my ($hostname) = @_;
9059: $hostname ||= &hostname($perlvar{'lonHostID'});
9060: my @ids;
9061: my %name_to_host = &all_names();
9062: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9063: return @{ $name_to_host{$hostname} };
9064: }
9065: return;
9066: }
9067:
9068: sub additional_machine_domains {
9069: my @domains;
9070: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9071: while( my $line = <$fh>) {
9072: $line =~ s/\s//g;
9073: push(@domains,$line);
9074: }
9075: return @domains;
9076: }
9077:
9078: sub default_login_domain {
9079: my $domain = $perlvar{'lonDefDomain'};
9080: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9081: foreach my $posdom (¤t_machine_domains(),
9082: &additional_machine_domains()) {
9083: if (lc($posdom) eq lc($testdomain)) {
9084: $domain=$posdom;
9085: last;
9086: }
9087: }
9088: return $domain;
9089: }
9090:
9091: # ------------------------------------------------------------- Declutters URLs
9092:
9093: sub declutter {
9094: my $thisfn=shift;
9095: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9096: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9097: $thisfn=~s/^\///;
9098: $thisfn=~s|^adm/wrapper/||;
9099: $thisfn=~s|^adm/coursedocs/showdoc/||;
9100: $thisfn=~s/^res\///;
9101: $thisfn=~s/\?.+$//;
9102: return $thisfn;
9103: }
9104:
9105: # ------------------------------------------------------------- Clutter up URLs
9106:
9107: sub clutter {
9108: my $thisfn='/'.&declutter(shift);
9109: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
9110: || $thisfn =~ m{^/adm/(includes|pages)} ) {
9111: $thisfn='/res'.$thisfn;
9112: }
9113: if ($thisfn !~m|/adm|) {
9114: if ($thisfn =~ m|/ext/|) {
9115: $thisfn='/adm/wrapper'.$thisfn;
9116: } else {
9117: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9118: my $embstyle=&Apache::loncommon::fileembstyle($ext);
9119: if ($embstyle eq 'ssi'
9120: || ($embstyle eq 'hdn')
9121: || ($embstyle eq 'rat')
9122: || ($embstyle eq 'prv')
9123: || ($embstyle eq 'ign')) {
9124: #do nothing with these
9125: } elsif (($embstyle eq 'img')
9126: || ($embstyle eq 'emb')
9127: || ($embstyle eq 'wrp')) {
9128: $thisfn='/adm/wrapper'.$thisfn;
9129: } elsif ($embstyle eq 'unk'
9130: && $thisfn!~/\.(sequence|page)$/) {
9131: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
9132: } else {
9133: # &logthis("Got a blank emb style");
9134: }
9135: }
9136: }
9137: return $thisfn;
9138: }
9139:
9140: sub clutter_with_no_wrapper {
9141: my $uri = &clutter(shift);
9142: if ($uri =~ m-^/adm/-) {
9143: $uri =~ s-^/adm/wrapper/-/-;
9144: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9145: }
9146: return $uri;
9147: }
9148:
9149: sub freeze_escape {
9150: my ($value)=@_;
9151: if (ref($value)) {
9152: $value=&nfreeze($value);
9153: return '__FROZEN__'.&escape($value);
9154: }
9155: return &escape($value);
9156: }
9157:
9158:
9159: sub thaw_unescape {
9160: my ($value)=@_;
9161: if ($value =~ /^__FROZEN__/) {
9162: substr($value,0,10,undef);
9163: $value=&unescape($value);
9164: return &thaw($value);
9165: }
9166: return &unescape($value);
9167: }
9168:
9169: sub correct_line_ends {
9170: my ($result)=@_;
9171: $$result =~s/\r\n/\n/mg;
9172: $$result =~s/\r/\n/mg;
9173: }
9174: # ================================================================ Main Program
9175:
9176: sub goodbye {
9177: &logthis("Starting Shut down");
9178: #not converted to using infrastruture and probably shouldn't be
9179: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
9180: #converted
9181: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
9182: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9183: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9184: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
9185: #1.1 only
9186: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9187: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9188: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9189: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9190: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
9191: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9192: &logthis(sprintf("%-20s is %s",'hits',$hits));
9193: &flushcourselogs();
9194: &logthis("Shutting down");
9195: }
9196:
9197: sub get_dns {
9198: my ($url,$func,$ignore_cache) = @_;
9199: if (!$ignore_cache) {
9200: my ($content,$cached)=
9201: &Apache::lonnet::is_cached_new('dns',$url);
9202: if ($cached) {
9203: &$func($content);
9204: return;
9205: }
9206: }
9207:
9208: my %alldns;
9209: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9210: foreach my $dns (<$config>) {
9211: next if ($dns !~ /^\^(\S*)/x);
9212: my $line = $1;
9213: my ($host,$protocol) = split(/:/,$line);
9214: if ($protocol ne 'https') {
9215: $protocol = 'http';
9216: }
9217: $alldns{$host} = $protocol;
9218: }
9219: while (%alldns) {
9220: my ($dns) = keys(%alldns);
9221: my $ua=new LWP::UserAgent;
9222: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
9223: my $response=$ua->request($request);
9224: delete($alldns{$dns});
9225: next if ($response->is_error());
9226: my @content = split("\n",$response->content);
9227: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
9228: &$func(\@content);
9229: return;
9230: }
9231: close($config);
9232: my $which = (split('/',$url))[3];
9233: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9234: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
9235: my @content = <$config>;
9236: &$func(\@content);
9237: return;
9238: }
9239: # ------------------------------------------------------------ Read domain file
9240: {
9241: my $loaded;
9242: my %domain;
9243:
9244: sub parse_domain_tab {
9245: my ($lines) = @_;
9246: foreach my $line (@$lines) {
9247: next if ($line =~ /^(\#|\s*$ )/x);
9248:
9249: chomp($line);
9250: my ($name,@elements) = split(/:/,$line,9);
9251: my %this_domain;
9252: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9253: 'lang_def', 'city', 'longi', 'lati',
9254: 'primary') {
9255: $this_domain{$field} = shift(@elements);
9256: }
9257: $domain{$name} = \%this_domain;
9258: }
9259: }
9260:
9261: sub reset_domain_info {
9262: undef($loaded);
9263: undef(%domain);
9264: }
9265:
9266: sub load_domain_tab {
9267: my ($ignore_cache) = @_;
9268: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
9269: my $fh;
9270: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9271: my @lines = <$fh>;
9272: &parse_domain_tab(\@lines);
9273: }
9274: close($fh);
9275: $loaded = 1;
9276: }
9277:
9278: sub domain {
9279: &load_domain_tab() if (!$loaded);
9280:
9281: my ($name,$what) = @_;
9282: return if ( !exists($domain{$name}) );
9283:
9284: if (!$what) {
9285: return $domain{$name}{'description'};
9286: }
9287: return $domain{$name}{$what};
9288: }
9289:
9290: sub domain_info {
9291: &load_domain_tab() if (!$loaded);
9292: return %domain;
9293: }
9294:
9295: }
9296:
9297:
9298: # ------------------------------------------------------------- Read hosts file
9299: {
9300: my %hostname;
9301: my %hostdom;
9302: my %libserv;
9303: my $loaded;
9304: my %name_to_host;
9305:
9306: sub parse_hosts_tab {
9307: my ($file) = @_;
9308: foreach my $configline (@$file) {
9309: next if ($configline =~ /^(\#|\s*$ )/x);
9310: next if ($configline =~ /^\^/);
9311: chomp($configline);
9312: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
9313: $name=~s/\s//g;
9314: if ($id && $domain && $role && $name) {
9315: $hostname{$id}=$name;
9316: push(@{$name_to_host{$name}}, $id);
9317: $hostdom{$id}=$domain;
9318: if ($role eq 'library') { $libserv{$id}=$name; }
9319: if (defined($protocol)) {
9320: if ($protocol eq 'https') {
9321: $protocol{$id} = $protocol;
9322: } else {
9323: $protocol{$id} = 'http';
9324: }
9325: } else {
9326: $protocol{$id} = 'http';
9327: }
9328: }
9329: }
9330: }
9331:
9332: sub reset_hosts_info {
9333: &purge_remembered();
9334: &reset_domain_info();
9335: &reset_hosts_ip_info();
9336: undef(%name_to_host);
9337: undef(%hostname);
9338: undef(%hostdom);
9339: undef(%libserv);
9340: undef($loaded);
9341: }
9342:
9343: sub load_hosts_tab {
9344: my ($ignore_cache) = @_;
9345: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
9346: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9347: my @config = <$config>;
9348: &parse_hosts_tab(\@config);
9349: close($config);
9350: $loaded=1;
9351: }
9352:
9353: sub hostname {
9354: &load_hosts_tab() if (!$loaded);
9355:
9356: my ($lonid) = @_;
9357: return $hostname{$lonid};
9358: }
9359:
9360: sub all_hostnames {
9361: &load_hosts_tab() if (!$loaded);
9362:
9363: return %hostname;
9364: }
9365:
9366: sub all_names {
9367: &load_hosts_tab() if (!$loaded);
9368:
9369: return %name_to_host;
9370: }
9371:
9372: sub all_host_domain {
9373: &load_hosts_tab() if (!$loaded);
9374: return %hostdom;
9375: }
9376:
9377: sub is_library {
9378: &load_hosts_tab() if (!$loaded);
9379:
9380: return exists($libserv{$_[0]});
9381: }
9382:
9383: sub all_library {
9384: &load_hosts_tab() if (!$loaded);
9385:
9386: return %libserv;
9387: }
9388:
9389: sub get_servers {
9390: &load_hosts_tab() if (!$loaded);
9391:
9392: my ($domain,$type) = @_;
9393: my %possible_hosts = ($type eq 'library') ? %libserv
9394: : %hostname;
9395: my %result;
9396: if (ref($domain) eq 'ARRAY') {
9397: while ( my ($host,$hostname) = each(%possible_hosts)) {
9398: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
9399: $result{$host} = $hostname;
9400: }
9401: }
9402: } else {
9403: while ( my ($host,$hostname) = each(%possible_hosts)) {
9404: if ($hostdom{$host} eq $domain) {
9405: $result{$host} = $hostname;
9406: }
9407: }
9408: }
9409: return %result;
9410: }
9411:
9412: sub host_domain {
9413: &load_hosts_tab() if (!$loaded);
9414:
9415: my ($lonid) = @_;
9416: return $hostdom{$lonid};
9417: }
9418:
9419: sub all_domains {
9420: &load_hosts_tab() if (!$loaded);
9421:
9422: my %seen;
9423: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9424: return @uniq;
9425: }
9426: }
9427:
9428: {
9429: my %iphost;
9430: my %name_to_ip;
9431: my %lonid_to_ip;
9432:
9433: sub get_hosts_from_ip {
9434: my ($ip) = @_;
9435: my %iphosts = &get_iphost();
9436: if (ref($iphosts{$ip})) {
9437: return @{$iphosts{$ip}};
9438: }
9439: return;
9440: }
9441:
9442: sub reset_hosts_ip_info {
9443: undef(%iphost);
9444: undef(%name_to_ip);
9445: undef(%lonid_to_ip);
9446: }
9447:
9448: sub get_host_ip {
9449: my ($lonid) = @_;
9450: if (exists($lonid_to_ip{$lonid})) {
9451: return $lonid_to_ip{$lonid};
9452: }
9453: my $name=&hostname($lonid);
9454: my $ip = gethostbyname($name);
9455: return if (!$ip || length($ip) ne 4);
9456: $ip=inet_ntoa($ip);
9457: $name_to_ip{$name} = $ip;
9458: $lonid_to_ip{$lonid} = $ip;
9459: return $ip;
9460: }
9461:
9462: sub get_iphost {
9463: my ($ignore_cache) = @_;
9464:
9465: if (!$ignore_cache) {
9466: if (%iphost) {
9467: return %iphost;
9468: }
9469: my ($ip_info,$cached)=
9470: &Apache::lonnet::is_cached_new('iphost','iphost');
9471: if ($cached) {
9472: %iphost = %{$ip_info->[0]};
9473: %name_to_ip = %{$ip_info->[1]};
9474: %lonid_to_ip = %{$ip_info->[2]};
9475: return %iphost;
9476: }
9477: }
9478:
9479: # get yesterday's info for fallback
9480: my %old_name_to_ip;
9481: my ($ip_info,$cached)=
9482: &Apache::lonnet::is_cached_new('iphost','iphost');
9483: if ($cached) {
9484: %old_name_to_ip = %{$ip_info->[1]};
9485: }
9486:
9487: my %name_to_host = &all_names();
9488: foreach my $name (keys(%name_to_host)) {
9489: my $ip;
9490: if (!exists($name_to_ip{$name})) {
9491: $ip = gethostbyname($name);
9492: if (!$ip || length($ip) ne 4) {
9493: if (defined($old_name_to_ip{$name})) {
9494: $ip = $old_name_to_ip{$name};
9495: &logthis("Can't find $name defaulting to old $ip");
9496: } else {
9497: &logthis("Name $name no IP found");
9498: next;
9499: }
9500: } else {
9501: $ip=inet_ntoa($ip);
9502: }
9503: $name_to_ip{$name} = $ip;
9504: } else {
9505: $ip = $name_to_ip{$name};
9506: }
9507: foreach my $id (@{ $name_to_host{$name} }) {
9508: $lonid_to_ip{$id} = $ip;
9509: }
9510: push(@{$iphost{$ip}},@{$name_to_host{$name}});
9511: }
9512: &Apache::lonnet::do_cache_new('iphost','iphost',
9513: [\%iphost,\%name_to_ip,\%lonid_to_ip],
9514: 48*60*60);
9515:
9516: return %iphost;
9517: }
9518:
9519: #
9520: # Given a DNS returns the loncapa host name for that DNS
9521: #
9522: sub host_from_dns {
9523: my ($dns) = @_;
9524: my @hosts;
9525: my $ip;
9526:
9527: if (exists($name_to_ip{$dns})) {
9528: $ip = $name_to_ip{$dns};
9529: }
9530: if (!$ip) {
9531: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9532: if (length($ip) == 4) {
9533: $ip = &IO::Socket::inet_ntoa($ip);
9534: }
9535: }
9536: if ($ip) {
9537: @hosts = get_hosts_from_ip($ip);
9538: return $hosts[0];
9539: }
9540: return undef;
9541: }
9542:
9543: }
9544:
9545: BEGIN {
9546:
9547: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9548: unless ($readit) {
9549: {
9550: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9551: %perlvar = (%perlvar,%{$configvars});
9552: }
9553:
9554:
9555: # ------------------------------------------------------ Read spare server file
9556: {
9557: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
9558:
9559: while (my $configline=<$config>) {
9560: chomp($configline);
9561: if ($configline) {
9562: my ($host,$type) = split(':',$configline,2);
9563: if (!defined($type) || $type eq '') { $type = 'default' };
9564: push(@{ $spareid{$type} }, $host);
9565: }
9566: }
9567: close($config);
9568: }
9569: # ------------------------------------------------------------ Read permissions
9570: {
9571: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
9572:
9573: while (my $configline=<$config>) {
9574: chomp($configline);
9575: if ($configline) {
9576: my ($role,$perm)=split(/ /,$configline);
9577: if ($perm ne '') { $pr{$role}=$perm; }
9578: }
9579: }
9580: close($config);
9581: }
9582:
9583: # -------------------------------------------- Read plain texts for permissions
9584: {
9585: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
9586:
9587: while (my $configline=<$config>) {
9588: chomp($configline);
9589: if ($configline) {
9590: my ($short,@plain)=split(/:/,$configline);
9591: %{$prp{$short}} = ();
9592: if (@plain > 0) {
9593: $prp{$short}{'std'} = $plain[0];
9594: for (my $i=1; $i<@plain; $i++) {
9595: $prp{$short}{'alt'.$i} = $plain[$i];
9596: }
9597: }
9598: }
9599: }
9600: close($config);
9601: }
9602:
9603: # ---------------------------------------------------------- Read package table
9604: {
9605: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
9606:
9607: while (my $configline=<$config>) {
9608: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
9609: chomp($configline);
9610: my ($short,$plain)=split(/:/,$configline);
9611: my ($pack,$name)=split(/\&/,$short);
9612: if ($plain ne '') {
9613: $packagetab{$pack.'&'.$name.'&name'}=$name;
9614: $packagetab{$short}=$plain;
9615: }
9616: }
9617: close($config);
9618: }
9619:
9620: # ------------- set up temporary directory
9621: {
9622: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9623:
9624: }
9625:
9626: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9627: 'compress_threshold'=> 20_000,
9628: });
9629:
9630: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
9631: $dumpcount=0;
9632: $locknum=0;
9633:
9634: &logtouch();
9635: &logthis('<font color="yellow">INFO: Read configuration</font>');
9636: $readit=1;
9637: {
9638: use integer;
9639: my $test=(2**32)+1;
9640: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
9641: &logthis(" Detected 64bit platform ($_64bit)");
9642: }
9643: }
9644: }
9645:
9646: 1;
9647: __END__
9648:
9649: =pod
9650:
9651: =head1 NAME
9652:
9653: Apache::lonnet - Subroutines to ask questions about things in the network.
9654:
9655: =head1 SYNOPSIS
9656:
9657: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
9658:
9659: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9660:
9661: Common parameters:
9662:
9663: =over 4
9664:
9665: =item *
9666:
9667: $uname : an internal username (if $cname expecting a course Id specifically)
9668:
9669: =item *
9670:
9671: $udom : a domain (if $cdom expecting a course's domain specifically)
9672:
9673: =item *
9674:
9675: $symb : a resource instance identifier
9676:
9677: =item *
9678:
9679: $namespace : the name of a .db file that contains the data needed or
9680: being set.
9681:
9682: =back
9683:
9684: =head1 OVERVIEW
9685:
9686: lonnet provides subroutines which interact with the
9687: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9688: about classes, users, and resources.
9689:
9690: For many of these objects you can also use this to store data about
9691: them or modify them in various ways.
9692:
9693: =head2 Symbs
9694:
9695: To identify a specific instance of a resource, LON-CAPA uses symbols
9696: or "symbs"X<symb>. These identifiers are built from the URL of the
9697: map, the resource number of the resource in the map, and the URL of
9698: the resource itself. The latter is somewhat redundant, but might help
9699: if maps change.
9700:
9701: An example is
9702:
9703: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9704:
9705: The respective map entry is
9706:
9707: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9708: title="Problem 2">
9709: </resource>
9710:
9711: Symbs are used by the random number generator, as well as to store and
9712: restore data specific to a certain instance of for example a problem.
9713:
9714: =head2 Storing And Retrieving Data
9715:
9716: X<store()>X<cstore()>X<restore()>Three of the most important functions
9717: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9718: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9719: is is the non-critical message twin of cstore. These functions are for
9720: handlers to store a perl hash to a user's permanent data space in an
9721: easy manner, and to retrieve it again on another call. It is expected
9722: that a handler would use this once at the beginning to retrieve data,
9723: and then again once at the end to send only the new data back.
9724:
9725: The data is stored in the user's data directory on the user's
9726: homeserver under the ID of the course.
9727:
9728: The hash that is returned by restore will have all of the previous
9729: value for all of the elements of the hash.
9730:
9731: Example:
9732:
9733: #creating a hash
9734: my %hash;
9735: $hash{'foo'}='bar';
9736:
9737: #storing it
9738: &Apache::lonnet::cstore(\%hash);
9739:
9740: #changing a value
9741: $hash{'foo'}='notbar';
9742:
9743: #adding a new value
9744: $hash{'bar'}='foo';
9745: &Apache::lonnet::cstore(\%hash);
9746:
9747: #retrieving the hash
9748: my %history=&Apache::lonnet::restore();
9749:
9750: #print the hash
9751: foreach my $key (sort(keys(%history))) {
9752: print("\%history{$key} = $history{$key}");
9753: }
9754:
9755: Will print out:
9756:
9757: %history{1:foo} = bar
9758: %history{1:keys} = foo:timestamp
9759: %history{1:timestamp} = 990455579
9760: %history{2:bar} = foo
9761: %history{2:foo} = notbar
9762: %history{2:keys} = foo:bar:timestamp
9763: %history{2:timestamp} = 990455580
9764: %history{bar} = foo
9765: %history{foo} = notbar
9766: %history{timestamp} = 990455580
9767: %history{version} = 2
9768:
9769: Note that the special hash entries C<keys>, C<version> and
9770: C<timestamp> were added to the hash. C<version> will be equal to the
9771: total number of versions of the data that have been stored. The
9772: C<timestamp> attribute will be the UNIX time the hash was
9773: stored. C<keys> is available in every historical section to list which
9774: keys were added or changed at a specific historical revision of a
9775: hash.
9776:
9777: B<Warning>: do not store the hash that restore returns directly. This
9778: will cause a mess since it will restore the historical keys as if the
9779: were new keys. I.E. 1:foo will become 1:1:foo etc.
9780:
9781: Calling convention:
9782:
9783: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9784: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
9785:
9786: For more detailed information, see lonnet specific documentation.
9787:
9788: =head1 RETURN MESSAGES
9789:
9790: =over 4
9791:
9792: =item * B<con_lost>: unable to contact remote host
9793:
9794: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9795: when the connection is brought back up
9796:
9797: =item * B<con_failed>: unable to contact remote host and unable to save message
9798: for later delivery
9799:
9800: =item * B<error:>: an error a occurred, a description of the error follows the :
9801:
9802: =item * B<no_such_host>: unable to fund a host associated with the user/domain
9803: that was requested
9804:
9805: =back
9806:
9807: =head1 PUBLIC SUBROUTINES
9808:
9809: =head2 Session Environment Functions
9810:
9811: =over 4
9812:
9813: =item *
9814: X<appenv()>
9815: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
9816: the user envirnoment file, and will be restored for each access this
9817: user makes during this session, also modifies the %env for the current
9818: process. Optional rolesarrayref - if defined contains a reference to an array
9819: of roles which are exempt from the restriction on modifying user.role entries
9820: in the user's environment.db and in %env.
9821:
9822: =item *
9823: X<delenv()>
9824: B<delenv($delthis,$regexp)>: removes all items from the session
9825: environment file that begin with $delthis. If the
9826: optional second arg - $regexp - is true, $delthis is treated as a
9827: regular expression, otherwise \Q$delthis\E is used.
9828: The values are also deleted from the current processes %env.
9829:
9830: =item * get_env_multiple($name)
9831:
9832: gets $name from the %env hash, it seemlessly handles the cases where multiple
9833: values may be defined and end up as an array ref.
9834:
9835: returns an array of values
9836:
9837: =back
9838:
9839: =head2 User Information
9840:
9841: =over 4
9842:
9843: =item *
9844: X<queryauthenticate()>
9845: B<queryauthenticate($uname,$udom)>: try to determine user's current
9846: authentication scheme
9847:
9848: =item *
9849: X<authenticate()>
9850: B<authenticate($uname,$upass,$udom)>: try to
9851: authenticate user from domain's lib servers (first use the current
9852: one). C<$upass> should be the users password.
9853:
9854: =item *
9855: X<homeserver()>
9856: B<homeserver($uname,$udom)>: find the server which has
9857: the user's directory and files (there must be only one), this caches
9858: the answer, and also caches if there is a borken connection.
9859:
9860: =item *
9861: X<idget()>
9862: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9863: (IDs are a unique resource in a domain, there must be only 1 ID per
9864: username, and only 1 username per ID in a specific domain) (returns
9865: hash: id=>name,id=>name)
9866:
9867: =item *
9868: X<idrget()>
9869: B<idrget($udom,@unames)>: find the IDs behind a list of
9870: usernames (returns hash: name=>id,name=>id)
9871:
9872: =item *
9873: X<idput()>
9874: B<idput($udom,%ids)>: store away a list of names and associated IDs
9875:
9876: =item *
9877: X<rolesinit()>
9878: B<rolesinit($udom,$username,$authhost)>: get user privileges
9879:
9880: =item *
9881: X<getsection()>
9882: B<getsection($udom,$uname,$cname)>: finds the section of student in the
9883: course $cname, return section name/number or '' for "not in course"
9884: and '-1' for "no section"
9885:
9886: =item *
9887: X<userenvironment()>
9888: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
9889: passed in @what from the requested user's environment, returns a hash
9890:
9891: =item *
9892: X<userlog_query()>
9893: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9894: activity.log file. %filters defines filters applied when parsing the
9895: log file. These can be start or end timestamps, or the type of action
9896: - log to look for Login or Logout events, check for Checkin or
9897: Checkout, role for role selection. The response is in the form
9898: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9899: escaped strings of the action recorded in the activity.log file.
9900:
9901: =back
9902:
9903: =head2 User Roles
9904:
9905: =over 4
9906:
9907: =item *
9908:
9909: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
9910: F: full access
9911: U,I,K: authentication modes (cxx only)
9912: '': forbidden
9913: 1: user needs to choose course
9914: 2: browse allowed
9915: A: passphrase authentication needed
9916:
9917: =item *
9918:
9919: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9920: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9921: and course level
9922:
9923: =item *
9924:
9925: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
9926: (rolesplain.tab); plain text explanation of a user role term.
9927: $type is Course (default) or Community.
9928: If $forcedefault evaluates to true, text returned will be default
9929: text for $type. Otherwise, if this is a course, the text returned
9930: will be a custom name for the role (if defined in the course's
9931: environment). If no custom name is defined the default is returned.
9932:
9933: =item *
9934:
9935: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
9936: All arguments are optional. Returns a hash of a roles, either for
9937: co-author/assistant author roles for a user's Construction Space
9938: (default), or if $context is 'userroles', roles for the user himself,
9939: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9940: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9941: For each key, value is set to colon-separated start and end times for
9942: the role. If no username and domain are specified, will default to
9943: current user/domain. Types, roles, and roledoms are references to arrays
9944: of role statuses (active, future or previous), roles
9945: (e.g., cc,in, st etc.) and domains of the roles which can be used
9946: to restrict the list of roles reported. If no array ref is
9947: provided for types, will default to return only active roles.
9948:
9949: =back
9950:
9951: =head2 User Modification
9952:
9953: =over 4
9954:
9955: =item *
9956:
9957: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
9958: user for the level given by URL. Optional start and end dates (leave empty
9959: string or zero for "no date")
9960:
9961: =item *
9962:
9963: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9964: change a users, password, possible return values are: ok,
9965: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9966: refused
9967:
9968: =item *
9969:
9970: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
9971:
9972: =item *
9973:
9974: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9975: $forceid,$desiredhome,$email,$inststatus) :
9976: modify user
9977:
9978: =item *
9979:
9980: modifystudent
9981:
9982: modify a student's enrollment and identification information.
9983: The course id is resolved based on the current users environment.
9984: This means the envoking user must be a course coordinator or otherwise
9985: associated with a course.
9986:
9987: This call is essentially a wrapper for lonnet::modifyuser and
9988: lonnet::modify_student_enrollment
9989:
9990: Inputs:
9991:
9992: =over 4
9993:
9994: =item B<$udom> Student's loncapa domain
9995:
9996: =item B<$uname> Student's loncapa login name
9997:
9998: =item B<$uid> Student/Employee ID
9999:
10000: =item B<$umode> Student's authentication mode
10001:
10002: =item B<$upass> Student's password
10003:
10004: =item B<$first> Student's first name
10005:
10006: =item B<$middle> Student's middle name
10007:
10008: =item B<$last> Student's last name
10009:
10010: =item B<$gene> Student's generation
10011:
10012: =item B<$usec> Student's section in course
10013:
10014: =item B<$end> Unix time of the roles expiration
10015:
10016: =item B<$start> Unix time of the roles start date
10017:
10018: =item B<$forceid> If defined, allow $uid to be changed
10019:
10020: =item B<$desiredhome> server to use as home server for student
10021:
10022: =item B<$email> Student's permanent e-mail address
10023:
10024: =item B<$type> Type of enrollment (auto or manual)
10025:
10026: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10027:
10028: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10029:
10030: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10031:
10032: =item B<$context> role change context (shown in User Management Logs display in a course)
10033:
10034: =item B<$inststatus> institutional status of user - : separated string of escaped status types
10035:
10036: =back
10037:
10038: =item *
10039:
10040: modify_student_enrollment
10041:
10042: Change a students enrollment status in a class. The environment variable
10043: 'role.request.course' must be defined for this function to proceed.
10044:
10045: Inputs:
10046:
10047: =over 4
10048:
10049: =item $udom, students domain
10050:
10051: =item $uname, students name
10052:
10053: =item $uid, students user id
10054:
10055: =item $first, students first name
10056:
10057: =item $middle
10058:
10059: =item $last
10060:
10061: =item $gene
10062:
10063: =item $usec
10064:
10065: =item $end
10066:
10067: =item $start
10068:
10069: =item $type
10070:
10071: =item $locktype
10072:
10073: =item $cid
10074:
10075: =item $selfenroll
10076:
10077: =item $context
10078:
10079: =back
10080:
10081:
10082: =item *
10083:
10084: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10085: custom role; give a custom role to a user for the level given by URL. Specify
10086: name and domain of role author, and role name
10087:
10088: =item *
10089:
10090: revokerole($udom,$uname,$url,$role) : revoke a role for url
10091:
10092: =item *
10093:
10094: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10095:
10096: =back
10097:
10098: =head2 Course Infomation
10099:
10100: =over 4
10101:
10102: =item *
10103:
10104: coursedescription($courseid) : returns a hash of information about the
10105: specified course id, including all environment settings for the
10106: course, the description of the course will be in the hash under the
10107: key 'description'
10108:
10109: =item *
10110:
10111: resdata($name,$domain,$type,@which) : request for current parameter
10112: setting for a specific $type, where $type is either 'course' or 'user',
10113: @what should be a list of parameters to ask about. This routine caches
10114: answers for 5 minutes.
10115:
10116: =item *
10117:
10118: get_courseresdata($courseid, $domain) : dump the entire course resource
10119: data base, returning a hash that is keyed by the resource name and has
10120: values that are the resource value. I believe that the timestamps and
10121: versions are also returned.
10122:
10123:
10124: =back
10125:
10126: =head2 Course Modification
10127:
10128: =over 4
10129:
10130: =item *
10131:
10132: writecoursepref($courseid,%prefs) : write preferences (environment
10133: database) for a course
10134:
10135: =item *
10136:
10137: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10138:
10139: =item *
10140:
10141: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
10142:
10143: =back
10144:
10145: =head2 Resource Subroutines
10146:
10147: =over 4
10148:
10149: =item *
10150:
10151: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10152:
10153: =item *
10154:
10155: repcopy($filename) : subscribes to the requested file, and attempts to
10156: replicate from the owning library server, Might return
10157: 'unavailable', 'not_found', 'forbidden', 'ok', or
10158: 'bad_request', also attempts to grab the metadata for the
10159: resource. Expects the local filesystem pathname
10160: (/home/httpd/html/res/....)
10161:
10162: =back
10163:
10164: =head2 Resource Information
10165:
10166: =over 4
10167:
10168: =item *
10169:
10170: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10171: a vairety of different possible values, $varname should be a request
10172: string, and the other parameters can be used to specify who and what
10173: one is asking about.
10174:
10175: Possible values for $varname are environment.lastname (or other item
10176: from the envirnment hash), user.name (or someother aspect about the
10177: user), resource.0.maxtries (or some other part and parameter of a
10178: resource)
10179:
10180: =item *
10181:
10182: directcondval($number) : get current value of a condition; reads from a state
10183: string
10184:
10185: =item *
10186:
10187: condval($condidx) : value of condition index based on state
10188:
10189: =item *
10190:
10191: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10192: resource's metadata, $what should be either a specific key, or either
10193: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10194: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10195:
10196: this function automatically caches all requests
10197:
10198: =item *
10199:
10200: metadata_query($query,$custom,$customshow) : make a metadata query against the
10201: network of library servers; returns file handle of where SQL and regex results
10202: will be stored for query
10203:
10204: =item *
10205:
10206: symbread($filename) : return symbolic list entry (filename argument optional);
10207: returns the data handle
10208:
10209: =item *
10210:
10211: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10212: a possible symb for the URL in $thisfn, and if is an encryypted
10213: resource that the user accessed using /enc/ returns a 1 on success, 0
10214: on failure, user must be in a course, as it assumes the existance of
10215: the course initial hash, and uses $env('request.course.id'}
10216:
10217:
10218: =item *
10219:
10220: symbclean($symb) : removes versions numbers from a symb, returns the
10221: cleaned symb
10222:
10223: =item *
10224:
10225: is_on_map($uri) : checks if the $uri is somewhere on the current
10226: course map, user must be in a course for it to work.
10227:
10228: =item *
10229:
10230: numval($salt) : return random seed value (addend for rndseed)
10231:
10232: =item *
10233:
10234: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10235: a random seed, all arguments are optional, if they aren't sent it uses the
10236: environment to derive them. Note: if symb isn't sent and it can't get one
10237: from &symbread it will use the current time as its return value
10238:
10239: =item *
10240:
10241: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10242: unfakeable, receipt
10243:
10244: =item *
10245:
10246: receipt() : API to ireceipt working off of env values; given out to users
10247:
10248: =item *
10249:
10250: countacc($url) : count the number of accesses to a given URL
10251:
10252: =item *
10253:
10254: 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
10255:
10256: =item *
10257:
10258: 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)
10259:
10260: =item *
10261:
10262: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10263:
10264: =item *
10265:
10266: devalidate($symb) : devalidate temporary spreadsheet calculations,
10267: forcing spreadsheet to reevaluate the resource scores next time.
10268:
10269: =back
10270:
10271: =head2 Storing/Retreiving Data
10272:
10273: =over 4
10274:
10275: =item *
10276:
10277: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10278: for this url; hashref needs to be given and should be a \%hashname; the
10279: remaining args aren't required and if they aren't passed or are '' they will
10280: be derived from the env
10281:
10282: =item *
10283:
10284: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10285: uses critical subroutine
10286:
10287: =item *
10288:
10289: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10290: all args are optional
10291:
10292: =item *
10293:
10294: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10295: dumps the complete (or key matching regexp) namespace into a hash
10296: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10297: normally &store()ed into
10298:
10299: $range should be either an integer '100' (give me the first 100
10300: matching records)
10301: or be two integers sperated by a - with no spaces
10302: '30-50' (give me the 30th through the 50th matching
10303: records)
10304:
10305:
10306: =item *
10307:
10308: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10309: replaces a &store() version of data with a replacement set of data
10310: for a particular resource in a namespace passed in the $storehash hash
10311: reference
10312:
10313: =item *
10314:
10315: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10316: works very similar to store/cstore, but all data is stored in a
10317: temporary location and can be reset using tmpreset, $storehash should
10318: be a hash reference, returns nothing on success
10319:
10320: =item *
10321:
10322: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10323: similar to restore, but all data is stored in a temporary location and
10324: can be reset using tmpreset. Returns a hash of values on success,
10325: error string otherwise.
10326:
10327: =item *
10328:
10329: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10330: deltes all keys for $symb form the temporary storage hash.
10331:
10332: =item *
10333:
10334: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10335: reference filled in from namesp ($udom and $uname are optional)
10336:
10337: =item *
10338:
10339: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10340: namesp ($udom and $uname are optional)
10341:
10342: =item *
10343:
10344: dump($namespace,$udom,$uname,$regexp,$range) :
10345: dumps the complete (or key matching regexp) namespace into a hash
10346: ($udom, $uname, $regexp, $range are optional)
10347:
10348: $range should be either an integer '100' (give me the first 100
10349: matching records)
10350: or be two integers sperated by a - with no spaces
10351: '30-50' (give me the 30th through the 50th matching
10352: records)
10353: =item *
10354:
10355: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10356: $store can be a scalar, an array reference, or if the amount to be
10357: incremented is > 1, a hash reference.
10358:
10359: ($udom and $uname are optional)
10360:
10361: =item *
10362:
10363: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10364: ($udom and $uname are optional)
10365:
10366: =item *
10367:
10368: cput($namespace,$storehash,$udom,$uname) : critical put
10369: ($udom and $uname are optional)
10370:
10371: =item *
10372:
10373: newput($namespace,$storehash,$udom,$uname) :
10374:
10375: Attempts to store the items in the $storehash, but only if they don't
10376: currently exist, if this succeeds you can be certain that you have
10377: successfully created a new key value pair in the $namespace db.
10378:
10379:
10380: Args:
10381: $namespace: name of database to store values to
10382: $storehash: hashref to store to the db
10383: $udom: (optional) domain of user containing the db
10384: $uname: (optional) name of user caontaining the db
10385:
10386: Returns:
10387: 'ok' -> succeeded in storing all keys of $storehash
10388: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10389: least <key> already existed in the db (other
10390: requested keys may also already exist)
10391: 'error: <msg>' -> unable to tie the DB or other error occurred
10392: 'con_lost' -> unable to contact request server
10393: 'refused' -> action was not allowed by remote machine
10394:
10395:
10396: =item *
10397:
10398: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10399: reference filled in from namesp (encrypts the return communication)
10400: ($udom and $uname are optional)
10401:
10402: =item *
10403:
10404: log($udom,$name,$home,$message) : write to permanent log for user; use
10405: critical subroutine
10406:
10407: =item *
10408:
10409: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10410: array reference filled in from namespace found in domain level on either
10411: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10412:
10413: =item *
10414:
10415: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10416: domain level either on specified domain server ($uhome) or primary domain
10417: server ($udom and $uhome are optional)
10418:
10419: =item *
10420:
10421: get_domain_defaults($target_domain) : returns hash with defaults for
10422: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10423: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10424: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10425: Values are retrieved from cache (if current), or from domain's configuration.db
10426: (if available), or lastly from values in lonTabs/dns_domain,tab,
10427: or lonTabs/domain.tab.
10428:
10429: %domdefaults = &get_auth_defaults($target_domain);
10430:
10431: =back
10432:
10433: =head2 Network Status Functions
10434:
10435: =over 4
10436:
10437: =item *
10438:
10439: dirlist($uri) : return directory list based on URI
10440:
10441: =item *
10442:
10443: spareserver() : find server with least workload from spare.tab
10444:
10445:
10446: =item *
10447:
10448: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10449: if there is no corresponding loncapa host.
10450:
10451: =back
10452:
10453:
10454: =head2 Apache Request
10455:
10456: =over 4
10457:
10458: =item *
10459:
10460: ssi($url,%hash) : server side include, does a complete request cycle on url to
10461: localhost, posts hash
10462:
10463: =back
10464:
10465: =head2 Data to String to Data
10466:
10467: =over 4
10468:
10469: =item *
10470:
10471: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10472: and '&' separators, supports elements that are arrayrefs and hashrefs
10473:
10474: =item *
10475:
10476: hashref2str($hashref) : convert a hashref into a string complete with
10477: escaping and '=' and '&' separators, supports elements that are
10478: arrayrefs and hashrefs
10479:
10480: =item *
10481:
10482: arrayref2str($arrayref) : convert an arrayref into a string complete
10483: with escaping and '&' separators, supports elements that are arrayrefs
10484: and hashrefs
10485:
10486: =item *
10487:
10488: str2hash($string) : convert string to hash using unescaping and
10489: splitting on '=' and '&', supports elements that are arrayrefs and
10490: hashrefs
10491:
10492: =item *
10493:
10494: str2array($string) : convert string to hash using unescaping and
10495: splitting on '&', supports elements that are arrayrefs and hashrefs
10496:
10497: =back
10498:
10499: =head2 Logging Routines
10500:
10501: =over 4
10502:
10503: These routines allow one to make log messages in the lonnet.log and
10504: lonnet.perm logfiles.
10505:
10506: =item *
10507:
10508: logtouch() : make sure the logfile, lonnet.log, exists
10509:
10510: =item *
10511:
10512: logthis() : append message to the normal lonnet.log file, it gets
10513: preiodically rolled over and deleted.
10514:
10515: =item *
10516:
10517: logperm() : append a permanent message to lonnet.perm.log, this log
10518: file never gets deleted by any automated portion of the system, only
10519: messages of critical importance should go in here.
10520:
10521: =back
10522:
10523: =head2 General File Helper Routines
10524:
10525: =over 4
10526:
10527: =item *
10528:
10529: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10530: (a) files in /uploaded
10531: (i) If a local copy of the file exists -
10532: compares modification date of local copy with last-modified date for
10533: definitive version stored on home server for course. If local copy is
10534: stale, requests a new version from the home server and stores it.
10535: If the original has been removed from the home server, then local copy
10536: is unlinked.
10537: (ii) If local copy does not exist -
10538: requests the file from the home server and stores it.
10539:
10540: If $caller is 'uploadrep':
10541: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10542: for request for files originally uploaded via DOCS.
10543: - returns 'ok' if fresh local copy now available, -1 otherwise.
10544:
10545: Otherwise:
10546: This indicates a call from the content generation phase of the request.
10547: - returns the entire contents of the file or -1.
10548:
10549: (b) files in /res
10550: - returns the entire contents of a file or -1;
10551: it properly subscribes to and replicates the file if neccessary.
10552:
10553:
10554: =item *
10555:
10556: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10557: reference
10558:
10559: returns either a stat() list of data about the file or an empty list
10560: if the file doesn't exist or couldn't find out about it (connection
10561: problems or user unknown)
10562:
10563: =item *
10564:
10565: filelocation($dir,$file) : returns file system location of a file
10566: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10567: directory that relative $file lookups are to looked in ($dir of /a/dir
10568: and a file of ../bob will become /a/bob)
10569:
10570: =item *
10571:
10572: hreflocation($dir,$file) : returns file system location or a URL; same as
10573: filelocation except for hrefs
10574:
10575: =item *
10576:
10577: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10578:
10579: =back
10580:
10581: =head2 Usererfile file routines (/uploaded*)
10582:
10583: =over 4
10584:
10585: =item *
10586:
10587: userfileupload(): main rotine for putting a file in a user or course's
10588: filespace, arguments are,
10589:
10590: formname - required - this is the name of the element in $env where the
10591: filename, and the contents of the file to create/modifed exist
10592: the filename is in $env{'form.'.$formname.'.filename'} and the
10593: contents of the file is located in $env{'form.'.$formname}
10594: coursedoc - if true, store the file in the course of the active role
10595: of the current user
10596: subdir - required - subdirectory to put the file in under ../userfiles/
10597: if undefined, it will be placed in "unknown"
10598:
10599: (This routine calls clean_filename() to remove any dangerous
10600: characters from the filename, and then calls finuserfileupload() to
10601: complete the transaction)
10602:
10603: returns either the url of the uploaded file (/uploaded/....) if successful
10604: and /adm/notfound.html if unsuccessful
10605:
10606: =item *
10607:
10608: clean_filename(): routine for cleaing a filename up for storage in
10609: userfile space, argument is:
10610:
10611: filename - proposed filename
10612:
10613: returns: the new clean filename
10614:
10615: =item *
10616:
10617: finishuserfileupload(): routine that creaes and sends the file to
10618: userspace, probably shouldn't be called directly
10619:
10620: docuname: username or courseid of destination for the file
10621: docudom: domain of user/course of destination for the file
10622: formname: same as for userfileupload()
10623: fname: filename (inculding subdirectories) for the file
10624:
10625: returns either the url of the uploaded file (/uploaded/....) if successful
10626: and /adm/notfound.html if unsuccessful
10627:
10628: =item *
10629:
10630: renameuserfile(): renames an existing userfile to a new name
10631:
10632: Args:
10633: docuname: username or courseid of destination for the file
10634: docudom: domain of user/course of destination for the file
10635: old: current file name (including any subdirs under userfiles)
10636: new: desired file name (including any subdirs under userfiles)
10637:
10638: =item *
10639:
10640: mkdiruserfile(): creates a directory is a userfiles dir
10641:
10642: Args:
10643: docuname: username or courseid of destination for the file
10644: docudom: domain of user/course of destination for the file
10645: dir: dir to create (including any subdirs under userfiles)
10646:
10647: =item *
10648:
10649: removeuserfile(): removes a file that exists in userfiles
10650:
10651: Args:
10652: docuname: username or courseid of destination for the file
10653: docudom: domain of user/course of destination for the file
10654: fname: filname to delete (including any subdirs under userfiles)
10655:
10656: =item *
10657:
10658: removeuploadedurl(): convience function for removeuserfile()
10659:
10660: Args:
10661: url: a full /uploaded/... url to delete
10662:
10663: =item *
10664:
10665: get_portfile_permissions():
10666: Args:
10667: domain: domain of user or course contain the portfolio files
10668: user: name of user or num of course contain the portfolio files
10669: Returns:
10670: hashref of a dump of the proper file_permissions.db
10671:
10672:
10673: =item *
10674:
10675: get_access_controls():
10676:
10677: Args:
10678: current_permissions: the hash ref returned from get_portfile_permissions()
10679: group: (optional) the group you want the files associated with
10680: file: (optional) the file you want access info on
10681:
10682: Returns:
10683: a hash (keys are file names) of hashes containing
10684: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10685: values are XML containing access control settings (see below)
10686:
10687: Internal notes:
10688:
10689: access controls are stored in file_permissions.db as key=value pairs.
10690: key -> path to file/file_name\0uniqueID:scope_end_start
10691: where scope -> public,guest,course,group,domains or users.
10692: end -> UNIX time for end of access (0 -> no end date)
10693: start -> UNIX time for start of access
10694:
10695: value -> XML description of access control
10696: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10697: <start></start>
10698: <end></end>
10699:
10700: <password></password> for scope type = guest
10701:
10702: <domain></domain> for scope type = course or group
10703: <number></number>
10704: <roles id="">
10705: <role></role>
10706: <access></access>
10707: <section></section>
10708: <group></group>
10709: </roles>
10710:
10711: <dom></dom> for scope type = domains
10712:
10713: <users> for scope type = users
10714: <user>
10715: <uname></uname>
10716: <udom></udom>
10717: </user>
10718: </users>
10719: </scope>
10720:
10721: Access data is also aggregated for each file in an additional key=value pair:
10722: key -> path to file/file_name\0accesscontrol
10723: value -> reference to hash
10724: hash contains key = value pairs
10725: where key = uniqueID:scope_end_start
10726: value = UNIX time record was last updated
10727:
10728: Used to improve speed of look-ups of access controls for each file.
10729:
10730: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10731:
10732: modify_access_controls():
10733:
10734: Modifies access controls for a portfolio file
10735: Args
10736: 1. file name
10737: 2. reference to hash of required changes,
10738: 3. domain
10739: 4. username
10740: where domain,username are the domain of the portfolio owner
10741: (either a user or a course)
10742:
10743: Returns:
10744: 1. result of additions or updates ('ok' or 'error', with error message).
10745: 2. result of deletions ('ok' or 'error', with error message).
10746: 3. reference to hash of any new or updated access controls.
10747: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10748: key = integer (inbound ID)
10749: value = uniqueID
10750:
10751: =back
10752:
10753: =head2 HTTP Helper Routines
10754:
10755: =over 4
10756:
10757: =item *
10758:
10759: escape() : unpack non-word characters into CGI-compatible hex codes
10760:
10761: =item *
10762:
10763: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10764:
10765: =back
10766:
10767: =head1 PRIVATE SUBROUTINES
10768:
10769: =head2 Underlying communication routines (Shouldn't call)
10770:
10771: =over 4
10772:
10773: =item *
10774:
10775: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10776:
10777: =item *
10778:
10779: reply() : uses subreply to send a message to remote machine, logs all failures
10780:
10781: =item *
10782:
10783: critical() : passes a critical message to another server; if cannot
10784: get through then place message in connection buffer directory and
10785: returns con_delayed, if incapable of saving message, returns
10786: con_failed
10787:
10788: =item *
10789:
10790: reconlonc() : tries to reconnect lonc client processes.
10791:
10792: =back
10793:
10794: =head2 Resource Access Logging
10795:
10796: =over 4
10797:
10798: =item *
10799:
10800: flushcourselogs() : flush (save) buffer logs and access logs
10801:
10802: =item *
10803:
10804: courselog($what) : save message for course in hash
10805:
10806: =item *
10807:
10808: courseacclog($what) : save message for course using &courselog(). Perform
10809: special processing for specific resource types (problems, exams, quizzes, etc).
10810:
10811: =item *
10812:
10813: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10814: as a PerlChildExitHandler
10815:
10816: =back
10817:
10818: =head2 Other
10819:
10820: =over 4
10821:
10822: =item *
10823:
10824: symblist($mapname,%newhash) : update symbolic storage links
10825:
10826: =back
10827:
10828: =cut
10829:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>