1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.1033 2009/10/22 22:01:47 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 $lonhost = $perlvar{'lonHostID'};
789: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
790: $server);
791: if (! $answer) {
792: &logthis("No reply on password change request to $server ".
793: "by $uname in domain $udom.");
794: } elsif ($answer =~ "^ok") {
795: &logthis("$uname in $udom successfully changed their password ".
796: "on $server.");
797: } elsif ($answer =~ "^pwchange_failure") {
798: &logthis("$uname in $udom was unable to change their password ".
799: "on $server. The action was blocked by either lcpasswd ".
800: "or pwchange");
801: } elsif ($answer =~ "^non_authorized") {
802: &logthis("$uname in $udom did not get their password correct when ".
803: "attempting to change it on $server.");
804: } elsif ($answer =~ "^auth_mode_error") {
805: &logthis("$uname in $udom attempted to change their password despite ".
806: "not being locally or internally authenticated on $server.");
807: } elsif ($answer =~ "^unknown_user") {
808: &logthis("$uname in $udom attempted to change their password ".
809: "on $server but were unable to because $server is not ".
810: "their home server.");
811: } elsif ($answer =~ "^refused") {
812: &logthis("$server refused to change $uname in $udom password because ".
813: "it was sent an unencrypted request to change the password.");
814: } elsif ($answer =~ "invalid_client") {
815: &logthis("$server refused to change $uname in $udom password because ".
816: "it was a reset by e-mail originating from an invalid server.");
817: }
818: return $answer;
819: }
820:
821: # ----------------------- Try to determine user's current authentication scheme
822:
823: sub queryauthenticate {
824: my ($uname,$udom)=@_;
825: my $uhome=&homeserver($uname,$udom);
826: if (!$uhome) {
827: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
828: return 'no_host';
829: }
830: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
831: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
832: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
833: }
834: return $answer;
835: }
836:
837: # --------- Try to authenticate user from domain's lib servers (first this one)
838:
839: sub authenticate {
840: my ($uname,$upass,$udom,$checkdefauth)=@_;
841: $upass=&escape($upass);
842: $uname= &LONCAPA::clean_username($uname);
843: my $uhome=&homeserver($uname,$udom,1);
844: my $newhome;
845: if ((!$uhome) || ($uhome eq 'no_host')) {
846: # Maybe the machine was offline and only re-appeared again recently?
847: &reconlonc();
848: # One more
849: $uhome=&homeserver($uname,$udom,1);
850: if (($uhome eq 'no_host') && $checkdefauth) {
851: if (defined(&domain($udom,'primary'))) {
852: $newhome=&domain($udom,'primary');
853: }
854: if ($newhome ne '') {
855: $uhome = $newhome;
856: }
857: }
858: if ((!$uhome) || ($uhome eq 'no_host')) {
859: &logthis("User $uname at $udom is unknown in authenticate");
860: return 'no_host';
861: }
862: }
863: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
864: if ($answer eq 'authorized') {
865: if ($newhome) {
866: &logthis("User $uname at $udom authorized by $uhome, but needs account");
867: return 'no_account_on_host';
868: } else {
869: &logthis("User $uname at $udom authorized by $uhome");
870: return $uhome;
871: }
872: }
873: if ($answer eq 'non_authorized') {
874: &logthis("User $uname at $udom rejected by $uhome");
875: return 'no_host';
876: }
877: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
878: return 'no_host';
879: }
880:
881: # ---------------------- Find the homebase for a user from domain's lib servers
882:
883: my %homecache;
884: sub homeserver {
885: my ($uname,$udom,$ignoreBadCache)=@_;
886: my $index="$uname:$udom";
887:
888: if (exists($homecache{$index})) { return $homecache{$index}; }
889:
890: my %servers = &get_servers($udom,'library');
891: foreach my $tryserver (keys(%servers)) {
892: next if ($ignoreBadCache ne 'true' &&
893: exists($badServerCache{$tryserver}));
894:
895: my $answer=reply("home:$udom:$uname",$tryserver);
896: if ($answer eq 'found') {
897: delete($badServerCache{$tryserver});
898: return $homecache{$index}=$tryserver;
899: } elsif ($answer eq 'no_host') {
900: $badServerCache{$tryserver}=1;
901: }
902: }
903: return 'no_host';
904: }
905:
906: # ------------------------------------- Find the usernames behind a list of IDs
907:
908: sub idget {
909: my ($udom,@ids)=@_;
910: my %returnhash=();
911:
912: my %servers = &get_servers($udom,'library');
913: foreach my $tryserver (keys(%servers)) {
914: my $idlist=join('&',@ids);
915: $idlist=~tr/A-Z/a-z/;
916: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
917: my @answer=();
918: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
919: @answer=split(/\&/,$reply);
920: } ;
921: my $i;
922: for ($i=0;$i<=$#ids;$i++) {
923: if ($answer[$i]) {
924: $returnhash{$ids[$i]}=$answer[$i];
925: }
926: }
927: }
928: return %returnhash;
929: }
930:
931: # ------------------------------------- Find the IDs behind a list of usernames
932:
933: sub idrget {
934: my ($udom,@unames)=@_;
935: my %returnhash=();
936: foreach my $uname (@unames) {
937: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
938: }
939: return %returnhash;
940: }
941:
942: # ------------------------------- Store away a list of names and associated IDs
943:
944: sub idput {
945: my ($udom,%ids)=@_;
946: my %servers=();
947: foreach my $uname (keys(%ids)) {
948: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
949: my $uhom=&homeserver($uname,$udom);
950: if ($uhom ne 'no_host') {
951: my $id=&escape($ids{$uname});
952: $id=~tr/A-Z/a-z/;
953: my $esc_unam=&escape($uname);
954: if ($servers{$uhom}) {
955: $servers{$uhom}.='&'.$id.'='.$esc_unam;
956: } else {
957: $servers{$uhom}=$id.'='.$esc_unam;
958: }
959: }
960: }
961: foreach my $server (keys(%servers)) {
962: &critical('idput:'.$udom.':'.$servers{$server},$server);
963: }
964: }
965:
966: # ------------------------------dump from db file owned by domainconfig user
967: sub dump_dom {
968: my ($namespace,$udom,$regexp,$range)=@_;
969: if (!$udom) {
970: $udom=$env{'user.domain'};
971: }
972: my %returnhash;
973: if ($udom) {
974: my $uname = &get_domainconfiguser($udom);
975: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
976: }
977: return %returnhash;
978: }
979:
980: # ------------------------------------------ get items from domain db files
981:
982: sub get_dom {
983: my ($namespace,$storearr,$udom,$uhome)=@_;
984: my $items='';
985: foreach my $item (@$storearr) {
986: $items.=&escape($item).'&';
987: }
988: $items=~s/\&$//;
989: if (!$udom) {
990: $udom=$env{'user.domain'};
991: if (defined(&domain($udom,'primary'))) {
992: $uhome=&domain($udom,'primary');
993: } else {
994: undef($uhome);
995: }
996: } else {
997: if (!$uhome) {
998: if (defined(&domain($udom,'primary'))) {
999: $uhome=&domain($udom,'primary');
1000: }
1001: }
1002: }
1003: if ($udom && $uhome && ($uhome ne 'no_host')) {
1004: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1005: my %returnhash;
1006: if ($rep eq '' || $rep =~ /^error: 2 /) {
1007: return %returnhash;
1008: }
1009: my @pairs=split(/\&/,$rep);
1010: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1011: return @pairs;
1012: }
1013: my $i=0;
1014: foreach my $item (@$storearr) {
1015: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1016: $i++;
1017: }
1018: return %returnhash;
1019: } else {
1020: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1021: }
1022: }
1023:
1024: # -------------------------------------------- put items in domain db files
1025:
1026: sub put_dom {
1027: my ($namespace,$storehash,$udom,$uhome)=@_;
1028: if (!$udom) {
1029: $udom=$env{'user.domain'};
1030: if (defined(&domain($udom,'primary'))) {
1031: $uhome=&domain($udom,'primary');
1032: } else {
1033: undef($uhome);
1034: }
1035: } else {
1036: if (!$uhome) {
1037: if (defined(&domain($udom,'primary'))) {
1038: $uhome=&domain($udom,'primary');
1039: }
1040: }
1041: }
1042: if ($udom && $uhome && ($uhome ne 'no_host')) {
1043: my $items='';
1044: foreach my $item (keys(%$storehash)) {
1045: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1046: }
1047: $items=~s/\&$//;
1048: return &reply("putdom:$udom:$namespace:$items",$uhome);
1049: } else {
1050: &logthis("put_dom failed - no homeserver and/or domain");
1051: }
1052: }
1053:
1054: # --------------------- newput for items in db file owned by domainconfig user
1055: sub newput_dom {
1056: my ($namespace,$storehash,$udom) = @_;
1057: my $result;
1058: if (!$udom) {
1059: $udom=$env{'user.domain'};
1060: }
1061: if ($udom) {
1062: my $uname = &get_domainconfiguser($udom);
1063: $result = &newput($namespace,$storehash,$udom,$uname);
1064: }
1065: return $result;
1066: }
1067:
1068: # --------------------- delete for items in db file owned by domainconfig user
1069: sub del_dom {
1070: my ($namespace,$storearr,$udom)=@_;
1071: if (ref($storearr) eq 'ARRAY') {
1072: if (!$udom) {
1073: $udom=$env{'user.domain'};
1074: }
1075: if ($udom) {
1076: my $uname = &get_domainconfiguser($udom);
1077: return &del($namespace,$storearr,$udom,$uname);
1078: }
1079: }
1080: }
1081:
1082: # ----------------------------------construct domainconfig user for a domain
1083: sub get_domainconfiguser {
1084: my ($udom) = @_;
1085: return $udom.'-domainconfig';
1086: }
1087:
1088: sub retrieve_inst_usertypes {
1089: my ($udom) = @_;
1090: my (%returnhash,@order);
1091: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1092: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1093: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1094: %returnhash = %{$domdefs{'inststatustypes'}};
1095: @order = @{$domdefs{'inststatusorder'}};
1096: } else {
1097: if (defined(&domain($udom,'primary'))) {
1098: my $uhome=&domain($udom,'primary');
1099: my $rep=&reply("inst_usertypes:$udom",$uhome);
1100: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1101: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1102: return (\%returnhash,\@order);
1103: }
1104: my ($hashitems,$orderitems) = split(/:/,$rep);
1105: my @pairs=split(/\&/,$hashitems);
1106: foreach my $item (@pairs) {
1107: my ($key,$value)=split(/=/,$item,2);
1108: $key = &unescape($key);
1109: next if ($key =~ /^error: 2 /);
1110: $returnhash{$key}=&thaw_unescape($value);
1111: }
1112: my @esc_order = split(/\&/,$orderitems);
1113: foreach my $item (@esc_order) {
1114: push(@order,&unescape($item));
1115: }
1116: } else {
1117: &logthis("get_dom failed - no primary domain server for $udom");
1118: }
1119: }
1120: return (\%returnhash,\@order);
1121: }
1122:
1123: sub is_domainimage {
1124: my ($url) = @_;
1125: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1126: if (&domain($1) ne '') {
1127: return '1';
1128: }
1129: }
1130: return;
1131: }
1132:
1133: sub inst_directory_query {
1134: my ($srch) = @_;
1135: my $udom = $srch->{'srchdomain'};
1136: my %results;
1137: my $homeserver = &domain($udom,'primary');
1138: my $outcome;
1139: if ($homeserver ne '') {
1140: my $queryid=&reply("querysend:instdirsearch:".
1141: &escape($srch->{'srchby'}).':'.
1142: &escape($srch->{'srchterm'}).':'.
1143: &escape($srch->{'srchtype'}),$homeserver);
1144: my $host=&hostname($homeserver);
1145: if ($queryid !~/^\Q$host\E\_/) {
1146: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1147: return;
1148: }
1149: my $response = &get_query_reply($queryid);
1150: my $maxtries = 5;
1151: my $tries = 1;
1152: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1153: $response = &get_query_reply($queryid);
1154: $tries ++;
1155: }
1156:
1157: if (!&error($response) && $response ne 'refused') {
1158: if ($response eq 'unavailable') {
1159: $outcome = $response;
1160: } else {
1161: $outcome = 'ok';
1162: my @matches = split(/\n/,$response);
1163: foreach my $match (@matches) {
1164: my ($key,$value) = split(/=/,$match);
1165: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1166: }
1167: }
1168: }
1169: }
1170: return ($outcome,%results);
1171: }
1172:
1173: sub usersearch {
1174: my ($srch) = @_;
1175: my $dom = $srch->{'srchdomain'};
1176: my %results;
1177: my %libserv = &all_library();
1178: my $query = 'usersearch';
1179: foreach my $tryserver (keys(%libserv)) {
1180: if (&host_domain($tryserver) eq $dom) {
1181: my $host=&hostname($tryserver);
1182: my $queryid=
1183: &reply("querysend:".&escape($query).':'.
1184: &escape($srch->{'srchby'}).':'.
1185: &escape($srch->{'srchtype'}).':'.
1186: &escape($srch->{'srchterm'}),$tryserver);
1187: if ($queryid !~/^\Q$host\E\_/) {
1188: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1189: next;
1190: }
1191: my $reply = &get_query_reply($queryid);
1192: my $maxtries = 1;
1193: my $tries = 1;
1194: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1195: $reply = &get_query_reply($queryid);
1196: $tries ++;
1197: }
1198: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1199: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1200: } else {
1201: my @matches;
1202: if ($reply =~ /\n/) {
1203: @matches = split(/\n/,$reply);
1204: } else {
1205: @matches = split(/\&/,$reply);
1206: }
1207: foreach my $match (@matches) {
1208: my ($uname,$udom,%userhash);
1209: foreach my $entry (split(/:/,$match)) {
1210: my ($key,$value) =
1211: map {&unescape($_);} split(/=/,$entry);
1212: $userhash{$key} = $value;
1213: if ($key eq 'username') {
1214: $uname = $value;
1215: } elsif ($key eq 'domain') {
1216: $udom = $value;
1217: }
1218: }
1219: $results{$uname.':'.$udom} = \%userhash;
1220: }
1221: }
1222: }
1223: }
1224: return %results;
1225: }
1226:
1227: sub get_instuser {
1228: my ($udom,$uname,$id) = @_;
1229: my $homeserver = &domain($udom,'primary');
1230: my ($outcome,%results);
1231: if ($homeserver ne '') {
1232: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1233: &escape($id).':'.&escape($udom),$homeserver);
1234: my $host=&hostname($homeserver);
1235: if ($queryid !~/^\Q$host\E\_/) {
1236: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1237: return;
1238: }
1239: my $response = &get_query_reply($queryid);
1240: my $maxtries = 5;
1241: my $tries = 1;
1242: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1243: $response = &get_query_reply($queryid);
1244: $tries ++;
1245: }
1246: if (!&error($response) && $response ne 'refused') {
1247: if ($response eq 'unavailable') {
1248: $outcome = $response;
1249: } else {
1250: $outcome = 'ok';
1251: my @matches = split(/\n/,$response);
1252: foreach my $match (@matches) {
1253: my ($key,$value) = split(/=/,$match);
1254: $results{&unescape($key)} = &thaw_unescape($value);
1255: }
1256: }
1257: }
1258: }
1259: my %userinfo;
1260: if (ref($results{$uname}) eq 'HASH') {
1261: %userinfo = %{$results{$uname}};
1262: }
1263: return ($outcome,%userinfo);
1264: }
1265:
1266: sub inst_rulecheck {
1267: my ($udom,$uname,$id,$item,$rules) = @_;
1268: my %returnhash;
1269: if ($udom ne '') {
1270: if (ref($rules) eq 'ARRAY') {
1271: @{$rules} = map {&escape($_);} (@{$rules});
1272: my $rulestr = join(':',@{$rules});
1273: my $homeserver=&domain($udom,'primary');
1274: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1275: my $response;
1276: if ($item eq 'username') {
1277: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1278: ':'.&escape($uname).':'.$rulestr,
1279: $homeserver));
1280: } elsif ($item eq 'id') {
1281: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1282: ':'.&escape($id).':'.$rulestr,
1283: $homeserver));
1284: } elsif ($item eq 'selfcreate') {
1285: $response=&unescape(&reply('instselfcreatecheck:'.
1286: &escape($udom).':'.&escape($uname).
1287: ':'.$rulestr,$homeserver));
1288: }
1289: if ($response ne 'refused') {
1290: my @pairs=split(/\&/,$response);
1291: foreach my $item (@pairs) {
1292: my ($key,$value)=split(/=/,$item,2);
1293: $key = &unescape($key);
1294: next if ($key =~ /^error: 2 /);
1295: $returnhash{$key}=&thaw_unescape($value);
1296: }
1297: }
1298: }
1299: }
1300: }
1301: return %returnhash;
1302: }
1303:
1304: sub inst_userrules {
1305: my ($udom,$check) = @_;
1306: my (%ruleshash,@ruleorder);
1307: if ($udom ne '') {
1308: my $homeserver=&domain($udom,'primary');
1309: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1310: my $response;
1311: if ($check eq 'id') {
1312: $response=&reply('instidrules:'.&escape($udom),
1313: $homeserver);
1314: } elsif ($check eq 'email') {
1315: $response=&reply('instemailrules:'.&escape($udom),
1316: $homeserver);
1317: } else {
1318: $response=&reply('instuserrules:'.&escape($udom),
1319: $homeserver);
1320: }
1321: if (($response ne 'refused') && ($response ne 'error') &&
1322: ($response ne 'unknown_cmd') &&
1323: ($response ne 'no_such_host')) {
1324: my ($hashitems,$orderitems) = split(/:/,$response);
1325: my @pairs=split(/\&/,$hashitems);
1326: foreach my $item (@pairs) {
1327: my ($key,$value)=split(/=/,$item,2);
1328: $key = &unescape($key);
1329: next if ($key =~ /^error: 2 /);
1330: $ruleshash{$key}=&thaw_unescape($value);
1331: }
1332: my @esc_order = split(/\&/,$orderitems);
1333: foreach my $item (@esc_order) {
1334: push(@ruleorder,&unescape($item));
1335: }
1336: }
1337: }
1338: }
1339: return (\%ruleshash,\@ruleorder);
1340: }
1341:
1342: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1343:
1344: sub get_domain_defaults {
1345: my ($domain) = @_;
1346: my $cachetime = 60*60*24;
1347: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1348: if (defined($cached)) {
1349: if (ref($result) eq 'HASH') {
1350: return %{$result};
1351: }
1352: }
1353: my %domdefaults;
1354: my %domconfig =
1355: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1356: 'requestcourses','inststatus'],$domain);
1357: if (ref($domconfig{'defaults'}) eq 'HASH') {
1358: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1359: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1360: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1361: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1362: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1363: } else {
1364: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1365: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1366: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1367: }
1368: if (ref($domconfig{'quotas'}) eq 'HASH') {
1369: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1370: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1371: } else {
1372: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1373: }
1374: my @usertools = ('aboutme','blog','portfolio');
1375: foreach my $item (@usertools) {
1376: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1377: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1378: }
1379: }
1380: }
1381: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1382: foreach my $item ('official','unofficial','community') {
1383: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1384: }
1385: }
1386: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1387: foreach my $item ('inststatustypes','inststatusorder') {
1388: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1389: }
1390: }
1391: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1392: $cachetime);
1393: return %domdefaults;
1394: }
1395:
1396: # --------------------------------------------------- Assign a key to a student
1397:
1398: sub assign_access_key {
1399: #
1400: # a valid key looks like uname:udom#comments
1401: # comments are being appended
1402: #
1403: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1404: $kdom=
1405: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1406: $knum=
1407: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1408: $cdom=
1409: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1410: $cnum=
1411: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1412: $udom=$env{'user.name'} unless (defined($udom));
1413: $uname=$env{'user.domain'} unless (defined($uname));
1414: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1415: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1416: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1417: # assigned to this person
1418: # - this should not happen,
1419: # unless something went wrong
1420: # the first time around
1421: # ready to assign
1422: $logentry=$1.'; '.$logentry;
1423: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1424: $kdom,$knum) eq 'ok') {
1425: # key now belongs to user
1426: my $envkey='key.'.$cdom.'_'.$cnum;
1427: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1428: &appenv({'environment.'.$envkey => $ckey});
1429: return 'ok';
1430: } else {
1431: return
1432: 'error: Count not permanently assign key, will need to be re-entered later.';
1433: }
1434: } else {
1435: return 'error: Could not assign key, try again later.';
1436: }
1437: } elsif (!$existing{$ckey}) {
1438: # the key does not exist
1439: return 'error: The key does not exist';
1440: } else {
1441: # the key is somebody else's
1442: return 'error: The key is already in use';
1443: }
1444: }
1445:
1446: # ------------------------------------------ put an additional comment on a key
1447:
1448: sub comment_access_key {
1449: #
1450: # a valid key looks like uname:udom#comments
1451: # comments are being appended
1452: #
1453: my ($ckey,$cdom,$cnum,$logentry)=@_;
1454: $cdom=
1455: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1456: $cnum=
1457: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1458: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1459: if ($existing{$ckey}) {
1460: $existing{$ckey}.='; '.$logentry;
1461: # ready to assign
1462: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1463: $cdom,$cnum) eq 'ok') {
1464: return 'ok';
1465: } else {
1466: return 'error: Count not store comment.';
1467: }
1468: } else {
1469: # the key does not exist
1470: return 'error: The key does not exist';
1471: }
1472: }
1473:
1474: # ------------------------------------------------------ Generate a set of keys
1475:
1476: sub generate_access_keys {
1477: my ($number,$cdom,$cnum,$logentry)=@_;
1478: $cdom=
1479: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1480: $cnum=
1481: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1482: unless (&allowed('mky',$cdom)) { return 0; }
1483: unless (($cdom) && ($cnum)) { return 0; }
1484: if ($number>10000) { return 0; }
1485: sleep(2); # make sure don't get same seed twice
1486: srand(time()^($$+($$<<15))); # from "Programming Perl"
1487: my $total=0;
1488: for (my $i=1;$i<=$number;$i++) {
1489: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1490: sprintf("%lx",int(100000*rand)).'-'.
1491: sprintf("%lx",int(100000*rand));
1492: $newkey=~s/1/g/g; # folks mix up 1 and l
1493: $newkey=~s/0/h/g; # and also 0 and O
1494: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1495: if ($existing{$newkey}) {
1496: $i--;
1497: } else {
1498: if (&put('accesskeys',
1499: { $newkey => '# generated '.localtime().
1500: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1501: '; '.$logentry },
1502: $cdom,$cnum) eq 'ok') {
1503: $total++;
1504: }
1505: }
1506: }
1507: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1508: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1509: return $total;
1510: }
1511:
1512: # ------------------------------------------------------- Validate an accesskey
1513:
1514: sub validate_access_key {
1515: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1516: $cdom=
1517: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1518: $cnum=
1519: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1520: $udom=$env{'user.domain'} unless (defined($udom));
1521: $uname=$env{'user.name'} unless (defined($uname));
1522: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1523: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1524: }
1525:
1526: # ------------------------------------- Find the section of student in a course
1527: sub devalidate_getsection_cache {
1528: my ($udom,$unam,$courseid)=@_;
1529: my $hashid="$udom:$unam:$courseid";
1530: &devalidate_cache_new('getsection',$hashid);
1531: }
1532:
1533: sub courseid_to_courseurl {
1534: my ($courseid) = @_;
1535: #already url style courseid
1536: return $courseid if ($courseid =~ m{^/});
1537:
1538: if (exists($env{'course.'.$courseid.'.num'})) {
1539: my $cnum = $env{'course.'.$courseid.'.num'};
1540: my $cdom = $env{'course.'.$courseid.'.domain'};
1541: return "/$cdom/$cnum";
1542: }
1543:
1544: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1545: if (exists($courseinfo{'num'})) {
1546: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1547: }
1548:
1549: return undef;
1550: }
1551:
1552: sub getsection {
1553: my ($udom,$unam,$courseid)=@_;
1554: my $cachetime=1800;
1555:
1556: my $hashid="$udom:$unam:$courseid";
1557: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1558: if (defined($cached)) { return $result; }
1559:
1560: my %Pending;
1561: my %Expired;
1562: #
1563: # Each role can either have not started yet (pending), be active,
1564: # or have expired.
1565: #
1566: # If there is an active role, we are done.
1567: #
1568: # If there is more than one role which has not started yet,
1569: # choose the one which will start sooner
1570: # If there is one role which has not started yet, return it.
1571: #
1572: # If there is more than one expired role, choose the one which ended last.
1573: # If there is a role which has expired, return it.
1574: #
1575: $courseid = &courseid_to_courseurl($courseid);
1576: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1577: foreach my $key (keys(%roleshash)) {
1578: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1579: my $section=$1;
1580: if ($key eq $courseid.'_st') { $section=''; }
1581: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1582: my $now=time;
1583: if (defined($end) && $end && ($now > $end)) {
1584: $Expired{$end}=$section;
1585: next;
1586: }
1587: if (defined($start) && $start && ($now < $start)) {
1588: $Pending{$start}=$section;
1589: next;
1590: }
1591: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1592: }
1593: #
1594: # Presumedly there will be few matching roles from the above
1595: # loop and the sorting time will be negligible.
1596: if (scalar(keys(%Pending))) {
1597: my ($time) = sort {$a <=> $b} keys(%Pending);
1598: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1599: }
1600: if (scalar(keys(%Expired))) {
1601: my @sorted = sort {$a <=> $b} keys(%Expired);
1602: my $time = pop(@sorted);
1603: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1604: }
1605: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1606: }
1607:
1608: sub save_cache {
1609: &purge_remembered();
1610: #&Apache::loncommon::validate_page();
1611: undef(%env);
1612: undef($env_loaded);
1613: }
1614:
1615: my $to_remember=-1;
1616: my %remembered;
1617: my %accessed;
1618: my $kicks=0;
1619: my $hits=0;
1620: sub make_key {
1621: my ($name,$id) = @_;
1622: if (length($id) > 65
1623: && length(&escape($id)) > 200) {
1624: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1625: }
1626: return &escape($name.':'.$id);
1627: }
1628:
1629: sub devalidate_cache_new {
1630: my ($name,$id,$debug) = @_;
1631: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1632: $id=&make_key($name,$id);
1633: $memcache->delete($id);
1634: delete($remembered{$id});
1635: delete($accessed{$id});
1636: }
1637:
1638: sub is_cached_new {
1639: my ($name,$id,$debug) = @_;
1640: $id=&make_key($name,$id);
1641: if (exists($remembered{$id})) {
1642: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1643: $accessed{$id}=[&gettimeofday()];
1644: $hits++;
1645: return ($remembered{$id},1);
1646: }
1647: my $value = $memcache->get($id);
1648: if (!(defined($value))) {
1649: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1650: return (undef,undef);
1651: }
1652: if ($value eq '__undef__') {
1653: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1654: $value=undef;
1655: }
1656: &make_room($id,$value,$debug);
1657: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1658: return ($value,1);
1659: }
1660:
1661: sub do_cache_new {
1662: my ($name,$id,$value,$time,$debug) = @_;
1663: $id=&make_key($name,$id);
1664: my $setvalue=$value;
1665: if (!defined($setvalue)) {
1666: $setvalue='__undef__';
1667: }
1668: if (!defined($time) ) {
1669: $time=600;
1670: }
1671: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1672: my $result = $memcache->set($id,$setvalue,$time);
1673: if (! $result) {
1674: &logthis("caching of id -> $id failed");
1675: $memcache->disconnect_all();
1676: }
1677: # need to make a copy of $value
1678: &make_room($id,$value,$debug);
1679: return $value;
1680: }
1681:
1682: sub make_room {
1683: my ($id,$value,$debug)=@_;
1684:
1685: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1686: : $value;
1687: if ($to_remember<0) { return; }
1688: $accessed{$id}=[&gettimeofday()];
1689: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1690: my $to_kick;
1691: my $max_time=0;
1692: foreach my $other (keys(%accessed)) {
1693: if (&tv_interval($accessed{$other}) > $max_time) {
1694: $to_kick=$other;
1695: $max_time=&tv_interval($accessed{$other});
1696: }
1697: }
1698: delete($remembered{$to_kick});
1699: delete($accessed{$to_kick});
1700: $kicks++;
1701: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1702: return;
1703: }
1704:
1705: sub purge_remembered {
1706: #&logthis("Tossing ".scalar(keys(%remembered)));
1707: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1708: undef(%remembered);
1709: undef(%accessed);
1710: }
1711: # ------------------------------------- Read an entry from a user's environment
1712:
1713: sub userenvironment {
1714: my ($udom,$unam,@what)=@_;
1715: my $items;
1716: foreach my $item (@what) {
1717: $items.=&escape($item).'&';
1718: }
1719: $items=~s/\&$//;
1720: my %returnhash=();
1721: my $uhome = &homeserver($unam,$udom);
1722: unless ($uhome eq 'no_host') {
1723: my @answer=split(/\&/,
1724: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1725: my $i;
1726: for ($i=0;$i<=$#what;$i++) {
1727: $returnhash{$what[$i]}=&unescape($answer[$i]);
1728: }
1729: }
1730: return %returnhash;
1731: }
1732:
1733: # ---------------------------------------------------------- Get a studentphoto
1734: sub studentphoto {
1735: my ($udom,$unam,$ext) = @_;
1736: my $home=&Apache::lonnet::homeserver($unam,$udom);
1737: if (defined($env{'request.course.id'})) {
1738: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1739: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1740: return(&retrievestudentphoto($udom,$unam,$ext));
1741: } else {
1742: my ($result,$perm_reqd)=
1743: &Apache::lonnet::auto_photo_permission($unam,$udom);
1744: if ($result eq 'ok') {
1745: if (!($perm_reqd eq 'yes')) {
1746: return(&retrievestudentphoto($udom,$unam,$ext));
1747: }
1748: }
1749: }
1750: }
1751: } else {
1752: my ($result,$perm_reqd) =
1753: &Apache::lonnet::auto_photo_permission($unam,$udom);
1754: if ($result eq 'ok') {
1755: if (!($perm_reqd eq 'yes')) {
1756: return(&retrievestudentphoto($udom,$unam,$ext));
1757: }
1758: }
1759: }
1760: return '/adm/lonKaputt/lonlogo_broken.gif';
1761: }
1762:
1763: sub retrievestudentphoto {
1764: my ($udom,$unam,$ext,$type) = @_;
1765: my $home=&Apache::lonnet::homeserver($unam,$udom);
1766: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1767: if ($ret eq 'ok') {
1768: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1769: if ($type eq 'thumbnail') {
1770: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1771: }
1772: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1773: return $tokenurl;
1774: } else {
1775: if ($type eq 'thumbnail') {
1776: return '/adm/lonKaputt/genericstudent_tn.gif';
1777: } else {
1778: return '/adm/lonKaputt/lonlogo_broken.gif';
1779: }
1780: }
1781: }
1782:
1783: # -------------------------------------------------------------------- New chat
1784:
1785: sub chatsend {
1786: my ($newentry,$anon,$group)=@_;
1787: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1788: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1789: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1790: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1791: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1792: &escape($newentry)).':'.$group,$chome);
1793: }
1794:
1795: # ------------------------------------------ Find current version of a resource
1796:
1797: sub getversion {
1798: my $fname=&clutter(shift);
1799: unless ($fname=~/^\/res\//) { return -1; }
1800: return ¤tversion(&filelocation('',$fname));
1801: }
1802:
1803: sub currentversion {
1804: my $fname=shift;
1805: my ($result,$cached)=&is_cached_new('resversion',$fname);
1806: if (defined($cached)) { return $result; }
1807: my $author=$fname;
1808: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1809: my ($udom,$uname)=split(/\//,$author);
1810: my $home=homeserver($uname,$udom);
1811: if ($home eq 'no_host') {
1812: return -1;
1813: }
1814: my $answer=reply("currentversion:$fname",$home);
1815: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1816: return -1;
1817: }
1818: return &do_cache_new('resversion',$fname,$answer,600);
1819: }
1820:
1821: # ----------------------------- Subscribe to a resource, return URL if possible
1822:
1823: sub subscribe {
1824: my $fname=shift;
1825: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1826: $fname=~s/[\n\r]//g;
1827: my $author=$fname;
1828: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1829: my ($udom,$uname)=split(/\//,$author);
1830: my $home=homeserver($uname,$udom);
1831: if ($home eq 'no_host') {
1832: return 'not_found';
1833: }
1834: my $answer=reply("sub:$fname",$home);
1835: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1836: $answer.=' by '.$home;
1837: }
1838: return $answer;
1839: }
1840:
1841: # -------------------------------------------------------------- Replicate file
1842:
1843: sub repcopy {
1844: my $filename=shift;
1845: $filename=~s/\/+/\//g;
1846: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1847: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1848: if ($filename=~m|^/home/httpd/html/userfiles/| or
1849: $filename=~m -^/*(uploaded|editupload)/-) {
1850: return &repcopy_userfile($filename);
1851: }
1852: $filename=~s/[\n\r]//g;
1853: my $transname="$filename.in.transfer";
1854: # FIXME: this should flock
1855: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1856: my $remoteurl=subscribe($filename);
1857: if ($remoteurl =~ /^con_lost by/) {
1858: &logthis("Subscribe returned $remoteurl: $filename");
1859: return 'unavailable';
1860: } elsif ($remoteurl eq 'not_found') {
1861: #&logthis("Subscribe returned not_found: $filename");
1862: return 'not_found';
1863: } elsif ($remoteurl =~ /^rejected by/) {
1864: &logthis("Subscribe returned $remoteurl: $filename");
1865: return 'forbidden';
1866: } elsif ($remoteurl eq 'directory') {
1867: return 'ok';
1868: } else {
1869: my $author=$filename;
1870: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1871: my ($udom,$uname)=split(/\//,$author);
1872: my $home=homeserver($uname,$udom);
1873: unless ($home eq $perlvar{'lonHostID'}) {
1874: my @parts=split(/\//,$filename);
1875: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1876: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1877: &logthis("Malconfiguration for replication: $filename");
1878: return 'bad_request';
1879: }
1880: my $count;
1881: for ($count=5;$count<$#parts;$count++) {
1882: $path.="/$parts[$count]";
1883: if ((-e $path)!=1) {
1884: mkdir($path,0777);
1885: }
1886: }
1887: my $ua=new LWP::UserAgent;
1888: my $request=new HTTP::Request('GET',"$remoteurl");
1889: my $response=$ua->request($request,$transname);
1890: if ($response->is_error()) {
1891: unlink($transname);
1892: my $message=$response->status_line;
1893: &logthis("<font color=\"blue\">WARNING:"
1894: ." LWP get: $message: $filename</font>");
1895: return 'unavailable';
1896: } else {
1897: if ($remoteurl!~/\.meta$/) {
1898: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1899: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1900: if ($mresponse->is_error()) {
1901: unlink($filename.'.meta');
1902: &logthis(
1903: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1904: }
1905: }
1906: rename($transname,$filename);
1907: return 'ok';
1908: }
1909: }
1910: }
1911: }
1912:
1913: # ------------------------------------------------ Get server side include body
1914: sub ssi_body {
1915: my ($filelink,%form)=@_;
1916: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1917: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1918: }
1919: my $output='';
1920: my $response;
1921: if ($filelink=~/^https?\:/) {
1922: ($output,$response)=&externalssi($filelink);
1923: } else {
1924: $filelink .= $filelink=~/\?/ ? '&' : '?';
1925: $filelink .= 'inhibitmenu=yes';
1926: ($output,$response)=&ssi($filelink,%form);
1927: }
1928: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1929: $output=~s/^.*?\<body[^\>]*\>//si;
1930: $output=~s/\<\/body\s*\>.*?$//si;
1931: if (wantarray) {
1932: return ($output, $response);
1933: } else {
1934: return $output;
1935: }
1936: }
1937:
1938: # --------------------------------------------------------- Server Side Include
1939:
1940: sub absolute_url {
1941: my ($host_name) = @_;
1942: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1943: if ($host_name eq '') {
1944: $host_name = $ENV{'SERVER_NAME'};
1945: }
1946: return $protocol.$host_name;
1947: }
1948:
1949: #
1950: # Server side include.
1951: # Parameters:
1952: # fn Possibly encrypted resource name/id.
1953: # form Hash that describes how the rendering should be done
1954: # and other things.
1955: # Returns:
1956: # Scalar context: The content of the response.
1957: # Array context: 2 element list of the content and the full response object.
1958: #
1959: sub ssi {
1960:
1961: my ($fn,%form)=@_;
1962: my $ua=new LWP::UserAgent;
1963: my $request;
1964:
1965: $form{'no_update_last_known'}=1;
1966: &Apache::lonenc::check_encrypt(\$fn);
1967: if (%form) {
1968: $request=new HTTP::Request('POST',&absolute_url().$fn);
1969: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1970: } else {
1971: $request=new HTTP::Request('GET',&absolute_url().$fn);
1972: }
1973:
1974: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1975: my $response=$ua->request($request);
1976:
1977: if (wantarray) {
1978: return ($response->content, $response);
1979: } else {
1980: return $response->content;
1981: }
1982: }
1983:
1984: sub externalssi {
1985: my ($url)=@_;
1986: my $ua=new LWP::UserAgent;
1987: my $request=new HTTP::Request('GET',$url);
1988: my $response=$ua->request($request);
1989: if (wantarray) {
1990: return ($response->content, $response);
1991: } else {
1992: return $response->content;
1993: }
1994: }
1995:
1996: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1997:
1998: sub allowuploaded {
1999: my ($srcurl,$url)=@_;
2000: $url=&clutter(&declutter($url));
2001: my $dir=$url;
2002: $dir=~s/\/[^\/]+$//;
2003: my %httpref=();
2004: my $httpurl=&hreflocation('',$url);
2005: $httpref{'httpref.'.$httpurl}=$srcurl;
2006: &Apache::lonnet::appenv(\%httpref);
2007: }
2008:
2009: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
2010: # input: action, courseID, current domain, intended
2011: # path to file, source of file, instruction to parse file for objects,
2012: # ref to hash for embedded objects,
2013: # ref to hash for codebase of java objects.
2014: #
2015: # output: url to file (if action was uploaddoc),
2016: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
2017: #
2018: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2019: # course.
2020: #
2021: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2022: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2023: # course's home server.
2024: #
2025: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2026: # be copied from $source (current location) to
2027: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2028: # and will then be copied to
2029: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2030: # course's home server.
2031: #
2032: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2033: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
2034: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2035: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2036: # in course's home server.
2037: #
2038:
2039: sub process_coursefile {
2040: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
2041: my $fetchresult;
2042: my $home=&homeserver($docuname,$docudom);
2043: if ($action eq 'propagate') {
2044: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2045: $home);
2046: } else {
2047: my $fpath = '';
2048: my $fname = $file;
2049: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2050: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2051: my $filepath = &build_filepath($fpath);
2052: if ($action eq 'copy') {
2053: if ($source eq '') {
2054: $fetchresult = 'no source file';
2055: return $fetchresult;
2056: } else {
2057: my $destination = $filepath.'/'.$fname;
2058: rename($source,$destination);
2059: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2060: $home);
2061: }
2062: } elsif ($action eq 'uploaddoc') {
2063: open(my $fh,'>'.$filepath.'/'.$fname);
2064: print $fh $env{'form.'.$source};
2065: close($fh);
2066: if ($parser eq 'parse') {
2067: my $mm = new File::MMagic;
2068: my $mime_type = $mm->checktype_filename($filepath.'/'.$fname);
2069: if ($mime_type eq 'text/html') {
2070: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2071: unless ($parse_result eq 'ok') {
2072: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2073: }
2074: }
2075: }
2076: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2077: $home);
2078: if ($fetchresult eq 'ok') {
2079: return '/uploaded/'.$fpath.'/'.$fname;
2080: } else {
2081: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2082: ' to host '.$home.': '.$fetchresult);
2083: return '/adm/notfound.html';
2084: }
2085: }
2086: }
2087: unless ( $fetchresult eq 'ok') {
2088: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2089: ' to host '.$home.': '.$fetchresult);
2090: }
2091: return $fetchresult;
2092: }
2093:
2094: sub build_filepath {
2095: my ($fpath) = @_;
2096: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2097: unless ($fpath eq '') {
2098: my @parts=split('/',$fpath);
2099: foreach my $part (@parts) {
2100: $filepath.= '/'.$part;
2101: if ((-e $filepath)!=1) {
2102: mkdir($filepath,0777);
2103: }
2104: }
2105: }
2106: return $filepath;
2107: }
2108:
2109: sub store_edited_file {
2110: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
2111: my $file = $primary_url;
2112: $file =~ s#^/uploaded/$docudom/$docuname/##;
2113: my $fpath = '';
2114: my $fname = $file;
2115: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2116: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2117: my $filepath = &build_filepath($fpath);
2118: open(my $fh,'>'.$filepath.'/'.$fname);
2119: print $fh $content;
2120: close($fh);
2121: my $home=&homeserver($docuname,$docudom);
2122: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2123: $home);
2124: if ($$fetchresult eq 'ok') {
2125: return '/uploaded/'.$fpath.'/'.$fname;
2126: } else {
2127: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2128: ' to host '.$home.': '.$$fetchresult);
2129: return '/adm/notfound.html';
2130: }
2131: }
2132:
2133: sub clean_filename {
2134: my ($fname,$args)=@_;
2135: # Replace Windows backslashes by forward slashes
2136: $fname=~s/\\/\//g;
2137: if (!$args->{'keep_path'}) {
2138: # Get rid of everything but the actual filename
2139: $fname=~s/^.*\/([^\/]+)$/$1/;
2140: }
2141: # Replace spaces by underscores
2142: $fname=~s/\s+/\_/g;
2143: # Replace all other weird characters by nothing
2144: $fname=~s{[^/\w\.\-]}{}g;
2145: # Replace all .\d. sequences with _\d. so they no longer look like version
2146: # numbers
2147: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2148: return $fname;
2149: }
2150: #This Function check if a Image max 400px width and height 500px. If not then scale the image down
2151: sub resizeImage {
2152: my($img_url) = @_;
2153: my $ima = Image::Magick->new;
2154: $ima->Read($img_url);
2155: if($ima->Get('width') > 400)
2156: {
2157: my $factor = $ima->Get('width')/400;
2158: $ima->Scale( width=>400, height=>$ima->Get('height')/$factor );
2159: }
2160: if($ima->Get('height') > 500)
2161: {
2162: my $factor = $ima->Get('height')/500;
2163: $ima->Scale( width=>$ima->Get('width')/$factor, height=>500);
2164: }
2165:
2166: $ima->Write($img_url);
2167: }
2168:
2169: #Wrapper function for userphotoupload
2170: sub userphotoupload
2171: {
2172: my($formname,$subdir) = @_;
2173: $upload_photo_form = 1;
2174: return &userfileupload($formname,undef,$subdir);
2175: }
2176:
2177: # --------------- Take an uploaded file and put it into the userfiles directory
2178: # input: $formname - the contents of the file are in $env{"form.$formname"}
2179: # the desired filenam is in $env{"form.$formname.filename"}
2180: # $coursedoc - if true up to the current course
2181: # if false
2182: # $subdir - directory in userfile to store the file into
2183: # $parser - instruction to parse file for objects ($parser = parse)
2184: # $allfiles - reference to hash for embedded objects
2185: # $codebase - reference to hash for codebase of java objects
2186: # $desuname - username for permanent storage of uploaded file
2187: # $dsetudom - domain for permanaent storage of uploaded file
2188: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2189: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2190: #
2191: # output: url of file in userspace, or error: <message>
2192: # or /adm/notfound.html if failure to upload occurse
2193:
2194:
2195: sub userfileupload {
2196: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2197: $destudom,$thumbwidth,$thumbheight)=@_;
2198: if (!defined($subdir)) { $subdir='unknown'; }
2199: my $fname=$env{'form.'.$formname.'.filename'};
2200: $fname=&clean_filename($fname);
2201: # See if there is anything left
2202: unless ($fname) { return 'error: no uploaded file'; }
2203: chop($env{'form.'.$formname});
2204: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2205: my $now = time;
2206: my $filepath = 'tmp/helprequests/'.$now;
2207: my @parts=split(/\//,$filepath);
2208: my $fullpath = $perlvar{'lonDaemons'};
2209: for (my $i=0;$i<@parts;$i++) {
2210: $fullpath .= '/'.$parts[$i];
2211: if ((-e $fullpath)!=1) {
2212: mkdir($fullpath,0777);
2213: }
2214: }
2215: open(my $fh,'>'.$fullpath.'/'.$fname);
2216: print $fh $env{'form.'.$formname};
2217: close($fh);
2218: return $fullpath.'/'.$fname;
2219: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2220: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2221: '_'.$env{'user.domain'}.'/pending';
2222: my @parts=split(/\//,$filepath);
2223: my $fullpath = $perlvar{'lonDaemons'};
2224: for (my $i=0;$i<@parts;$i++) {
2225: $fullpath .= '/'.$parts[$i];
2226: if ((-e $fullpath)!=1) {
2227: mkdir($fullpath,0777);
2228: }
2229: }
2230: open(my $fh,'>'.$fullpath.'/'.$fname);
2231: print $fh $env{'form.'.$formname};
2232: close($fh);
2233: return $fullpath.'/'.$fname;
2234: }
2235: if ($subdir eq 'scantron') {
2236: $fname = 'scantron_orig_'.$fname;
2237: } else {
2238: # Create the directory if not present
2239: $fname="$subdir/$fname";
2240: }
2241: if ($coursedoc) {
2242: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2243: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2244: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2245: return &finishuserfileupload($docuname,$docudom,
2246: $formname,$fname,$parser,$allfiles,
2247: $codebase,$thumbwidth,$thumbheight);
2248: } else {
2249: $fname=$env{'form.folder'}.'/'.$fname;
2250: return &process_coursefile('uploaddoc',$docuname,$docudom,
2251: $fname,$formname,$parser,
2252: $allfiles,$codebase);
2253: }
2254: } elsif (defined($destuname)) {
2255: my $docuname=$destuname;
2256: my $docudom=$destudom;
2257: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2258: $parser,$allfiles,$codebase,
2259: $thumbwidth,$thumbheight);
2260:
2261: } else {
2262: my $docuname=$env{'user.name'};
2263: my $docudom=$env{'user.domain'};
2264: if (exists($env{'form.group'})) {
2265: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2266: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2267: }
2268: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2269: $parser,$allfiles,$codebase,
2270: $thumbwidth,$thumbheight);
2271: }
2272: }
2273:
2274: sub finishuserfileupload {
2275: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2276: $thumbwidth,$thumbheight) = @_;
2277: my $path=$docudom.'/'.$docuname.'/';
2278: my $filepath=$perlvar{'lonDocRoot'};
2279:
2280: my ($fnamepath,$file,$fetchthumb);
2281: $file=$fname;
2282: if ($fname=~m|/|) {
2283: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2284: $path.=$fnamepath.'/';
2285: }
2286: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2287: my $count;
2288: for ($count=4;$count<=$#parts;$count++) {
2289: $filepath.="/$parts[$count]";
2290: if ((-e $filepath)!=1) {
2291: mkdir($filepath,0777);
2292: }
2293: }
2294:
2295: # Save the file
2296: {
2297: if (!open(FH,'>'.$filepath.'/'.$file)) {
2298: &logthis('Failed to create '.$filepath.'/'.$file);
2299: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2300: return '/adm/notfound.html';
2301: }
2302: if (!print FH ($env{'form.'.$formname})) {
2303: &logthis('Failed to write to '.$filepath.'/'.$file);
2304: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2305: return '/adm/notfound.html';
2306: }
2307: close(FH);
2308: if($upload_photo_form==1)
2309: {
2310: resizeImage($filepath.'/'.$file);
2311: $upload_photo_form = 0;
2312: }
2313: }
2314: if ($parser eq 'parse') {
2315: my $mm = new File::MMagic;
2316: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2317: if ($mime_type eq 'text/html') {
2318: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2319: $allfiles,$codebase);
2320: unless ($parse_result eq 'ok') {
2321: &logthis('Failed to parse '.$filepath.$file.
2322: ' for embedded media: '.$parse_result);
2323: }
2324: }
2325: }
2326: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2327: my $input = $filepath.'/'.$file;
2328: my $output = $filepath.'/'.'tn-'.$file;
2329: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2330: system("convert -sample $thumbsize $input $output");
2331: if (-e $filepath.'/'.'tn-'.$file) {
2332: $fetchthumb = 1;
2333: }
2334: }
2335:
2336: # Notify homeserver to grep it
2337: #
2338: my $docuhome=&homeserver($docuname,$docudom);
2339: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2340: if ($fetchresult eq 'ok') {
2341: if ($fetchthumb) {
2342: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2343: if ($thumbresult ne 'ok') {
2344: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2345: $docuhome.': '.$thumbresult);
2346: }
2347: }
2348: #
2349: # Return the URL to it
2350: return '/uploaded/'.$path.$file;
2351: } else {
2352: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2353: ': '.$fetchresult);
2354: return '/adm/notfound.html';
2355: }
2356: }
2357:
2358: sub extract_embedded_items {
2359: my ($fullpath,$allfiles,$codebase,$content) = @_;
2360: my @state = ();
2361: my %javafiles = (
2362: codebase => '',
2363: code => '',
2364: archive => ''
2365: );
2366: my %mediafiles = (
2367: src => '',
2368: movie => '',
2369: );
2370: my $p;
2371: if ($content) {
2372: $p = HTML::LCParser->new($content);
2373: } else {
2374: $p = HTML::LCParser->new($fullpath);
2375: }
2376: while (my $t=$p->get_token()) {
2377: if ($t->[0] eq 'S') {
2378: my ($tagname, $attr) = ($t->[1],$t->[2]);
2379: push(@state, $tagname);
2380: if (lc($tagname) eq 'allow') {
2381: &add_filetype($allfiles,$attr->{'src'},'src');
2382: }
2383: if (lc($tagname) eq 'img') {
2384: &add_filetype($allfiles,$attr->{'src'},'src');
2385: }
2386: if (lc($tagname) eq 'a') {
2387: &add_filetype($allfiles,$attr->{'href'},'href');
2388: }
2389: if (lc($tagname) eq 'script') {
2390: if ($attr->{'archive'} =~ /\.jar$/i) {
2391: &add_filetype($allfiles,$attr->{'archive'},'archive');
2392: } else {
2393: &add_filetype($allfiles,$attr->{'src'},'src');
2394: }
2395: }
2396: if (lc($tagname) eq 'link') {
2397: if (lc($attr->{'rel'}) eq 'stylesheet') {
2398: &add_filetype($allfiles,$attr->{'href'},'href');
2399: }
2400: }
2401: if (lc($tagname) eq 'object' ||
2402: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2403: foreach my $item (keys(%javafiles)) {
2404: $javafiles{$item} = '';
2405: }
2406: }
2407: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2408: my $name = lc($attr->{'name'});
2409: foreach my $item (keys(%javafiles)) {
2410: if ($name eq $item) {
2411: $javafiles{$item} = $attr->{'value'};
2412: last;
2413: }
2414: }
2415: foreach my $item (keys(%mediafiles)) {
2416: if ($name eq $item) {
2417: &add_filetype($allfiles, $attr->{'value'}, 'value');
2418: last;
2419: }
2420: }
2421: }
2422: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2423: foreach my $item (keys(%javafiles)) {
2424: if ($attr->{$item}) {
2425: $javafiles{$item} = $attr->{$item};
2426: last;
2427: }
2428: }
2429: foreach my $item (keys(%mediafiles)) {
2430: if ($attr->{$item}) {
2431: &add_filetype($allfiles,$attr->{$item},$item);
2432: last;
2433: }
2434: }
2435: }
2436: } elsif ($t->[0] eq 'E') {
2437: my ($tagname) = ($t->[1]);
2438: if ($javafiles{'codebase'} ne '') {
2439: $javafiles{'codebase'} .= '/';
2440: }
2441: if (lc($tagname) eq 'applet' ||
2442: lc($tagname) eq 'object' ||
2443: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2444: ) {
2445: foreach my $item (keys(%javafiles)) {
2446: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2447: my $file=$javafiles{'codebase'}.$javafiles{$item};
2448: &add_filetype($allfiles,$file,$item);
2449: }
2450: }
2451: }
2452: pop @state;
2453: }
2454: }
2455: return 'ok';
2456: }
2457:
2458: sub add_filetype {
2459: my ($allfiles,$file,$type)=@_;
2460: if (exists($allfiles->{$file})) {
2461: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2462: push(@{$allfiles->{$file}}, &escape($type));
2463: }
2464: } else {
2465: @{$allfiles->{$file}} = (&escape($type));
2466: }
2467: }
2468:
2469: sub removeuploadedurl {
2470: my ($url)=@_;
2471: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
2472: return &removeuserfile($uname,$udom,$fname);
2473: }
2474:
2475: sub removeuserfile {
2476: my ($docuname,$docudom,$fname)=@_;
2477: my $home=&homeserver($docuname,$docudom);
2478: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2479: if ($result eq 'ok') {
2480: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2481: my $metafile = $fname.'.meta';
2482: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
2483: my $url = "/uploaded/$docudom/$docuname/$fname";
2484: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2485: my $sqlresult =
2486: &update_portfolio_table($docuname,$docudom,$file,
2487: 'portfolio_metadata',$group,
2488: 'delete');
2489: }
2490: }
2491: return $result;
2492: }
2493:
2494: sub mkdiruserfile {
2495: my ($docuname,$docudom,$dir)=@_;
2496: my $home=&homeserver($docuname,$docudom);
2497: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2498: }
2499:
2500: sub renameuserfile {
2501: my ($docuname,$docudom,$old,$new)=@_;
2502: my $home=&homeserver($docuname,$docudom);
2503: my $result = &reply("renameuserfile:$docudom:$docuname:".
2504: &escape("$old").':'.&escape("$new"),$home);
2505: if ($result eq 'ok') {
2506: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2507: my $oldmeta = $old.'.meta';
2508: my $newmeta = $new.'.meta';
2509: my $metaresult =
2510: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
2511: my $url = "/uploaded/$docudom/$docuname/$old";
2512: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2513: my $sqlresult =
2514: &update_portfolio_table($docuname,$docudom,$file,
2515: 'portfolio_metadata',$group,
2516: 'delete');
2517: }
2518: }
2519: return $result;
2520: }
2521:
2522: # ------------------------------------------------------------------------- Log
2523:
2524: sub log {
2525: my ($dom,$nam,$hom,$what)=@_;
2526: return critical("log:$dom:$nam:$what",$hom);
2527: }
2528:
2529: # ------------------------------------------------------------------ Course Log
2530: #
2531: # This routine flushes several buffers of non-mission-critical nature
2532: #
2533:
2534: sub flushcourselogs {
2535: &logthis('Flushing log buffers');
2536: #
2537: # course logs
2538: # This is a log of all transactions in a course, which can be used
2539: # for data mining purposes
2540: #
2541: # It also collects the courseid database, which lists last transaction
2542: # times and course titles for all courseids
2543: #
2544: my %courseidbuffer=();
2545: foreach my $crsid (keys(%courselogs)) {
2546: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
2547: &escape($courselogs{$crsid}),
2548: $coursehombuf{$crsid}) eq 'ok') {
2549: delete $courselogs{$crsid};
2550: } else {
2551: &logthis('Failed to flush log buffer for '.$crsid);
2552: if (length($courselogs{$crsid})>40000) {
2553: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
2554: " exceeded maximum size, deleting.</font>");
2555: delete $courselogs{$crsid};
2556: }
2557: }
2558: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
2559: 'description' => $coursedescrbuf{$crsid},
2560: 'inst_code' => $courseinstcodebuf{$crsid},
2561: 'type' => $coursetypebuf{$crsid},
2562: 'owner' => $courseownerbuf{$crsid},
2563: };
2564: }
2565: #
2566: # Write course id database (reverse lookup) to homeserver of courses
2567: # Is used in pickcourse
2568: #
2569: foreach my $crs_home (keys(%courseidbuffer)) {
2570: my $response = &courseidput(&host_domain($crs_home),
2571: $courseidbuffer{$crs_home},
2572: $crs_home,'timeonly');
2573: }
2574: #
2575: # File accesses
2576: # Writes to the dynamic metadata of resources to get hit counts, etc.
2577: #
2578: foreach my $entry (keys(%accesshash)) {
2579: if ($entry =~ /___count$/) {
2580: my ($dom,$name);
2581: ($dom,$name,undef)=
2582: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
2583: if (! defined($dom) || $dom eq '' ||
2584: ! defined($name) || $name eq '') {
2585: my $cid = $env{'request.course.id'};
2586: $dom = $env{'request.'.$cid.'.domain'};
2587: $name = $env{'request.'.$cid.'.num'};
2588: }
2589: my $value = $accesshash{$entry};
2590: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2591: my %temphash=($url => $value);
2592: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2593: if ($result eq 'ok') {
2594: delete $accesshash{$entry};
2595: } elsif ($result eq 'unknown_cmd') {
2596: # Target server has old code running on it.
2597: my %temphash=($entry => $value);
2598: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2599: delete $accesshash{$entry};
2600: }
2601: }
2602: } else {
2603: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
2604: my %temphash=($entry => $accesshash{$entry});
2605: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2606: delete $accesshash{$entry};
2607: }
2608: }
2609: }
2610: #
2611: # Roles
2612: # Reverse lookup of user roles for course faculty/staff and co-authorship
2613: #
2614: foreach my $entry (keys(%userrolehash)) {
2615: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
2616: split(/\:/,$entry);
2617: if (&Apache::lonnet::put('nohist_userroles',
2618: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
2619: $rudom,$runame) eq 'ok') {
2620: delete $userrolehash{$entry};
2621: }
2622: }
2623: #
2624: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2625: #
2626: my %domrolebuffer = ();
2627: foreach my $entry (keys(%domainrolehash)) {
2628: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
2629: if ($domrolebuffer{$rudom}) {
2630: $domrolebuffer{$rudom}.='&'.&escape($entry).
2631: '='.&escape($domainrolehash{$entry});
2632: } else {
2633: $domrolebuffer{$rudom}.=&escape($entry).
2634: '='.&escape($domainrolehash{$entry});
2635: }
2636: delete $domainrolehash{$entry};
2637: }
2638: foreach my $dom (keys(%domrolebuffer)) {
2639: my %servers = &get_servers($dom,'library');
2640: foreach my $tryserver (keys(%servers)) {
2641: unless (&reply('domroleput:'.$dom.':'.
2642: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2643: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2644: }
2645: }
2646: }
2647: $dumpcount++;
2648: }
2649:
2650: sub courselog {
2651: my $what=shift;
2652: $what=time.':'.$what;
2653: unless ($env{'request.course.id'}) { return ''; }
2654: $coursedombuf{$env{'request.course.id'}}=
2655: $env{'course.'.$env{'request.course.id'}.'.domain'};
2656: $coursenumbuf{$env{'request.course.id'}}=
2657: $env{'course.'.$env{'request.course.id'}.'.num'};
2658: $coursehombuf{$env{'request.course.id'}}=
2659: $env{'course.'.$env{'request.course.id'}.'.home'};
2660: $coursedescrbuf{$env{'request.course.id'}}=
2661: $env{'course.'.$env{'request.course.id'}.'.description'};
2662: $courseinstcodebuf{$env{'request.course.id'}}=
2663: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2664: $courseownerbuf{$env{'request.course.id'}}=
2665: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
2666: $coursetypebuf{$env{'request.course.id'}}=
2667: $env{'course.'.$env{'request.course.id'}.'.type'};
2668: if (defined $courselogs{$env{'request.course.id'}}) {
2669: $courselogs{$env{'request.course.id'}}.='&'.$what;
2670: } else {
2671: $courselogs{$env{'request.course.id'}}.=$what;
2672: }
2673: if (length($courselogs{$env{'request.course.id'}})>4048) {
2674: &flushcourselogs();
2675: }
2676: }
2677:
2678: sub courseacclog {
2679: my $fnsymb=shift;
2680: unless ($env{'request.course.id'}) { return ''; }
2681: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2682: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2683: $what.=':POST';
2684: # FIXME: Probably ought to escape things....
2685: foreach my $key (keys(%env)) {
2686: if ($key=~/^form\.(.*)/) {
2687: my $formitem = $1;
2688: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2689: $what.=':'.$formitem.'='.$env{$key};
2690: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2691: $what.=':'.$formitem.'='.$env{$key};
2692: }
2693: }
2694: }
2695: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2696: # FIXME: We should not be depending on a form parameter that someone
2697: # editing lonsearchcat.pm might change in the future.
2698: if ($env{'form.phase'} eq 'course_search') {
2699: $what.= ':POST';
2700: # FIXME: Probably ought to escape things....
2701: foreach my $element ('courseexp','crsfulltext','crsrelated',
2702: 'crsdiscuss') {
2703: $what.=':'.$element.'='.$env{'form.'.$element};
2704: }
2705: }
2706: }
2707: &courselog($what);
2708: }
2709:
2710: sub countacc {
2711: my $url=&declutter(shift);
2712: return if (! defined($url) || $url eq '');
2713: unless ($env{'request.course.id'}) { return ''; }
2714: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2715: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2716: $accesshash{$key}++;
2717: }
2718:
2719: sub linklog {
2720: my ($from,$to)=@_;
2721: $from=&declutter($from);
2722: $to=&declutter($to);
2723: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2724: $accesshash{$to.'___'.$from.'___goto'}=1;
2725: }
2726:
2727: sub userrolelog {
2728: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2729: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2730: ($trole=~/^in/) || ($trole=~/^cc/) ||
2731: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2732: ($trole=~/^ta/)) {
2733: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2734: $userrolehash
2735: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2736: =$tend.':'.$tstart;
2737: }
2738: if (($env{'request.role'} =~ /dc\./) &&
2739: (($trole=~/^au/) || ($trole=~/^in/) ||
2740: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2741: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2742: $userrolehash
2743: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2744: =$tend.':'.$tstart;
2745: }
2746: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2747: ($trole=~/^li/) || ($trole=~/^li/) ||
2748: ($trole=~/^au/) || ($trole=~/^dg/) ||
2749: ($trole=~/^sc/)) {
2750: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2751: $domainrolehash
2752: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2753: = $tend.':'.$tstart;
2754: }
2755: }
2756:
2757: sub courserolelog {
2758: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2759: if (($trole eq 'cc') || ($trole eq 'in') ||
2760: ($trole eq 'ep') || ($trole eq 'ad') ||
2761: ($trole eq 'ta') || ($trole eq 'st') ||
2762: ($trole=~/^cr/) || ($trole eq 'gr')) {
2763: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2764: my $cdom = $1;
2765: my $cnum = $2;
2766: my $sec = $3;
2767: my $namespace = 'rolelog';
2768: my %storehash = (
2769: role => $trole,
2770: start => $tstart,
2771: end => $tend,
2772: selfenroll => $selfenroll,
2773: context => $context,
2774: );
2775: if ($trole eq 'gr') {
2776: $namespace = 'groupslog';
2777: $storehash{'group'} = $sec;
2778: } else {
2779: $storehash{'section'} = $sec;
2780: }
2781: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2782: if (($trole ne 'st') || ($sec ne '')) {
2783: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
2784: }
2785: }
2786: }
2787: return;
2788: }
2789:
2790: sub get_course_adv_roles {
2791: my ($cid,$codes) = @_;
2792: $cid=$env{'request.course.id'} unless (defined($cid));
2793: my %coursehash=&coursedescription($cid);
2794: my $crstype = &Apache::loncommon::course_type($cid);
2795: my %nothide=();
2796: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2797: if ($user !~ /:/) {
2798: $nothide{join(':',split(/[\@]/,$user))}=1;
2799: } else {
2800: $nothide{$user}=1;
2801: }
2802: }
2803: my %returnhash=();
2804: my %dumphash=
2805: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2806: my $now=time;
2807: my %privileged;
2808: foreach my $entry (keys(%dumphash)) {
2809: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2810: if (($tstart) && ($tstart<0)) { next; }
2811: if (($tend) && ($tend<$now)) { next; }
2812: if (($tstart) && ($now<$tstart)) { next; }
2813: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2814: if ($username eq '' || $domain eq '') { next; }
2815: unless (ref($privileged{$domain}) eq 'HASH') {
2816: my %dompersonnel =
2817: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2818: $privileged{$domain} = {};
2819: foreach my $server (keys(%dompersonnel)) {
2820: if (ref($dompersonnel{$server}) eq 'HASH') {
2821: foreach my $user (keys(%{$dompersonnel{$server}})) {
2822: my ($trole,$uname,$udom) = split(/:/,$user);
2823: $privileged{$udom}{$uname} = 1;
2824: }
2825: }
2826: }
2827: }
2828: if ((exists($privileged{$domain}{$username})) &&
2829: (!$nothide{$username.':'.$domain})) { next; }
2830: if ($role eq 'cr') { next; }
2831: if ($codes) {
2832: if ($section) { $role .= ':'.$section; }
2833: if ($returnhash{$role}) {
2834: $returnhash{$role}.=','.$username.':'.$domain;
2835: } else {
2836: $returnhash{$role}=$username.':'.$domain;
2837: }
2838: } else {
2839: my $key=&plaintext($role,$crstype);
2840: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
2841: if ($returnhash{$key}) {
2842: $returnhash{$key}.=','.$username.':'.$domain;
2843: } else {
2844: $returnhash{$key}=$username.':'.$domain;
2845: }
2846: }
2847: }
2848: return %returnhash;
2849: }
2850:
2851: sub get_my_roles {
2852: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
2853: unless (defined($uname)) { $uname=$env{'user.name'}; }
2854: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2855: my (%dumphash,%nothide);
2856: if ($context eq 'userroles') {
2857: %dumphash = &dump('roles',$udom,$uname);
2858: } else {
2859: %dumphash=
2860: &dump('nohist_userroles',$udom,$uname);
2861: if ($hidepriv) {
2862: my %coursehash=&coursedescription($udom.'_'.$uname);
2863: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2864: if ($user !~ /:/) {
2865: $nothide{join(':',split(/[\@]/,$user))} = 1;
2866: } else {
2867: $nothide{$user} = 1;
2868: }
2869: }
2870: }
2871: }
2872: my %returnhash=();
2873: my $now=time;
2874: my %privileged;
2875: foreach my $entry (keys(%dumphash)) {
2876: my ($role,$tend,$tstart);
2877: if ($context eq 'userroles') {
2878: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2879: } else {
2880: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2881: }
2882: if (($tstart) && ($tstart<0)) { next; }
2883: my $status = 'active';
2884: if (($tend) && ($tend<=$now)) {
2885: $status = 'previous';
2886: }
2887: if (($tstart) && ($now<$tstart)) {
2888: $status = 'future';
2889: }
2890: if (ref($types) eq 'ARRAY') {
2891: if (!grep(/^\Q$status\E$/,@{$types})) {
2892: next;
2893: }
2894: } else {
2895: if ($status ne 'active') {
2896: next;
2897: }
2898: }
2899: my ($rolecode,$username,$domain,$section,$area);
2900: if ($context eq 'userroles') {
2901: ($area,$rolecode) = split(/_/,$entry);
2902: (undef,$domain,$username,$section) = split(/\//,$area);
2903: } else {
2904: ($role,$username,$domain,$section) = split(/\:/,$entry);
2905: }
2906: if (ref($roledoms) eq 'ARRAY') {
2907: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2908: next;
2909: }
2910: }
2911: if (ref($roles) eq 'ARRAY') {
2912: if (!grep(/^\Q$role\E$/,@{$roles})) {
2913: if ($role =~ /^cr\//) {
2914: if (!grep(/^cr$/,@{$roles})) {
2915: next;
2916: }
2917: } else {
2918: next;
2919: }
2920: }
2921: }
2922: if ($hidepriv) {
2923: if ($context eq 'userroles') {
2924: if ((&privileged($username,$domain)) &&
2925: (!$nothide{$username.':'.$domain})) {
2926: next;
2927: }
2928: } else {
2929: unless (ref($privileged{$domain}) eq 'HASH') {
2930: my %dompersonnel =
2931: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
2932: $privileged{$domain} = {};
2933: if (keys(%dompersonnel)) {
2934: foreach my $server (keys(%dompersonnel)) {
2935: if (ref($dompersonnel{$server}) eq 'HASH') {
2936: foreach my $user (keys(%{$dompersonnel{$server}})) {
2937: my ($trole,$uname,$udom) = split(/:/,$user);
2938: $privileged{$udom}{$uname} = $trole;
2939: }
2940: }
2941: }
2942: }
2943: }
2944: if (exists($privileged{$domain}{$username})) {
2945: if (!$nothide{$username.':'.$domain}) {
2946: next;
2947: }
2948: }
2949: }
2950: }
2951: if ($withsec) {
2952: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2953: $tstart.':'.$tend;
2954: } else {
2955: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2956: }
2957: }
2958: return %returnhash;
2959: }
2960:
2961: # ----------------------------------------------------- Frontpage Announcements
2962: #
2963: #
2964:
2965: sub postannounce {
2966: my ($server,$text)=@_;
2967: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
2968: unless ($text=~/\w/) { $text=''; }
2969: return &reply('setannounce:'.&escape($text),$server);
2970: }
2971:
2972: sub getannounce {
2973:
2974: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2975: my $announcement='';
2976: while (my $line = <$fh>) { $announcement .= $line; }
2977: close($fh);
2978: if ($announcement=~/\w/) {
2979: return
2980: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2981: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2982: } else {
2983: return '';
2984: }
2985: } else {
2986: return '';
2987: }
2988: }
2989:
2990: # ---------------------------------------------------------- Course ID routines
2991: # Deal with domain's nohist_courseid.db files
2992: #
2993:
2994: sub courseidput {
2995: my ($domain,$storehash,$coursehome,$caller) = @_;
2996: my $outcome;
2997: if ($caller eq 'timeonly') {
2998: my $cids = '';
2999: foreach my $item (keys(%$storehash)) {
3000: $cids.=&escape($item).'&';
3001: }
3002: $cids=~s/\&$//;
3003: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3004: $coursehome);
3005: } else {
3006: my $items = '';
3007: foreach my $item (keys(%$storehash)) {
3008: $items.= &escape($item).'='.
3009: &freeze_escape($$storehash{$item}).'&';
3010: }
3011: $items=~s/\&$//;
3012: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3013: $coursehome);
3014: }
3015: if ($outcome eq 'unknown_cmd') {
3016: my $what;
3017: foreach my $cid (keys(%$storehash)) {
3018: $what .= &escape($cid).'=';
3019: foreach my $item ('description','inst_code','owner','type') {
3020: $what .= &escape($storehash->{$cid}{$item}).':';
3021: }
3022: $what =~ s/\:$/&/;
3023: }
3024: $what =~ s/\&$//;
3025: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3026: } else {
3027: return $outcome;
3028: }
3029: }
3030:
3031: sub courseiddump {
3032: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
3033: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
3034: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
3035: $cloneonly,$createdbefore,$createdafter,$creationcontext)=@_;
3036: my $as_hash = 1;
3037: my %returnhash;
3038: if (!$domfilter) { $domfilter=''; }
3039: my %libserv = &all_library();
3040: foreach my $tryserver (keys(%libserv)) {
3041: if ( ( $hostidflag == 1
3042: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3043: || (!defined($hostidflag)) ) {
3044:
3045: if (($domfilter eq '') ||
3046: (&host_domain($tryserver) eq $domfilter)) {
3047: my $rep =
3048: &reply('courseiddump:'.&host_domain($tryserver).':'.
3049: $sincefilter.':'.&escape($descfilter).':'.
3050: &escape($instcodefilter).':'.&escape($ownerfilter).
3051: ':'.&escape($coursefilter).':'.&escape($typefilter).
3052: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3053: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3054: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3055: &escape($cc_clone).':'.$cloneonly.':'.
3056: &escape($createdbefore).':'.&escape($createdafter).':'.
3057: &escape($creationcontext),$tryserver);
3058: my @pairs=split(/\&/,$rep);
3059: foreach my $item (@pairs) {
3060: my ($key,$value)=split(/\=/,$item,2);
3061: $key = &unescape($key);
3062: next if ($key =~ /^error: 2 /);
3063: my $result = &thaw_unescape($value);
3064: if (ref($result) eq 'HASH') {
3065: $returnhash{$key}=$result;
3066: } else {
3067: my @responses = split(/:/,$value);
3068: my @items = ('description','inst_code','owner','type');
3069: for (my $i=0; $i<@responses; $i++) {
3070: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
3071: }
3072: }
3073: }
3074: }
3075: }
3076: }
3077: return %returnhash;
3078: }
3079:
3080: # ---------------------------------------------------------- DC e-mail
3081:
3082: sub dcmailput {
3083: my ($domain,$msgid,$message,$server)=@_;
3084: my $status = &Apache::lonnet::critical(
3085: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3086: &escape($message),$server);
3087: return $status;
3088: }
3089:
3090: sub dcmaildump {
3091: my ($dom,$startdate,$enddate,$senders) = @_;
3092: my %returnhash=();
3093:
3094: if (defined(&domain($dom,'primary'))) {
3095: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3096: &escape($enddate).':';
3097: my @esc_senders=map { &escape($_)} @$senders;
3098: $cmd.=&escape(join('&',@esc_senders));
3099: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
3100: my ($key,$value) = split(/\=/,$line,2);
3101: if (($key) && ($value)) {
3102: $returnhash{&unescape($key)} = &unescape($value);
3103: }
3104: }
3105: }
3106: return %returnhash;
3107: }
3108: # ---------------------------------------------------------- Domain roles
3109:
3110: sub get_domain_roles {
3111: my ($dom,$roles,$startdate,$enddate)=@_;
3112: if ((!defined($startdate)) || ($startdate eq '')) {
3113: $startdate = '.';
3114: }
3115: if ((!defined($enddate)) || ($enddate eq '')) {
3116: $enddate = '.';
3117: }
3118: my $rolelist;
3119: if (ref($roles) eq 'ARRAY') {
3120: $rolelist = join(':',@{$roles});
3121: }
3122: my %personnel = ();
3123:
3124: my %servers = &get_servers($dom,'library');
3125: foreach my $tryserver (keys(%servers)) {
3126: %{$personnel{$tryserver}}=();
3127: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3128: &escape($startdate).':'.
3129: &escape($enddate).':'.
3130: &escape($rolelist), $tryserver))) {
3131: my ($key,$value) = split(/\=/,$line,2);
3132: if (($key) && ($value)) {
3133: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3134: }
3135: }
3136: }
3137: return %personnel;
3138: }
3139:
3140: # ----------------------------------------------------------- Check out an item
3141:
3142: sub get_first_access {
3143: my ($type,$argsymb)=@_;
3144: my ($symb,$courseid,$udom,$uname)=&whichuser();
3145: if ($argsymb) { $symb=$argsymb; }
3146: my ($map,$id,$res)=&decode_symb($symb);
3147: if ($type eq 'course') {
3148: $res='course';
3149: } elsif ($type eq 'map') {
3150: $res=&symbread($map);
3151: } else {
3152: $res=$symb;
3153: }
3154: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3155: return $times{"$courseid\0$res"};
3156: }
3157:
3158: sub set_first_access {
3159: my ($type)=@_;
3160: my ($symb,$courseid,$udom,$uname)=&whichuser();
3161: my ($map,$id,$res)=&decode_symb($symb);
3162: if ($type eq 'course') {
3163: $res='course';
3164: } elsif ($type eq 'map') {
3165: $res=&symbread($map);
3166: } else {
3167: $res=$symb;
3168: }
3169: my $firstaccess=&get_first_access($type,$symb);
3170: if (!$firstaccess) {
3171: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
3172: }
3173: return 'already_set';
3174: }
3175:
3176: sub checkout {
3177: my ($symb,$tuname,$tudom,$tcrsid)=@_;
3178: my $now=time;
3179: my $lonhost=$perlvar{'lonHostID'};
3180: my $infostr=&escape(
3181: 'CHECKOUTTOKEN&'.
3182: $tuname.'&'.
3183: $tudom.'&'.
3184: $tcrsid.'&'.
3185: $symb.'&'.
3186: $now.'&'.$ENV{'REMOTE_ADDR'});
3187: my $token=&reply('tmpput:'.$infostr,$lonhost);
3188: if ($token=~/^error\:/) {
3189: &logthis("<font color=\"blue\">WARNING: ".
3190: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
3191: "</font>");
3192: return '';
3193: }
3194:
3195: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
3196: $token=~tr/a-z/A-Z/;
3197:
3198: my %infohash=('resource.0.outtoken' => $token,
3199: 'resource.0.checkouttime' => $now,
3200: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
3201:
3202: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3203: return '';
3204: } else {
3205: &logthis("<font color=\"blue\">WARNING: ".
3206: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
3207: "</font>");
3208: }
3209:
3210: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3211: &escape('Checkout '.$infostr.' - '.
3212: $token)) ne 'ok') {
3213: return '';
3214: } else {
3215: &logthis("<font color=\"blue\">WARNING: ".
3216: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
3217: "</font>");
3218: }
3219: return $token;
3220: }
3221:
3222: # ------------------------------------------------------------ Check in an item
3223:
3224: sub checkin {
3225: my $token=shift;
3226: my $now=time;
3227: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3228: $lonhost=~tr/A-Z/a-z/;
3229: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
3230: $dtoken=~s/\W/\_/g;
3231: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
3232: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3233:
3234: unless (($tuname) && ($tudom)) {
3235: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3236: return '';
3237: }
3238:
3239: unless (&allowed('mgr',$tcrsid)) {
3240: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
3241: $env{'user.name'}.' - '.$env{'user.domain'});
3242: return '';
3243: }
3244:
3245: my %infohash=('resource.0.intoken' => $token,
3246: 'resource.0.checkintime' => $now,
3247: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
3248:
3249: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3250: return '';
3251: }
3252:
3253: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3254: &escape('Checkin - '.$token)) ne 'ok') {
3255: return '';
3256: }
3257:
3258: return ($symb,$tuname,$tudom,$tcrsid);
3259: }
3260:
3261: # --------------------------------------------- Set Expire Date for Spreadsheet
3262:
3263: sub expirespread {
3264: my ($uname,$udom,$stype,$usymb)=@_;
3265: my $cid=$env{'request.course.id'};
3266: if ($cid) {
3267: my $now=time;
3268: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3269: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3270: $env{'course.'.$cid.'.num'}.
3271: ':nohist_expirationdates:'.
3272: &escape($key).'='.$now,
3273: $env{'course.'.$cid.'.home'})
3274: }
3275: return 'ok';
3276: }
3277:
3278: # ----------------------------------------------------- Devalidate Spreadsheets
3279:
3280: sub devalidate {
3281: my ($symb,$uname,$udom)=@_;
3282: my $cid=$env{'request.course.id'};
3283: if ($cid) {
3284: # delete the stored spreadsheets for
3285: # - the student level sheet of this user in course's homespace
3286: # - the assessment level sheet for this resource
3287: # for this user in user's homespace
3288: # - current conditional state info
3289: my $key=$uname.':'.$udom.':';
3290: my $status=
3291: &del('nohist_calculatedsheets',
3292: [$key.'studentcalc:'],
3293: $env{'course.'.$cid.'.domain'},
3294: $env{'course.'.$cid.'.num'})
3295: .' '.
3296: &del('nohist_calculatedsheets_'.$cid,
3297: [$key.'assesscalc:'.$symb],$udom,$uname);
3298: unless ($status eq 'ok ok') {
3299: &logthis('Could not devalidate spreadsheet '.
3300: $uname.' at '.$udom.' for '.
3301: $symb.': '.$status);
3302: }
3303: &delenv('user.state.'.$cid);
3304: }
3305: }
3306:
3307: sub get_scalar {
3308: my ($string,$end) = @_;
3309: my $value;
3310: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3311: $value = $1;
3312: } elsif ($$string =~ s/^([^&]*?)&//) {
3313: $value = $1;
3314: }
3315: return &unescape($value);
3316: }
3317:
3318: sub array2str {
3319: my (@array) = @_;
3320: my $result=&arrayref2str(\@array);
3321: $result=~s/^__ARRAY_REF__//;
3322: $result=~s/__END_ARRAY_REF__$//;
3323: return $result;
3324: }
3325:
3326: sub arrayref2str {
3327: my ($arrayref) = @_;
3328: my $result='__ARRAY_REF__';
3329: foreach my $elem (@$arrayref) {
3330: if(ref($elem) eq 'ARRAY') {
3331: $result.=&arrayref2str($elem).'&';
3332: } elsif(ref($elem) eq 'HASH') {
3333: $result.=&hashref2str($elem).'&';
3334: } elsif(ref($elem)) {
3335: #print("Got a ref of ".(ref($elem))." skipping.");
3336: } else {
3337: $result.=&escape($elem).'&';
3338: }
3339: }
3340: $result=~s/\&$//;
3341: $result .= '__END_ARRAY_REF__';
3342: return $result;
3343: }
3344:
3345: sub hash2str {
3346: my (%hash) = @_;
3347: my $result=&hashref2str(\%hash);
3348: $result=~s/^__HASH_REF__//;
3349: $result=~s/__END_HASH_REF__$//;
3350: return $result;
3351: }
3352:
3353: sub hashref2str {
3354: my ($hashref)=@_;
3355: my $result='__HASH_REF__';
3356: foreach my $key (sort(keys(%$hashref))) {
3357: if (ref($key) eq 'ARRAY') {
3358: $result.=&arrayref2str($key).'=';
3359: } elsif (ref($key) eq 'HASH') {
3360: $result.=&hashref2str($key).'=';
3361: } elsif (ref($key)) {
3362: $result.='=';
3363: #print("Got a ref of ".(ref($key))." skipping.");
3364: } else {
3365: if ($key) {$result.=&escape($key).'=';} else { last; }
3366: }
3367:
3368: if(ref($hashref->{$key}) eq 'ARRAY') {
3369: $result.=&arrayref2str($hashref->{$key}).'&';
3370: } elsif(ref($hashref->{$key}) eq 'HASH') {
3371: $result.=&hashref2str($hashref->{$key}).'&';
3372: } elsif(ref($hashref->{$key})) {
3373: $result.='&';
3374: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3375: } else {
3376: $result.=&escape($hashref->{$key}).'&';
3377: }
3378: }
3379: $result=~s/\&$//;
3380: $result .= '__END_HASH_REF__';
3381: return $result;
3382: }
3383:
3384: sub str2hash {
3385: my ($string)=@_;
3386: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3387: return %$hash;
3388: }
3389:
3390: sub str2hashref {
3391: my ($string) = @_;
3392:
3393: my %hash;
3394:
3395: if($string !~ /^__HASH_REF__/) {
3396: if (! ($string eq '' || !defined($string))) {
3397: $hash{'error'}='Not hash reference';
3398: }
3399: return (\%hash, $string);
3400: }
3401:
3402: $string =~ s/^__HASH_REF__//;
3403:
3404: while($string !~ /^__END_HASH_REF__/) {
3405: #key
3406: my $key='';
3407: if($string =~ /^__HASH_REF__/) {
3408: ($key, $string)=&str2hashref($string);
3409: if(defined($key->{'error'})) {
3410: $hash{'error'}='Bad data';
3411: return (\%hash, $string);
3412: }
3413: } elsif($string =~ /^__ARRAY_REF__/) {
3414: ($key, $string)=&str2arrayref($string);
3415: if($key->[0] eq 'Array reference error') {
3416: $hash{'error'}='Bad data';
3417: return (\%hash, $string);
3418: }
3419: } else {
3420: $string =~ s/^(.*?)=//;
3421: $key=&unescape($1);
3422: }
3423: $string =~ s/^=//;
3424:
3425: #value
3426: my $value='';
3427: if($string =~ /^__HASH_REF__/) {
3428: ($value, $string)=&str2hashref($string);
3429: if(defined($value->{'error'})) {
3430: $hash{'error'}='Bad data';
3431: return (\%hash, $string);
3432: }
3433: } elsif($string =~ /^__ARRAY_REF__/) {
3434: ($value, $string)=&str2arrayref($string);
3435: if($value->[0] eq 'Array reference error') {
3436: $hash{'error'}='Bad data';
3437: return (\%hash, $string);
3438: }
3439: } else {
3440: $value=&get_scalar(\$string,'__END_HASH_REF__');
3441: }
3442: $string =~ s/^&//;
3443:
3444: $hash{$key}=$value;
3445: }
3446:
3447: $string =~ s/^__END_HASH_REF__//;
3448:
3449: return (\%hash, $string);
3450: }
3451:
3452: sub str2array {
3453: my ($string)=@_;
3454: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3455: return @$array;
3456: }
3457:
3458: sub str2arrayref {
3459: my ($string) = @_;
3460: my @array;
3461:
3462: if($string !~ /^__ARRAY_REF__/) {
3463: if (! ($string eq '' || !defined($string))) {
3464: $array[0]='Array reference error';
3465: }
3466: return (\@array, $string);
3467: }
3468:
3469: $string =~ s/^__ARRAY_REF__//;
3470:
3471: while($string !~ /^__END_ARRAY_REF__/) {
3472: my $value='';
3473: if($string =~ /^__HASH_REF__/) {
3474: ($value, $string)=&str2hashref($string);
3475: if(defined($value->{'error'})) {
3476: $array[0] ='Array reference error';
3477: return (\@array, $string);
3478: }
3479: } elsif($string =~ /^__ARRAY_REF__/) {
3480: ($value, $string)=&str2arrayref($string);
3481: if($value->[0] eq 'Array reference error') {
3482: $array[0] ='Array reference error';
3483: return (\@array, $string);
3484: }
3485: } else {
3486: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3487: }
3488: $string =~ s/^&//;
3489:
3490: push(@array, $value);
3491: }
3492:
3493: $string =~ s/^__END_ARRAY_REF__//;
3494:
3495: return (\@array, $string);
3496: }
3497:
3498: # -------------------------------------------------------------------Temp Store
3499:
3500: sub tmpreset {
3501: my ($symb,$namespace,$domain,$stuname) = @_;
3502: if (!$symb) {
3503: $symb=&symbread();
3504: if (!$symb) { $symb= $env{'request.url'}; }
3505: }
3506: $symb=escape($symb);
3507:
3508: if (!$namespace) { $namespace=$env{'request.state'}; }
3509: $namespace=~s/\//\_/g;
3510: $namespace=~s/\W//g;
3511:
3512: if (!$domain) { $domain=$env{'user.domain'}; }
3513: if (!$stuname) { $stuname=$env{'user.name'}; }
3514: if ($domain eq 'public' && $stuname eq 'public') {
3515: $stuname=$ENV{'REMOTE_ADDR'};
3516: }
3517: my $path=$perlvar{'lonDaemons'}.'/tmp';
3518: my %hash;
3519: if (tie(%hash,'GDBM_File',
3520: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3521: &GDBM_WRCREAT(),0640)) {
3522: foreach my $key (keys(%hash)) {
3523: if ($key=~ /:$symb/) {
3524: delete($hash{$key});
3525: }
3526: }
3527: }
3528: }
3529:
3530: sub tmpstore {
3531: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3532:
3533: if (!$symb) {
3534: $symb=&symbread();
3535: if (!$symb) { $symb= $env{'request.url'}; }
3536: }
3537: $symb=escape($symb);
3538:
3539: if (!$namespace) {
3540: # I don't think we would ever want to store this for a course.
3541: # it seems this will only be used if we don't have a course.
3542: #$namespace=$env{'request.course.id'};
3543: #if (!$namespace) {
3544: $namespace=$env{'request.state'};
3545: #}
3546: }
3547: $namespace=~s/\//\_/g;
3548: $namespace=~s/\W//g;
3549: if (!$domain) { $domain=$env{'user.domain'}; }
3550: if (!$stuname) { $stuname=$env{'user.name'}; }
3551: if ($domain eq 'public' && $stuname eq 'public') {
3552: $stuname=$ENV{'REMOTE_ADDR'};
3553: }
3554: my $now=time;
3555: my %hash;
3556: my $path=$perlvar{'lonDaemons'}.'/tmp';
3557: if (tie(%hash,'GDBM_File',
3558: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3559: &GDBM_WRCREAT(),0640)) {
3560: $hash{"version:$symb"}++;
3561: my $version=$hash{"version:$symb"};
3562: my $allkeys='';
3563: foreach my $key (keys(%$storehash)) {
3564: $allkeys.=$key.':';
3565: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
3566: }
3567: $hash{"$version:$symb:timestamp"}=$now;
3568: $allkeys.='timestamp';
3569: $hash{"$version:keys:$symb"}=$allkeys;
3570: if (untie(%hash)) {
3571: return 'ok';
3572: } else {
3573: return "error:$!";
3574: }
3575: } else {
3576: return "error:$!";
3577: }
3578: }
3579:
3580: # -----------------------------------------------------------------Temp Restore
3581:
3582: sub tmprestore {
3583: my ($symb,$namespace,$domain,$stuname) = @_;
3584:
3585: if (!$symb) {
3586: $symb=&symbread();
3587: if (!$symb) { $symb= $env{'request.url'}; }
3588: }
3589: $symb=escape($symb);
3590:
3591: if (!$namespace) { $namespace=$env{'request.state'}; }
3592:
3593: if (!$domain) { $domain=$env{'user.domain'}; }
3594: if (!$stuname) { $stuname=$env{'user.name'}; }
3595: if ($domain eq 'public' && $stuname eq 'public') {
3596: $stuname=$ENV{'REMOTE_ADDR'};
3597: }
3598: my %returnhash;
3599: $namespace=~s/\//\_/g;
3600: $namespace=~s/\W//g;
3601: my %hash;
3602: my $path=$perlvar{'lonDaemons'}.'/tmp';
3603: if (tie(%hash,'GDBM_File',
3604: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3605: &GDBM_READER(),0640)) {
3606: my $version=$hash{"version:$symb"};
3607: $returnhash{'version'}=$version;
3608: my $scope;
3609: for ($scope=1;$scope<=$version;$scope++) {
3610: my $vkeys=$hash{"$scope:keys:$symb"};
3611: my @keys=split(/:/,$vkeys);
3612: my $key;
3613: $returnhash{"$scope:keys"}=$vkeys;
3614: foreach $key (@keys) {
3615: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3616: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3617: }
3618: }
3619: if (!(untie(%hash))) {
3620: return "error:$!";
3621: }
3622: } else {
3623: return "error:$!";
3624: }
3625: return %returnhash;
3626: }
3627:
3628: # ----------------------------------------------------------------------- Store
3629:
3630: sub store {
3631: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3632: my $home='';
3633:
3634: if ($stuname) { $home=&homeserver($stuname,$domain); }
3635:
3636: $symb=&symbclean($symb);
3637: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3638:
3639: if (!$domain) { $domain=$env{'user.domain'}; }
3640: if (!$stuname) { $stuname=$env{'user.name'}; }
3641:
3642: &devalidate($symb,$stuname,$domain);
3643:
3644: $symb=escape($symb);
3645: if (!$namespace) {
3646: unless ($namespace=$env{'request.course.id'}) {
3647: return '';
3648: }
3649: }
3650: if (!$home) { $home=$env{'user.home'}; }
3651:
3652: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3653: $$storehash{'host'}=$perlvar{'lonHostID'};
3654:
3655: my $namevalue='';
3656: foreach my $key (keys(%$storehash)) {
3657: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3658: }
3659: $namevalue=~s/\&$//;
3660: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
3661: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3662: }
3663:
3664: # -------------------------------------------------------------- Critical Store
3665:
3666: sub cstore {
3667: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3668: my $home='';
3669:
3670: if ($stuname) { $home=&homeserver($stuname,$domain); }
3671:
3672: $symb=&symbclean($symb);
3673: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3674:
3675: if (!$domain) { $domain=$env{'user.domain'}; }
3676: if (!$stuname) { $stuname=$env{'user.name'}; }
3677:
3678: &devalidate($symb,$stuname,$domain);
3679:
3680: $symb=escape($symb);
3681: if (!$namespace) {
3682: unless ($namespace=$env{'request.course.id'}) {
3683: return '';
3684: }
3685: }
3686: if (!$home) { $home=$env{'user.home'}; }
3687:
3688: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3689: $$storehash{'host'}=$perlvar{'lonHostID'};
3690:
3691: my $namevalue='';
3692: foreach my $key (keys(%$storehash)) {
3693: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3694: }
3695: $namevalue=~s/\&$//;
3696: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
3697: return critical
3698: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3699: }
3700:
3701: # --------------------------------------------------------------------- Restore
3702:
3703: sub restore {
3704: my ($symb,$namespace,$domain,$stuname) = @_;
3705: my $home='';
3706:
3707: if ($stuname) { $home=&homeserver($stuname,$domain); }
3708:
3709: if (!$symb) {
3710: unless ($symb=escape(&symbread())) { return ''; }
3711: } else {
3712: $symb=&escape(&symbclean($symb));
3713: }
3714: if (!$namespace) {
3715: unless ($namespace=$env{'request.course.id'}) {
3716: return '';
3717: }
3718: }
3719: if (!$domain) { $domain=$env{'user.domain'}; }
3720: if (!$stuname) { $stuname=$env{'user.name'}; }
3721: if (!$home) { $home=$env{'user.home'}; }
3722: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3723:
3724: my %returnhash=();
3725: foreach my $line (split(/\&/,$answer)) {
3726: my ($name,$value)=split(/\=/,$line);
3727: $returnhash{&unescape($name)}=&thaw_unescape($value);
3728: }
3729: my $version;
3730: for ($version=1;$version<=$returnhash{'version'};$version++) {
3731: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3732: $returnhash{$item}=$returnhash{$version.':'.$item};
3733: }
3734: }
3735: return %returnhash;
3736: }
3737:
3738: # ---------------------------------------------------------- Course Description
3739:
3740: sub coursedescription {
3741: my ($courseid,$args)=@_;
3742: $courseid=~s/^\///;
3743: $courseid=~s/\_/\//g;
3744: my ($cdomain,$cnum)=split(/\//,$courseid);
3745: my $chome=&homeserver($cnum,$cdomain);
3746: my $normalid=$cdomain.'_'.$cnum;
3747: # need to always cache even if we get errors otherwise we keep
3748: # trying and trying and trying to get the course description.
3749: my %envhash=();
3750: my %returnhash=();
3751:
3752: my $expiretime=600;
3753: if ($env{'request.course.id'} eq $normalid) {
3754: $expiretime=120;
3755: }
3756:
3757: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3758: if (!$args->{'freshen_cache'}
3759: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3760: foreach my $key (keys(%env)) {
3761: next if ($key !~ /^\Q$prefix\E(.*)/);
3762: my ($setting) = $1;
3763: $returnhash{$setting} = $env{$key};
3764: }
3765: return %returnhash;
3766: }
3767:
3768: # get the data agin
3769: if (!$args->{'one_time'}) {
3770: $envhash{'course.'.$normalid.'.last_cache'}=time;
3771: }
3772:
3773: if ($chome ne 'no_host') {
3774: %returnhash=&dump('environment',$cdomain,$cnum);
3775: if (!exists($returnhash{'con_lost'})) {
3776: $returnhash{'home'}= $chome;
3777: $returnhash{'domain'} = $cdomain;
3778: $returnhash{'num'} = $cnum;
3779: if (!defined($returnhash{'type'})) {
3780: $returnhash{'type'} = 'Course';
3781: }
3782: while (my ($name,$value) = each %returnhash) {
3783: $envhash{'course.'.$normalid.'.'.$name}=$value;
3784: }
3785: $returnhash{'url'}=&clutter($returnhash{'url'});
3786: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
3787: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
3788: $envhash{'course.'.$normalid.'.home'}=$chome;
3789: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3790: $envhash{'course.'.$normalid.'.num'}=$cnum;
3791: }
3792: }
3793: if (!$args->{'one_time'}) {
3794: &appenv(\%envhash);
3795: }
3796: return %returnhash;
3797: }
3798:
3799: # -------------------------------------------------See if a user is privileged
3800:
3801: sub privileged {
3802: my ($username,$domain)=@_;
3803: my $rolesdump=&reply("dump:$domain:$username:roles",
3804: &homeserver($username,$domain));
3805: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3806: ($rolesdump =~ /^error:/)) {
3807: return 0;
3808: }
3809: my $now=time;
3810: if ($rolesdump ne '') {
3811: foreach my $entry (split(/&/,$rolesdump)) {
3812: if ($entry!~/^rolesdef_/) {
3813: my ($area,$role)=split(/=/,$entry);
3814: $area=~s/\_\w\w$//;
3815: my ($trole,$tend,$tstart)=split(/_/,$role);
3816: if (($trole eq 'dc') || ($trole eq 'su')) {
3817: my $active=1;
3818: if ($tend) {
3819: if ($tend<$now) { $active=0; }
3820: }
3821: if ($tstart) {
3822: if ($tstart>$now) { $active=0; }
3823: }
3824: if ($active) { return 1; }
3825: }
3826: }
3827: }
3828: }
3829: return 0;
3830: }
3831:
3832: # -------------------------------------------------------- Get user privileges
3833:
3834: sub rolesinit {
3835: my ($domain,$username,$authhost)=@_;
3836: my %userroles;
3837: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
3838: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
3839: ($rolesdump =~ /^error:/)) {
3840: return \%userroles;
3841: }
3842: my %allroles=();
3843: my %allgroups=();
3844: my $now=time;
3845: %userroles = ('user.login.time' => $now);
3846: my $group_privs;
3847:
3848: if ($rolesdump ne '') {
3849: foreach my $entry (split(/&/,$rolesdump)) {
3850: if ($entry!~/^rolesdef_/) {
3851: my ($area,$role)=split(/=/,$entry);
3852: $area=~s/\_\w\w$//;
3853: my ($trole,$tend,$tstart,$group_privs);
3854: if ($role=~/^cr/) {
3855: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3856: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
3857: ($tend,$tstart)=split('_',$trest);
3858: } else {
3859: $trole=$role;
3860: }
3861: } elsif ($role =~ m|^gr/|) {
3862: ($trole,$tend,$tstart) = split(/_/,$role);
3863: ($trole,$group_privs) = split(/\//,$trole);
3864: $group_privs = &unescape($group_privs);
3865: } else {
3866: ($trole,$tend,$tstart)=split(/_/,$role);
3867: }
3868: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3869: $username);
3870: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
3871: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3872: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
3873: if (($area ne '') && ($trole ne '')) {
3874: my $spec=$trole.'.'.$area;
3875: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3876: if ($trole =~ /^cr\//) {
3877: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
3878: } elsif ($trole eq 'gr') {
3879: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
3880: } else {
3881: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
3882: }
3883: }
3884: }
3885: }
3886: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3887: $userroles{'user.adv'} = $adv;
3888: $userroles{'user.author'} = $author;
3889: $env{'user.adv'}=$adv;
3890: }
3891: return \%userroles;
3892: }
3893:
3894: sub set_arearole {
3895: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3896: # log the associated role with the area
3897: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
3898: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
3899: }
3900:
3901: sub custom_roleprivs {
3902: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3903: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3904: my $homsvr=homeserver($rauthor,$rdomain);
3905: if (&hostname($homsvr) ne '') {
3906: my ($rdummy,$roledef)=
3907: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3908: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3909: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3910: if (defined($syspriv)) {
3911: $$allroles{'cm./'}.=':'.$syspriv;
3912: $$allroles{$spec.'./'}.=':'.$syspriv;
3913: }
3914: if ($tdomain ne '') {
3915: if (defined($dompriv)) {
3916: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3917: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3918: }
3919: if (($trest ne '') && (defined($coursepriv))) {
3920: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3921: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3922: }
3923: }
3924: }
3925: }
3926: }
3927:
3928: sub group_roleprivs {
3929: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3930: my $access = 1;
3931: my $now = time;
3932: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3933: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3934: if ($access) {
3935: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3936: $$allgroups{$course}{$group} .=':'.$group_privs;
3937: }
3938: }
3939:
3940: sub standard_roleprivs {
3941: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3942: if (defined($pr{$trole.':s'})) {
3943: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3944: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3945: }
3946: if ($tdomain ne '') {
3947: if (defined($pr{$trole.':d'})) {
3948: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3949: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3950: }
3951: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3952: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3953: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3954: }
3955: }
3956: }
3957:
3958: sub set_userprivs {
3959: my ($userroles,$allroles,$allgroups) = @_;
3960: my $author=0;
3961: my $adv=0;
3962: my %grouproles = ();
3963: if (keys(%{$allgroups}) > 0) {
3964: foreach my $role (keys(%{$allroles})) {
3965: my ($trole,$area,$sec,$extendedarea);
3966: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
3967: $trole = $1;
3968: $area = $2;
3969: $sec = $3;
3970: $extendedarea = $area.$sec;
3971: if (exists($$allgroups{$area})) {
3972: foreach my $group (keys(%{$$allgroups{$area}})) {
3973: my $spec = $trole.'.'.$extendedarea;
3974: $grouproles{$spec.'.'.$area.'/'.$group} =
3975: $$allgroups{$area}{$group};
3976: }
3977: }
3978: }
3979: }
3980: }
3981: foreach my $group (keys(%grouproles)) {
3982: $$allroles{$group} = $grouproles{$group};
3983: }
3984: foreach my $role (keys(%{$allroles})) {
3985: my %thesepriv;
3986: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
3987: foreach my $item (split(/:/,$$allroles{$role})) {
3988: if ($item ne '') {
3989: my ($privilege,$restrictions)=split(/&/,$item);
3990: if ($restrictions eq '') {
3991: $thesepriv{$privilege}='F';
3992: } elsif ($thesepriv{$privilege} ne 'F') {
3993: $thesepriv{$privilege}.=$restrictions;
3994: }
3995: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3996: }
3997: }
3998: my $thesestr='';
3999: foreach my $priv (keys(%thesepriv)) {
4000: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4001: }
4002: $userroles->{'user.priv.'.$role} = $thesestr;
4003: }
4004: return ($author,$adv);
4005: }
4006:
4007: sub role_status {
4008: my ($rolekey,$then,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
4009: my @pwhere = ();
4010: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4011: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4012: unless (!defined($$role) || $$role eq '') {
4013: $$where=join('.',@pwhere);
4014: $$trolecode=$$role.'.'.$$where;
4015: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4016: $$tstatus='is';
4017: if ($$tstart && $$tstart>$then) {
4018: $$tstatus='future';
4019: if ($$tstart && $$tstart>$refresh) {
4020: if ($$tstart<$now) {
4021: if (($$where ne '') && ($$role ne '')) {
4022: my (%allroles,%allgroups,$group_privs);
4023: my %userroles = (
4024: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4025: );
4026: my $spec=$$role.'.'.$$where;
4027: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4028: if ($$role eq 'gr') {
4029: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4030: $env{'user.name'})=@_;
4031: my ($trole) = split('_',$role,1);
4032: (undef,my $group_privs) = split(/\//,$trole);
4033: $group_privs = &unescape($group_privs);
4034: }
4035: if ($$role =~ /^cr\//) {
4036: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
4037: } elsif ($$role eq 'gr') {
4038: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4039: $env{'user.name'});
4040: my $trole = split('_',$rolehash{$$where.'_'.$$role},1);
4041: (undef,my $group_privs) = split(/\//,$trole);
4042: $group_privs = &unescape($group_privs);
4043: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
4044: } else {
4045: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4046: }
4047: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups);
4048: &appenv(\%userroles,[$$role,'cm']);
4049: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4050: $$tstatus = 'is';
4051: }
4052: }
4053: }
4054: }
4055: if ($$tend) {
4056: if ($$tend<$then) {
4057: $$tstatus='expired';
4058: } elsif ($$tend<$now) {
4059: $$tstatus='will_not';
4060: }
4061: }
4062: }
4063: }
4064: }
4065:
4066: sub check_adhoc_privs {
4067: my ($cdom,$cnum,$then,$refresh,$now,$checkrole) = @_;
4068: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4069: if ($env{$cckey}) {
4070: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
4071: &role_status($cckey,$then,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
4072: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
4073: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4074: }
4075: } else {
4076: &set_adhoc_privileges($cdom,$cnum,$checkrole);
4077: }
4078: }
4079:
4080: sub set_adhoc_privileges {
4081: # role can be cc or ca
4082: my ($dcdom,$pickedcourse,$role) = @_;
4083: my $area = '/'.$dcdom.'/'.$pickedcourse;
4084: my $spec = $role.'.'.$area;
4085: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4086: $env{'user.name'});
4087: my %ccrole = ();
4088: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4089: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4090: &appenv(\%userroles,[$role,'cm']);
4091: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4092: &appenv( {'request.role' => $spec,
4093: 'request.role.domain' => $dcdom,
4094: 'request.course.sec' => ''
4095: }
4096: );
4097: my $tadv=0;
4098: if (&allowed('adv') eq 'F') { $tadv=1; }
4099: &appenv({'request.role.adv' => $tadv});
4100: }
4101:
4102: # --------------------------------------------------------------- get interface
4103:
4104: sub get {
4105: my ($namespace,$storearr,$udomain,$uname)=@_;
4106: my $items='';
4107: foreach my $item (@$storearr) {
4108: $items.=&escape($item).'&';
4109: }
4110: $items=~s/\&$//;
4111: if (!$udomain) { $udomain=$env{'user.domain'}; }
4112: if (!$uname) { $uname=$env{'user.name'}; }
4113: my $uhome=&homeserver($uname,$udomain);
4114:
4115: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
4116: my @pairs=split(/\&/,$rep);
4117: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4118: return @pairs;
4119: }
4120: my %returnhash=();
4121: my $i=0;
4122: foreach my $item (@$storearr) {
4123: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4124: $i++;
4125: }
4126: return %returnhash;
4127: }
4128:
4129: # --------------------------------------------------------------- del interface
4130:
4131: sub del {
4132: my ($namespace,$storearr,$udomain,$uname)=@_;
4133: my $items='';
4134: foreach my $item (@$storearr) {
4135: $items.=&escape($item).'&';
4136: }
4137:
4138: $items=~s/\&$//;
4139: if (!$udomain) { $udomain=$env{'user.domain'}; }
4140: if (!$uname) { $uname=$env{'user.name'}; }
4141: my $uhome=&homeserver($uname,$udomain);
4142: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
4143: }
4144:
4145: # -------------------------------------------------------------- dump interface
4146:
4147: sub dump {
4148: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4149: if (!$udomain) { $udomain=$env{'user.domain'}; }
4150: if (!$uname) { $uname=$env{'user.name'}; }
4151: my $uhome=&homeserver($uname,$udomain);
4152: if ($regexp) {
4153: $regexp=&escape($regexp);
4154: } else {
4155: $regexp='.';
4156: }
4157: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4158: my @pairs=split(/\&/,$rep);
4159: my %returnhash=();
4160: foreach my $item (@pairs) {
4161: my ($key,$value)=split(/=/,$item,2);
4162: $key = &unescape($key);
4163: next if ($key =~ /^error: 2 /);
4164: $returnhash{$key}=&thaw_unescape($value);
4165: }
4166: return %returnhash;
4167: }
4168:
4169: # --------------------------------------------------------- dumpstore interface
4170:
4171: sub dumpstore {
4172: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
4173: if (!$udomain) { $udomain=$env{'user.domain'}; }
4174: if (!$uname) { $uname=$env{'user.name'}; }
4175: my $uhome=&homeserver($uname,$udomain);
4176: if ($regexp) {
4177: $regexp=&escape($regexp);
4178: } else {
4179: $regexp='.';
4180: }
4181: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4182: my @pairs=split(/\&/,$rep);
4183: my %returnhash=();
4184: foreach my $item (@pairs) {
4185: my ($key,$value)=split(/=/,$item,2);
4186: next if ($key =~ /^error: 2 /);
4187: $returnhash{$key}=&thaw_unescape($value);
4188: }
4189: return %returnhash;
4190: }
4191:
4192: # -------------------------------------------------------------- keys interface
4193:
4194: sub getkeys {
4195: my ($namespace,$udomain,$uname)=@_;
4196: if (!$udomain) { $udomain=$env{'user.domain'}; }
4197: if (!$uname) { $uname=$env{'user.name'}; }
4198: my $uhome=&homeserver($uname,$udomain);
4199: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4200: my @keyarray=();
4201: foreach my $key (split(/\&/,$rep)) {
4202: next if ($key =~ /^error: 2 /);
4203: push(@keyarray,&unescape($key));
4204: }
4205: return @keyarray;
4206: }
4207:
4208: # --------------------------------------------------------------- currentdump
4209: sub currentdump {
4210: my ($courseid,$sdom,$sname)=@_;
4211: $courseid = $env{'request.course.id'} if (! defined($courseid));
4212: $sdom = $env{'user.domain'} if (! defined($sdom));
4213: $sname = $env{'user.name'} if (! defined($sname));
4214: my $uhome = &homeserver($sname,$sdom);
4215: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
4216: return if ($rep =~ /^(error:|no_such_host)/);
4217: #
4218: my %returnhash=();
4219: #
4220: if ($rep eq "unknown_cmd") {
4221: # an old lond will not know currentdump
4222: # Do a dump and make it look like a currentdump
4223: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
4224: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4225: my %hash = @tmp;
4226: @tmp=();
4227: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
4228: } else {
4229: my @pairs=split(/\&/,$rep);
4230: foreach my $pair (@pairs) {
4231: my ($key,$value)=split(/=/,$pair,2);
4232: my ($symb,$param) = split(/:/,$key);
4233: $returnhash{&unescape($symb)}->{&unescape($param)} =
4234: &thaw_unescape($value);
4235: }
4236: }
4237: return %returnhash;
4238: }
4239:
4240: sub convert_dump_to_currentdump{
4241: my %hash = %{shift()};
4242: my %returnhash;
4243: # Code ripped from lond, essentially. The only difference
4244: # here is the unescaping done by lonnet::dump(). Conceivably
4245: # we might run in to problems with parameter names =~ /^v\./
4246: while (my ($key,$value) = each(%hash)) {
4247: my ($v,$symb,$param) = split(/:/,$key);
4248: $symb = &unescape($symb);
4249: $param = &unescape($param);
4250: next if ($v eq 'version' || $symb eq 'keys');
4251: next if (exists($returnhash{$symb}) &&
4252: exists($returnhash{$symb}->{$param}) &&
4253: $returnhash{$symb}->{'v.'.$param} > $v);
4254: $returnhash{$symb}->{$param}=$value;
4255: $returnhash{$symb}->{'v.'.$param}=$v;
4256: }
4257: #
4258: # Remove all of the keys in the hashes which keep track of
4259: # the version of the parameter.
4260: while (my ($symb,$param_hash) = each(%returnhash)) {
4261: # use a foreach because we are going to delete from the hash.
4262: foreach my $key (keys(%$param_hash)) {
4263: delete($param_hash->{$key}) if ($key =~ /^v\./);
4264: }
4265: }
4266: return \%returnhash;
4267: }
4268:
4269: # ------------------------------------------------------ critical inc interface
4270:
4271: sub cinc {
4272: return &inc(@_,'critical');
4273: }
4274:
4275: # --------------------------------------------------------------- inc interface
4276:
4277: sub inc {
4278: my ($namespace,$store,$udomain,$uname,$critical) = @_;
4279: if (!$udomain) { $udomain=$env{'user.domain'}; }
4280: if (!$uname) { $uname=$env{'user.name'}; }
4281: my $uhome=&homeserver($uname,$udomain);
4282: my $items='';
4283: if (! ref($store)) {
4284: # got a single value, so use that instead
4285: $items = &escape($store).'=&';
4286: } elsif (ref($store) eq 'SCALAR') {
4287: $items = &escape($$store).'=&';
4288: } elsif (ref($store) eq 'ARRAY') {
4289: $items = join('=&',map {&escape($_);} @{$store});
4290: } elsif (ref($store) eq 'HASH') {
4291: while (my($key,$value) = each(%{$store})) {
4292: $items.= &escape($key).'='.&escape($value).'&';
4293: }
4294: }
4295: $items=~s/\&$//;
4296: if ($critical) {
4297: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
4298: } else {
4299: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
4300: }
4301: }
4302:
4303: # --------------------------------------------------------------- put interface
4304:
4305: sub put {
4306: my ($namespace,$storehash,$udomain,$uname)=@_;
4307: if (!$udomain) { $udomain=$env{'user.domain'}; }
4308: if (!$uname) { $uname=$env{'user.name'}; }
4309: my $uhome=&homeserver($uname,$udomain);
4310: my $items='';
4311: foreach my $item (keys(%$storehash)) {
4312: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4313: }
4314: $items=~s/\&$//;
4315: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4316: }
4317:
4318: # ------------------------------------------------------------ newput interface
4319:
4320: sub newput {
4321: my ($namespace,$storehash,$udomain,$uname)=@_;
4322: if (!$udomain) { $udomain=$env{'user.domain'}; }
4323: if (!$uname) { $uname=$env{'user.name'}; }
4324: my $uhome=&homeserver($uname,$udomain);
4325: my $items='';
4326: foreach my $key (keys(%$storehash)) {
4327: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4328: }
4329: $items=~s/\&$//;
4330: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4331: }
4332:
4333: # --------------------------------------------------------- putstore interface
4334:
4335: sub putstore {
4336: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4337: if (!$udomain) { $udomain=$env{'user.domain'}; }
4338: if (!$uname) { $uname=$env{'user.name'}; }
4339: my $uhome=&homeserver($uname,$udomain);
4340: my $items='';
4341: foreach my $key (keys(%$storehash)) {
4342: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
4343: }
4344: $items=~s/\&$//;
4345: my $esc_symb=&escape($symb);
4346: my $esc_v=&escape($version);
4347: my $reply =
4348: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
4349: $uhome);
4350: if ($reply eq 'unknown_cmd') {
4351: # gfall back to way things use to be done
4352: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4353: $uname);
4354: }
4355: return $reply;
4356: }
4357:
4358: sub old_putstore {
4359: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4360: if (!$udomain) { $udomain=$env{'user.domain'}; }
4361: if (!$uname) { $uname=$env{'user.name'}; }
4362: my $uhome=&homeserver($uname,$udomain);
4363: my %newstorehash;
4364: foreach my $item (keys(%$storehash)) {
4365: my $key = $version.':'.&escape($symb).':'.$item;
4366: $newstorehash{$key} = $storehash->{$item};
4367: }
4368: my $items='';
4369: my %allitems = ();
4370: foreach my $item (keys(%newstorehash)) {
4371: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
4372: my $key = $1.':keys:'.$2;
4373: $allitems{$key} .= $3.':';
4374: }
4375: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
4376: }
4377: foreach my $item (keys(%allitems)) {
4378: $allitems{$item} =~ s/\:$//;
4379: $items.= $item.'='.$allitems{$item}.'&';
4380: }
4381: $items=~s/\&$//;
4382: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4383: }
4384:
4385: # ------------------------------------------------------ critical put interface
4386:
4387: sub cput {
4388: my ($namespace,$storehash,$udomain,$uname)=@_;
4389: if (!$udomain) { $udomain=$env{'user.domain'}; }
4390: if (!$uname) { $uname=$env{'user.name'}; }
4391: my $uhome=&homeserver($uname,$udomain);
4392: my $items='';
4393: foreach my $item (keys(%$storehash)) {
4394: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4395: }
4396: $items=~s/\&$//;
4397: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
4398: }
4399:
4400: # -------------------------------------------------------------- eget interface
4401:
4402: sub eget {
4403: my ($namespace,$storearr,$udomain,$uname)=@_;
4404: my $items='';
4405: foreach my $item (@$storearr) {
4406: $items.=&escape($item).'&';
4407: }
4408: $items=~s/\&$//;
4409: if (!$udomain) { $udomain=$env{'user.domain'}; }
4410: if (!$uname) { $uname=$env{'user.name'}; }
4411: my $uhome=&homeserver($uname,$udomain);
4412: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
4413: my @pairs=split(/\&/,$rep);
4414: my %returnhash=();
4415: my $i=0;
4416: foreach my $item (@$storearr) {
4417: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4418: $i++;
4419: }
4420: return %returnhash;
4421: }
4422:
4423: # ------------------------------------------------------------ tmpput interface
4424: sub tmpput {
4425: my ($storehash,$server,$context)=@_;
4426: my $items='';
4427: foreach my $item (keys(%$storehash)) {
4428: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4429: }
4430: $items=~s/\&$//;
4431: if (defined($context)) {
4432: $items .= ':'.&escape($context);
4433: }
4434: return &reply("tmpput:$items",$server);
4435: }
4436:
4437: # ------------------------------------------------------------ tmpget interface
4438: sub tmpget {
4439: my ($token,$server)=@_;
4440: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4441: my $rep=&reply("tmpget:$token",$server);
4442: my %returnhash;
4443: foreach my $item (split(/\&/,$rep)) {
4444: my ($key,$value)=split(/=/,$item);
4445: next if ($key =~ /^error: 2 /);
4446: $returnhash{&unescape($key)}=&thaw_unescape($value);
4447: }
4448: return %returnhash;
4449: }
4450:
4451: # ------------------------------------------------------------ tmpget interface
4452: sub tmpdel {
4453: my ($token,$server)=@_;
4454: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4455: return &reply("tmpdel:$token",$server);
4456: }
4457:
4458: # -------------------------------------------------- portfolio access checking
4459:
4460: sub portfolio_access {
4461: my ($requrl) = @_;
4462: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4463: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
4464: if ($result) {
4465: my %setters;
4466: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4467: my ($startblock,$endblock) =
4468: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4469: if ($startblock && $endblock) {
4470: return 'B';
4471: }
4472: } else {
4473: my ($startblock,$endblock) =
4474: &Apache::loncommon::blockcheck(\%setters,'port');
4475: if ($startblock && $endblock) {
4476: return 'B';
4477: }
4478: }
4479: }
4480: if ($result eq 'ok') {
4481: return 'F';
4482: } elsif ($result =~ /^[^:]+:guest_/) {
4483: return 'A';
4484: }
4485: return '';
4486: }
4487:
4488: sub get_portfolio_access {
4489: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4490:
4491: if (!ref($access_hash)) {
4492: my $current_perms = &get_portfile_permissions($udom,$unum);
4493: my %access_controls = &get_access_controls($current_perms,$group,
4494: $file_name);
4495: $access_hash = $access_controls{$file_name};
4496: }
4497:
4498: my ($public,$guest,@domains,@users,@courses,@groups);
4499: my $now = time;
4500: if (ref($access_hash) eq 'HASH') {
4501: foreach my $key (keys(%{$access_hash})) {
4502: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4503: if ($start > $now) {
4504: next;
4505: }
4506: if ($end && $end<$now) {
4507: next;
4508: }
4509: if ($scope eq 'public') {
4510: $public = $key;
4511: last;
4512: } elsif ($scope eq 'guest') {
4513: $guest = $key;
4514: } elsif ($scope eq 'domains') {
4515: push(@domains,$key);
4516: } elsif ($scope eq 'users') {
4517: push(@users,$key);
4518: } elsif ($scope eq 'course') {
4519: push(@courses,$key);
4520: } elsif ($scope eq 'group') {
4521: push(@groups,$key);
4522: }
4523: }
4524: if ($public) {
4525: return 'ok';
4526: }
4527: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4528: if ($guest) {
4529: return $guest;
4530: }
4531: } else {
4532: if (@domains > 0) {
4533: foreach my $domkey (@domains) {
4534: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4535: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4536: return 'ok';
4537: }
4538: }
4539: }
4540: }
4541: if (@users > 0) {
4542: foreach my $userkey (@users) {
4543: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4544: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4545: if (ref($item) eq 'HASH') {
4546: if (($item->{'uname'} eq $env{'user.name'}) &&
4547: ($item->{'udom'} eq $env{'user.domain'})) {
4548: return 'ok';
4549: }
4550: }
4551: }
4552: }
4553: }
4554: }
4555: my %roleshash;
4556: my @courses_and_groups = @courses;
4557: push(@courses_and_groups,@groups);
4558: if (@courses_and_groups > 0) {
4559: my (%allgroups,%allroles);
4560: my ($start,$end,$role,$sec,$group);
4561: foreach my $envkey (%env) {
4562: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
4563: my $cid = $2.'_'.$3;
4564: if ($1 eq 'gr') {
4565: $group = $4;
4566: $allgroups{$cid}{$group} = $env{$envkey};
4567: } else {
4568: if ($4 eq '') {
4569: $sec = 'none';
4570: } else {
4571: $sec = $4;
4572: }
4573: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4574: }
4575: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
4576: my $cid = $2.'_'.$3;
4577: if ($4 eq '') {
4578: $sec = 'none';
4579: } else {
4580: $sec = $4;
4581: }
4582: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4583: }
4584: }
4585: if (keys(%allroles) == 0) {
4586: return;
4587: }
4588: foreach my $key (@courses_and_groups) {
4589: my %content = %{$$access_hash{$key}};
4590: my $cnum = $content{'number'};
4591: my $cdom = $content{'domain'};
4592: my $cid = $cdom.'_'.$cnum;
4593: if (!exists($allroles{$cid})) {
4594: next;
4595: }
4596: foreach my $role_id (keys(%{$content{'roles'}})) {
4597: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4598: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4599: my @status = @{$content{'roles'}{$role_id}{'access'}};
4600: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4601: foreach my $role (keys(%{$allroles{$cid}})) {
4602: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4603: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4604: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4605: if (grep/^all$/,@sections) {
4606: return 'ok';
4607: } else {
4608: if (grep/^$sec$/,@sections) {
4609: return 'ok';
4610: }
4611: }
4612: }
4613: }
4614: if (keys(%{$allgroups{$cid}}) == 0) {
4615: if (grep/^none$/,@groups) {
4616: return 'ok';
4617: }
4618: } else {
4619: if (grep/^all$/,@groups) {
4620: return 'ok';
4621: }
4622: foreach my $group (keys(%{$allgroups{$cid}})) {
4623: if (grep/^$group$/,@groups) {
4624: return 'ok';
4625: }
4626: }
4627: }
4628: }
4629: }
4630: }
4631: }
4632: }
4633: if ($guest) {
4634: return $guest;
4635: }
4636: }
4637: }
4638: return;
4639: }
4640:
4641: sub course_group_datechecker {
4642: my ($dates,$now,$status) = @_;
4643: my ($start,$end) = split(/\./,$dates);
4644: if (!$start && !$end) {
4645: return 'ok';
4646: }
4647: if (grep/^active$/,@{$status}) {
4648: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4649: return 'ok';
4650: }
4651: }
4652: if (grep/^previous$/,@{$status}) {
4653: if ($end > $now ) {
4654: return 'ok';
4655: }
4656: }
4657: if (grep/^future$/,@{$status}) {
4658: if ($start > $now) {
4659: return 'ok';
4660: }
4661: }
4662: return;
4663: }
4664:
4665: sub parse_portfolio_url {
4666: my ($url) = @_;
4667:
4668: my ($type,$udom,$unum,$group,$file_name);
4669:
4670: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
4671: $type = 1;
4672: $udom = $1;
4673: $unum = $2;
4674: $file_name = $3;
4675: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
4676: $type = 2;
4677: $udom = $1;
4678: $unum = $2;
4679: $group = $3;
4680: $file_name = $3.'/'.$4;
4681: }
4682: if (wantarray) {
4683: return ($type,$udom,$unum,$file_name,$group);
4684: }
4685: return $type;
4686: }
4687:
4688: sub is_portfolio_url {
4689: my ($url) = @_;
4690: return scalar(&parse_portfolio_url($url));
4691: }
4692:
4693: sub is_portfolio_file {
4694: my ($file) = @_;
4695: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
4696: return 1;
4697: }
4698: return;
4699: }
4700:
4701: sub usertools_access {
4702: my ($uname,$udom,$tool,$action,$context) = @_;
4703: my ($access,%tools);
4704: if ($context eq '') {
4705: $context = 'tools';
4706: }
4707: if ($context eq 'requestcourses') {
4708: %tools = (
4709: official => 1,
4710: unofficial => 1,
4711: community => 1,
4712: );
4713: } else {
4714: %tools = (
4715: aboutme => 1,
4716: blog => 1,
4717: portfolio => 1,
4718: );
4719: }
4720: return if (!defined($tools{$tool}));
4721:
4722: if ((!defined($udom)) || (!defined($uname))) {
4723: $udom = $env{'user.domain'};
4724: $uname = $env{'user.name'};
4725: }
4726:
4727: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4728: if ($action ne 'reload') {
4729: if ($context eq 'requestcourses') {
4730: return $env{'environment.canrequest.'.$tool};
4731: } else {
4732: return $env{'environment.availabletools.'.$tool};
4733: }
4734: }
4735: }
4736:
4737: my ($toolstatus,$inststatus);
4738:
4739: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
4740: ($action ne 'reload')) {
4741: $toolstatus = $env{'environment.'.$context.'.'.$tool};
4742: $inststatus = $env{'environment.inststatus'};
4743: } else {
4744: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
4745: $toolstatus = $userenv{$context.'.'.$tool};
4746: $inststatus = $userenv{'inststatus'};
4747: }
4748:
4749: if ($toolstatus ne '') {
4750: if ($toolstatus) {
4751: $access = 1;
4752: } else {
4753: $access = 0;
4754: }
4755: return $access;
4756: }
4757:
4758: my $is_adv = &is_advanced_user($udom,$uname);
4759: my %domdef = &get_domain_defaults($udom);
4760: if (ref($domdef{$tool}) eq 'HASH') {
4761: if ($is_adv) {
4762: if ($domdef{$tool}{'_LC_adv'} ne '') {
4763: if ($domdef{$tool}{'_LC_adv'}) {
4764: $access = 1;
4765: } else {
4766: $access = 0;
4767: }
4768: return $access;
4769: }
4770: }
4771: if ($inststatus ne '') {
4772: my ($hasaccess,$hasnoaccess);
4773: foreach my $affiliation (split(/:/,$inststatus)) {
4774: if ($domdef{$tool}{$affiliation} ne '') {
4775: if ($domdef{$tool}{$affiliation}) {
4776: $hasaccess = 1;
4777: } else {
4778: $hasnoaccess = 1;
4779: }
4780: }
4781: }
4782: if ($hasaccess || $hasnoaccess) {
4783: if ($hasaccess) {
4784: $access = 1;
4785: } elsif ($hasnoaccess) {
4786: $access = 0;
4787: }
4788: return $access;
4789: }
4790: } else {
4791: if ($domdef{$tool}{'default'} ne '') {
4792: if ($domdef{$tool}{'default'}) {
4793: $access = 1;
4794: } elsif ($domdef{$tool}{'default'} == 0) {
4795: $access = 0;
4796: }
4797: return $access;
4798: }
4799: }
4800: } else {
4801: if ($context eq 'tools') {
4802: $access = 1;
4803: } else {
4804: $access = 0;
4805: }
4806: return $access;
4807: }
4808: }
4809:
4810: sub is_advanced_user {
4811: my ($udom,$uname) = @_;
4812: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4813: my %allroles;
4814: my $is_adv;
4815: foreach my $role (keys(%roleshash)) {
4816: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4817: my $area = '/'.$tdomain.'/'.$trest;
4818: if ($sec ne '') {
4819: $area .= '/'.$sec;
4820: }
4821: if (($area ne '') && ($trole ne '')) {
4822: my $spec=$trole.'.'.$area;
4823: if ($trole =~ /^cr\//) {
4824: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4825: } elsif ($trole ne 'gr') {
4826: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4827: }
4828: }
4829: }
4830: foreach my $role (keys(%allroles)) {
4831: last if ($is_adv);
4832: foreach my $item (split(/:/,$allroles{$role})) {
4833: if ($item ne '') {
4834: my ($privilege,$restrictions)=split(/&/,$item);
4835: if ($privilege eq 'adv') {
4836: $is_adv = 1;
4837: last;
4838: }
4839: }
4840: }
4841: }
4842: return $is_adv;
4843: }
4844:
4845: # ---------------------------------------------- Custom access rule evaluation
4846:
4847: sub customaccess {
4848: my ($priv,$uri)=@_;
4849: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
4850: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
4851: $udom = &LONCAPA::clean_domain($udom);
4852: $ucrs = &LONCAPA::clean_username($ucrs);
4853: my $access=0;
4854: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
4855: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4856: if ($type eq 'user') {
4857: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4858: my ($tdom,$tuname)=split(m{/},$scope);
4859: if ($tdom) {
4860: if ($tdom ne $env{'user.domain'}) { next; }
4861: }
4862: if ($tuname) {
4863: if ($tuname ne $env{'user.name'}) { next; }
4864: }
4865: $access=($effect eq 'allow');
4866: last;
4867: }
4868: } else {
4869: if ($role) {
4870: if ($role ne $urole) { next; }
4871: }
4872: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4873: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4874: if ($tdom) {
4875: if ($tdom ne $udom) { next; }
4876: }
4877: if ($tcrs) {
4878: if ($tcrs ne $ucrs) { next; }
4879: }
4880: if ($tsec) {
4881: if ($tsec ne $usec) { next; }
4882: }
4883: $access=($effect eq 'allow');
4884: last;
4885: }
4886: if ($realm eq '' && $role eq '') {
4887: $access=($effect eq 'allow');
4888: }
4889: }
4890: }
4891: return $access;
4892: }
4893:
4894: # ------------------------------------------------- Check for a user privilege
4895:
4896: sub allowed {
4897: my ($priv,$uri,$symb,$role)=@_;
4898: my $ver_orguri=$uri;
4899: $uri=&deversion($uri);
4900: my $orguri=$uri;
4901: $uri=&declutter($uri);
4902:
4903: if ($priv eq 'evb') {
4904: # Evade communication block restrictions for specified role in a course
4905: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4906: return $1;
4907: } else {
4908: return;
4909: }
4910: }
4911:
4912: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
4913: # Free bre access to adm and meta resources
4914: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
4915: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4916: && ($priv eq 'bre')) {
4917: return 'F';
4918: }
4919:
4920: # Free bre access to user's own portfolio contents
4921: my ($space,$domain,$name,@dir)=split('/',$uri);
4922: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
4923: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
4924: my %setters;
4925: my ($startblock,$endblock) =
4926: &Apache::loncommon::blockcheck(\%setters,'port');
4927: if ($startblock && $endblock) {
4928: return 'B';
4929: } else {
4930: return 'F';
4931: }
4932: }
4933:
4934: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
4935: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4936: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4937: if (exists($env{'request.course.id'})) {
4938: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4939: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4940: if (($domain eq $cdom) && ($name eq $cnum)) {
4941: my $courseprivid=$env{'request.course.id'};
4942: $courseprivid=~s/\_/\//;
4943: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4944: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4945: return $1;
4946: } else {
4947: if ($env{'request.course.sec'}) {
4948: $courseprivid.='/'.$env{'request.course.sec'};
4949: }
4950: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4951: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4952: return $2;
4953: }
4954: }
4955: }
4956: }
4957: }
4958:
4959: # Free bre to public access
4960:
4961: if ($priv eq 'bre') {
4962: my $copyright=&metadata($uri,'copyright');
4963: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
4964: return 'F';
4965: }
4966: if ($copyright eq 'priv') {
4967: $uri=~/([^\/]+)\/([^\/]+)\//;
4968: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
4969: return '';
4970: }
4971: }
4972: if ($copyright eq 'domain') {
4973: $uri=~/([^\/]+)\/([^\/]+)\//;
4974: unless (($env{'user.domain'} eq $1) ||
4975: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
4976: return '';
4977: }
4978: }
4979: if ($env{'request.role'}=~ /li\.\//) {
4980: # Library role, so allow browsing of resources in this domain.
4981: return 'F';
4982: }
4983: if ($copyright eq 'custom') {
4984: unless (&customaccess($priv,$uri)) { return ''; }
4985: }
4986: }
4987: # Domain coordinator is trying to create a course
4988: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
4989: # uri is the requested domain in this case.
4990: # comparison to 'request.role.domain' shows if the user has selected
4991: # a role of dc for the domain in question.
4992: return 'F' if ($uri eq $env{'request.role.domain'});
4993: }
4994:
4995: my $thisallowed='';
4996: my $statecond=0;
4997: my $courseprivid='';
4998:
4999: # Course
5000:
5001: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
5002: $thisallowed.=$1;
5003: }
5004:
5005: # Domain
5006:
5007: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
5008: =~/\Q$priv\E\&([^\:]*)/) {
5009: $thisallowed.=$1;
5010: }
5011:
5012: # Course: uri itself is a course
5013: my $courseuri=$uri;
5014: $courseuri=~s/\_(\d)/\/$1/;
5015: $courseuri=~s/^([^\/])/\/$1/;
5016:
5017: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
5018: =~/\Q$priv\E\&([^\:]*)/) {
5019: $thisallowed.=$1;
5020: }
5021:
5022: # URI is an uploaded document for this course, default permissions don't matter
5023: # not allowing 'edit' access (editupload) to uploaded course docs
5024: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
5025: $thisallowed='';
5026: my ($match)=&is_on_map($uri);
5027: if ($match) {
5028: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5029: =~/\Q$priv\E\&([^\:]*)/) {
5030: $thisallowed.=$1;
5031: }
5032: } else {
5033: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
5034: if ($refuri) {
5035: if ($refuri =~ m|^/adm/|) {
5036: $thisallowed='F';
5037: } else {
5038: $refuri=&declutter($refuri);
5039: my ($match) = &is_on_map($refuri);
5040: if ($match) {
5041: $thisallowed='F';
5042: }
5043: }
5044: }
5045: }
5046: }
5047:
5048: if ($priv eq 'bre'
5049: && $thisallowed ne 'F'
5050: && $thisallowed ne '2'
5051: && &is_portfolio_url($uri)) {
5052: $thisallowed = &portfolio_access($uri);
5053: }
5054:
5055: # Full access at system, domain or course-wide level? Exit.
5056: if ($thisallowed=~/F/) {
5057: return 'F';
5058: }
5059:
5060: # If this is generating or modifying users, exit with special codes
5061:
5062: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5063: if (($priv eq 'cca') || ($priv eq 'caa')) {
5064: my ($audom,$auname)=split('/',$uri);
5065: # no author name given, so this just checks on the general right to make a co-author in this domain
5066: unless ($auname) { return $thisallowed; }
5067: # an author name is given, so we are about to actually make a co-author for a certain account
5068: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5069: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5070: ($audom ne $env{'request.role.domain'}))) { return ''; }
5071: }
5072: return $thisallowed;
5073: }
5074: #
5075: # Gathered so far: system, domain and course wide privileges
5076: #
5077: # Course: See if uri or referer is an individual resource that is part of
5078: # the course
5079:
5080: if ($env{'request.course.id'}) {
5081:
5082: $courseprivid=$env{'request.course.id'};
5083: if ($env{'request.course.sec'}) {
5084: $courseprivid.='/'.$env{'request.course.sec'};
5085: }
5086: $courseprivid=~s/\_/\//;
5087: my $checkreferer=1;
5088: my ($match,$cond)=&is_on_map($uri);
5089: if ($match) {
5090: $statecond=$cond;
5091: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5092: =~/\Q$priv\E\&([^\:]*)/) {
5093: $thisallowed.=$1;
5094: $checkreferer=0;
5095: }
5096: }
5097:
5098: if ($checkreferer) {
5099: my $refuri=$env{'httpref.'.$orguri};
5100: unless ($refuri) {
5101: foreach my $key (keys(%env)) {
5102: if ($key=~/^httpref\..*\*/) {
5103: my $pattern=$key;
5104: $pattern=~s/^httpref\.\/res\///;
5105: $pattern=~s/\*/\[\^\/\]\+/g;
5106: $pattern=~s/\//\\\//g;
5107: if ($orguri=~/$pattern/) {
5108: $refuri=$env{$key};
5109: }
5110: }
5111: }
5112: }
5113:
5114: if ($refuri) {
5115: $refuri=&declutter($refuri);
5116: my ($match,$cond)=&is_on_map($refuri);
5117: if ($match) {
5118: my $refstatecond=$cond;
5119: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
5120: =~/\Q$priv\E\&([^\:]*)/) {
5121: $thisallowed.=$1;
5122: $uri=$refuri;
5123: $statecond=$refstatecond;
5124: }
5125: }
5126: }
5127: }
5128: }
5129:
5130: #
5131: # Gathered now: all privileges that could apply, and condition number
5132: #
5133: #
5134: # Full or no access?
5135: #
5136:
5137: if ($thisallowed=~/F/) {
5138: return 'F';
5139: }
5140:
5141: unless ($thisallowed) {
5142: return '';
5143: }
5144:
5145: # Restrictions exist, deal with them
5146: #
5147: # C:according to course preferences
5148: # R:according to resource settings
5149: # L:unless locked
5150: # X:according to user session state
5151: #
5152:
5153: # Possibly locked functionality, check all courses
5154: # Locks might take effect only after 10 minutes cache expiration for other
5155: # courses, and 2 minutes for current course
5156:
5157: my $envkey;
5158: if ($thisallowed=~/L/) {
5159: foreach $envkey (keys(%env)) {
5160: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
5161: my $courseid=$2;
5162: my $roleid=$1.'.'.$2;
5163: $courseid=~s/^\///;
5164: my $expiretime=600;
5165: if ($env{'request.role'} eq $roleid) {
5166: $expiretime=120;
5167: }
5168: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
5169: my $prefix='course.'.$cdom.'_'.$cnum.'.';
5170: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
5171: &coursedescription($courseid,{'freshen_cache' => 1});
5172: }
5173: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
5174: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
5175: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
5176: &log($env{'user.domain'},$env{'user.name'},
5177: $env{'user.home'},
5178: 'Locked by res: '.$priv.' for '.$uri.' due to '.
5179: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5180: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5181: return '';
5182: }
5183: }
5184: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
5185: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
5186: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
5187: &log($env{'user.domain'},$env{'user.name'},
5188: $env{'user.home'},
5189: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
5190: $cdom.'/'.$cnum.'/'.$csec.' expire '.
5191: $env{$prefix.'priv.'.$priv.'.lock.expire'});
5192: return '';
5193: }
5194: }
5195: }
5196: }
5197: }
5198:
5199: #
5200: # Rest of the restrictions depend on selected course
5201: #
5202:
5203: unless ($env{'request.course.id'}) {
5204: if ($thisallowed eq 'A') {
5205: return 'A';
5206: } elsif ($thisallowed eq 'B') {
5207: return 'B';
5208: } else {
5209: return '1';
5210: }
5211: }
5212:
5213: #
5214: # Now user is definitely in a course
5215: #
5216:
5217:
5218: # Course preferences
5219:
5220: if ($thisallowed=~/C/) {
5221: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5222: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
5223: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
5224: =~/\Q$rolecode\E/) {
5225: if ($priv ne 'pch') {
5226: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5227: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
5228: $env{'request.course.id'});
5229: }
5230: return '';
5231: }
5232:
5233: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
5234: =~/\Q$unamedom\E/) {
5235: if ($priv ne 'pch') {
5236: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
5237: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
5238: $env{'request.course.id'});
5239: }
5240: return '';
5241: }
5242: }
5243:
5244: # Resource preferences
5245:
5246: if ($thisallowed=~/R/) {
5247: my $rolecode=(split(/\./,$env{'request.role'}))[0];
5248: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
5249: if ($priv ne 'pch') {
5250: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
5251: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
5252: }
5253: return '';
5254: }
5255: }
5256:
5257: # Restricted by state or randomout?
5258:
5259: if ($thisallowed=~/X/) {
5260: if ($env{'acc.randomout'}) {
5261: if (!$symb) { $symb=&symbread($uri,1); }
5262: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
5263: return '';
5264: }
5265: }
5266: if (&condval($statecond)) {
5267: return '2';
5268: } else {
5269: return '';
5270: }
5271: }
5272:
5273: if ($thisallowed eq 'A') {
5274: return 'A';
5275: } elsif ($thisallowed eq 'B') {
5276: return 'B';
5277: }
5278: return 'F';
5279: }
5280:
5281: sub split_uri_for_cond {
5282: my $uri=&deversion(&declutter(shift));
5283: my @uriparts=split(/\//,$uri);
5284: my $filename=pop(@uriparts);
5285: my $pathname=join('/',@uriparts);
5286: return ($pathname,$filename);
5287: }
5288: # --------------------------------------------------- Is a resource on the map?
5289:
5290: sub is_on_map {
5291: my ($pathname,$filename) = &split_uri_for_cond(shift);
5292: #Trying to find the conditional for the file
5293: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
5294: /\&\Q$filename\E\:([\d\|]+)\&/);
5295: if ($match) {
5296: return (1,$1);
5297: } else {
5298: return (0,0);
5299: }
5300: }
5301:
5302: # --------------------------------------------------------- Get symb from alias
5303:
5304: sub get_symb_from_alias {
5305: my $symb=shift;
5306: my ($map,$resid,$url)=&decode_symb($symb);
5307: # Already is a symb
5308: if ($url) { return $symb; }
5309: # Must be an alias
5310: my $aliassymb='';
5311: my %bighash;
5312: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
5313: &GDBM_READER(),0640)) {
5314: my $rid=$bighash{'mapalias_'.$symb};
5315: if ($rid) {
5316: my ($mapid,$resid)=split(/\./,$rid);
5317: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
5318: $resid,$bighash{'src_'.$rid});
5319: }
5320: untie %bighash;
5321: }
5322: return $aliassymb;
5323: }
5324:
5325: # ----------------------------------------------------------------- Define Role
5326:
5327: sub definerole {
5328: if (allowed('mcr','/')) {
5329: my ($rolename,$sysrole,$domrole,$courole)=@_;
5330: foreach my $role (split(':',$sysrole)) {
5331: my ($crole,$cqual)=split(/\&/,$role);
5332: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
5333: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
5334: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5335: return "refused:s:$crole&$cqual";
5336: }
5337: }
5338: }
5339: foreach my $role (split(':',$domrole)) {
5340: my ($crole,$cqual)=split(/\&/,$role);
5341: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
5342: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
5343: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
5344: return "refused:d:$crole&$cqual";
5345: }
5346: }
5347: }
5348: foreach my $role (split(':',$courole)) {
5349: my ($crole,$cqual)=split(/\&/,$role);
5350: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5351: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5352: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5353: return "refused:c:$crole&$cqual";
5354: }
5355: }
5356: }
5357: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5358: "$env{'user.domain'}:$env{'user.name'}:".
5359: "rolesdef_$rolename=".
5360: escape($sysrole.'_'.$domrole.'_'.$courole);
5361: return reply($command,$env{'user.home'});
5362: } else {
5363: return 'refused';
5364: }
5365: }
5366:
5367: # ---------------- Make a metadata query against the network of library servers
5368:
5369: sub metadata_query {
5370: my ($query,$custom,$customshow,$server_array)=@_;
5371: my %rhash;
5372: my %libserv = &all_library();
5373: my @server_list = (defined($server_array) ? @$server_array
5374: : keys(%libserv) );
5375: for my $server (@server_list) {
5376: unless ($custom or $customshow) {
5377: my $reply=&reply("querysend:".&escape($query),$server);
5378: $rhash{$server}=$reply;
5379: }
5380: else {
5381: my $reply=&reply("querysend:".&escape($query).':'.
5382: &escape($custom).':'.&escape($customshow),
5383: $server);
5384: $rhash{$server}=$reply;
5385: }
5386: }
5387: return \%rhash;
5388: }
5389:
5390: # ----------------------------------------- Send log queries and wait for reply
5391:
5392: sub log_query {
5393: my ($uname,$udom,$query,%filters)=@_;
5394: my $uhome=&homeserver($uname,$udom);
5395: if ($uhome eq 'no_host') { return 'error: no_host'; }
5396: my $uhost=&hostname($uhome);
5397: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
5398: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5399: $uhome);
5400: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
5401: return get_query_reply($queryid);
5402: }
5403:
5404: # -------------------------- Update MySQL table for portfolio file
5405:
5406: sub update_portfolio_table {
5407: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
5408: if ($group ne '') {
5409: $file_name =~s /^\Q$group\E//;
5410: }
5411: my $homeserver = &homeserver($uname,$udom);
5412: my $queryid=
5413: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5414: ':'.&escape($file_name).':'.$action,$homeserver);
5415: my $reply = &get_query_reply($queryid);
5416: return $reply;
5417: }
5418:
5419: # -------------------------- Update MySQL allusers table
5420:
5421: sub update_allusers_table {
5422: my ($uname,$udom,$names) = @_;
5423: my $homeserver = &homeserver($uname,$udom);
5424: my $queryid=
5425: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5426: 'lastname='.&escape($names->{'lastname'}).'%%'.
5427: 'firstname='.&escape($names->{'firstname'}).'%%'.
5428: 'middlename='.&escape($names->{'middlename'}).'%%'.
5429: 'generation='.&escape($names->{'generation'}).'%%'.
5430: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5431: 'id='.&escape($names->{'id'}),$homeserver);
5432: my $reply = &get_query_reply($queryid);
5433: return $reply;
5434: }
5435:
5436: # ------- Request retrieval of institutional classlists for course(s)
5437:
5438: sub fetch_enrollment_query {
5439: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
5440: my $homeserver;
5441: my $maxtries = 1;
5442: if ($context eq 'automated') {
5443: $homeserver = $perlvar{'lonHostID'};
5444: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
5445: } else {
5446: $homeserver = &homeserver($cnum,$dom);
5447: }
5448: my $host=&hostname($homeserver);
5449: my $cmd = '';
5450: foreach my $affiliate (keys(%{$affiliatesref})) {
5451: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5452: }
5453: $cmd =~ s/%%$//;
5454: $cmd = &escape($cmd);
5455: my $query = 'fetchenrollment';
5456: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
5457: unless ($queryid=~/^\Q$host\E\_/) {
5458: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5459: return 'error: '.$queryid;
5460: }
5461: my $reply = &get_query_reply($queryid);
5462: my $tries = 1;
5463: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5464: $reply = &get_query_reply($queryid);
5465: $tries ++;
5466: }
5467: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5468: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5469: } else {
5470: my @responses = split(/:/,$reply);
5471: if ($homeserver eq $perlvar{'lonHostID'}) {
5472: foreach my $line (@responses) {
5473: my ($key,$value) = split(/=/,$line,2);
5474: $$replyref{$key} = $value;
5475: }
5476: } else {
5477: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
5478: foreach my $line (@responses) {
5479: my ($key,$value) = split(/=/,$line);
5480: $$replyref{$key} = $value;
5481: if ($value > 0) {
5482: foreach my $item (@{$$affiliatesref{$key}}) {
5483: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
5484: my $destname = $pathname.'/'.$filename;
5485: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
5486: if ($xml_classlist =~ /^error/) {
5487: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5488: } else {
5489: if ( open(FILE,">$destname") ) {
5490: print FILE &unescape($xml_classlist);
5491: close(FILE);
5492: } else {
5493: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
5494: }
5495: }
5496: }
5497: }
5498: }
5499: }
5500: return 'ok';
5501: }
5502: return 'error';
5503: }
5504:
5505: sub get_query_reply {
5506: my $queryid=shift;
5507: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5508: my $reply='';
5509: for (1..100) {
5510: sleep 2;
5511: if (-e $replyfile.'.end') {
5512: if (open(my $fh,$replyfile)) {
5513: $reply = join('',<$fh>);
5514: close($fh);
5515: } else { return 'error: reply_file_error'; }
5516: return &unescape($reply);
5517: }
5518: }
5519: return 'timeout:'.$queryid;
5520: }
5521:
5522: sub courselog_query {
5523: #
5524: # possible filters:
5525: # url: url or symb
5526: # username
5527: # domain
5528: # action: view, submit, grade
5529: # start: timestamp
5530: # end: timestamp
5531: #
5532: my (%filters)=@_;
5533: unless ($env{'request.course.id'}) { return 'no_course'; }
5534: if ($filters{'url'}) {
5535: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5536: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5537: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5538: }
5539: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5540: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5541: return &log_query($cname,$cdom,'courselog',%filters);
5542: }
5543:
5544: sub userlog_query {
5545: #
5546: # possible filters:
5547: # action: log check role
5548: # start: timestamp
5549: # end: timestamp
5550: #
5551: my ($uname,$udom,%filters)=@_;
5552: return &log_query($uname,$udom,'userlog',%filters);
5553: }
5554:
5555: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5556:
5557: sub auto_run {
5558: my ($cnum,$cdom) = @_;
5559: my $response = 0;
5560: my $settings;
5561: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5562: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5563: $settings = $domconfig{'autoenroll'};
5564: if ($settings->{'run'} eq '1') {
5565: $response = 1;
5566: }
5567: } else {
5568: my $homeserver;
5569: if (&is_course($cdom,$cnum)) {
5570: $homeserver = &homeserver($cnum,$cdom);
5571: } else {
5572: $homeserver = &domain($cdom,'primary');
5573: }
5574: if ($homeserver ne 'no_host') {
5575: $response = &reply('autorun:'.$cdom,$homeserver);
5576: }
5577: }
5578: return $response;
5579: }
5580:
5581: sub auto_get_sections {
5582: my ($cnum,$cdom,$inst_coursecode) = @_;
5583: my $homeserver;
5584: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5585: $homeserver = &homeserver($cnum,$cdom);
5586: }
5587: if (!defined($homeserver)) {
5588: if ($cdom =~ /^$match_domain$/) {
5589: $homeserver = &domain($cdom,'primary');
5590: }
5591: }
5592: my @secs;
5593: if (defined($homeserver)) {
5594: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5595: unless ($response eq 'refused') {
5596: @secs = split(/:/,$response);
5597: }
5598: }
5599: return @secs;
5600: }
5601:
5602: sub auto_new_course {
5603: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5604: my $homeserver = &homeserver($cnum,$cdom);
5605: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
5606: return $response;
5607: }
5608:
5609: sub auto_validate_courseID {
5610: my ($cnum,$cdom,$inst_course_id) = @_;
5611: my $homeserver = &homeserver($cnum,$cdom);
5612: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
5613: return $response;
5614: }
5615:
5616: sub auto_validate_instcode {
5617: my ($cnum,$cdom,$instcode,$owner) = @_;
5618: my ($homeserver,$response);
5619: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5620: $homeserver = &homeserver($cnum,$cdom);
5621: }
5622: if (!defined($homeserver)) {
5623: if ($cdom =~ /^$match_domain$/) {
5624: $homeserver = &domain($cdom,'primary');
5625: }
5626: }
5627: my $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
5628: &escape($instcode).':'.&escape($owner),$homeserver));
5629: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
5630: return ($outcome,$description);
5631: }
5632:
5633: sub auto_create_password {
5634: my ($cnum,$cdom,$authparam,$udom) = @_;
5635: my ($homeserver,$response);
5636: my $create_passwd = 0;
5637: my $authchk = '';
5638: if ($udom =~ /^$match_domain$/) {
5639: $homeserver = &domain($udom,'primary');
5640: }
5641: if ($homeserver eq '') {
5642: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5643: $homeserver = &homeserver($cnum,$cdom);
5644: }
5645: }
5646: if ($homeserver eq '') {
5647: $authchk = 'nodomain';
5648: } else {
5649: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5650: if ($response eq 'refused') {
5651: $authchk = 'refused';
5652: } else {
5653: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
5654: }
5655: }
5656: return ($authparam,$create_passwd,$authchk);
5657: }
5658:
5659: sub auto_photo_permission {
5660: my ($cnum,$cdom,$students) = @_;
5661: my $homeserver = &homeserver($cnum,$cdom);
5662: my ($outcome,$perm_reqd,$conditions) =
5663: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
5664: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5665: return (undef,undef);
5666: }
5667: return ($outcome,$perm_reqd,$conditions);
5668: }
5669:
5670: sub auto_checkphotos {
5671: my ($uname,$udom,$pid) = @_;
5672: my $homeserver = &homeserver($uname,$udom);
5673: my ($result,$resulttype);
5674: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
5675: &escape($uname).':'.&escape($pid),
5676: $homeserver));
5677: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5678: return (undef,undef);
5679: }
5680: if ($outcome) {
5681: ($result,$resulttype) = split(/:/,$outcome);
5682: }
5683: return ($result,$resulttype);
5684: }
5685:
5686: sub auto_photochoice {
5687: my ($cnum,$cdom) = @_;
5688: my $homeserver = &homeserver($cnum,$cdom);
5689: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
5690: &escape($cdom),
5691: $homeserver)));
5692: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5693: return (undef,undef);
5694: }
5695: return ($update,$comment);
5696: }
5697:
5698: sub auto_photoupdate {
5699: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5700: my $homeserver = &homeserver($cnum,$dom);
5701: my $host=&hostname($homeserver);
5702: my $cmd = '';
5703: my $maxtries = 1;
5704: foreach my $affiliate (keys(%{$affiliatesref})) {
5705: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5706: }
5707: $cmd =~ s/%%$//;
5708: $cmd = &escape($cmd);
5709: my $query = 'institutionalphotos';
5710: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5711: unless ($queryid=~/^\Q$host\E\_/) {
5712: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5713: return 'error: '.$queryid;
5714: }
5715: my $reply = &get_query_reply($queryid);
5716: my $tries = 1;
5717: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5718: $reply = &get_query_reply($queryid);
5719: $tries ++;
5720: }
5721: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5722: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5723: } else {
5724: my @responses = split(/:/,$reply);
5725: my $outcome = shift(@responses);
5726: foreach my $item (@responses) {
5727: my ($key,$value) = split(/=/,$item);
5728: $$photo{$key} = $value;
5729: }
5730: return $outcome;
5731: }
5732: return 'error';
5733: }
5734:
5735: sub auto_instcode_format {
5736: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5737: $cat_order) = @_;
5738: my $courses = '';
5739: my @homeservers;
5740: if ($caller eq 'global') {
5741: my %servers = &get_servers($codedom,'library');
5742: foreach my $tryserver (keys(%servers)) {
5743: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5744: push(@homeservers,$tryserver);
5745: }
5746: }
5747: } elsif ($caller eq 'requests') {
5748: if ($codedom =~ /^$match_domain$/) {
5749: my $chome = &domain($codedom,'primary');
5750: unless ($chome eq 'no_host') {
5751: push(@homeservers,$chome);
5752: }
5753: }
5754: } else {
5755: push(@homeservers,&homeserver($caller,$codedom));
5756: }
5757: foreach my $code (keys(%{$instcodes})) {
5758: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
5759: }
5760: chop($courses);
5761: my $ok_response = 0;
5762: my $response;
5763: while (@homeservers > 0 && $ok_response == 0) {
5764: my $server = shift(@homeservers);
5765: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5766: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5767: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
5768: split(/:/,$response);
5769: %{$codes} = (%{$codes},&str2hash($codes_str));
5770: push(@{$codetitles},&str2array($codetitles_str));
5771: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5772: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5773: $ok_response = 1;
5774: }
5775: }
5776: if ($ok_response) {
5777: return 'ok';
5778: } else {
5779: return $response;
5780: }
5781: }
5782:
5783: sub auto_instcode_defaults {
5784: my ($domain,$returnhash,$code_order) = @_;
5785: my @homeservers;
5786:
5787: my %servers = &get_servers($domain,'library');
5788: foreach my $tryserver (keys(%servers)) {
5789: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5790: push(@homeservers,$tryserver);
5791: }
5792: }
5793:
5794: my $response;
5795: foreach my $server (@homeservers) {
5796: $response=&reply('autoinstcodedefaults:'.$domain,$server);
5797: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5798:
5799: foreach my $pair (split(/\&/,$response)) {
5800: my ($name,$value)=split(/\=/,$pair);
5801: if ($name eq 'code_order') {
5802: @{$code_order} = split(/\&/,&unescape($value));
5803: } else {
5804: $returnhash->{&unescape($name)}=&unescape($value);
5805: }
5806: }
5807: return 'ok';
5808: }
5809:
5810: return $response;
5811: }
5812:
5813: sub auto_possible_instcodes {
5814: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
5815: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
5816: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
5817: return;
5818: }
5819: my (@homeservers,$uhome);
5820: if (defined(&domain($domain,'primary'))) {
5821: $uhome=&domain($domain,'primary');
5822: push(@homeservers,&domain($domain,'primary'));
5823: } else {
5824: my %servers = &get_servers($domain,'library');
5825: foreach my $tryserver (keys(%servers)) {
5826: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5827: push(@homeservers,$tryserver);
5828: }
5829: }
5830: }
5831: my $response;
5832: foreach my $server (@homeservers) {
5833: $response=&reply('autopossibleinstcodes:'.$domain,$server);
5834: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5835: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
5836: split(':',$response);
5837: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
5838: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
5839: foreach my $item (split('&',$cat_title)) {
5840: my ($name,$value)=split('=',$item);
5841: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
5842: }
5843: foreach my $item (split('&',$cat_order)) {
5844: my ($name,$value)=split('=',$item);
5845: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
5846: }
5847: return 'ok';
5848: }
5849: return $response;
5850: }
5851:
5852: sub auto_courserequest_checks {
5853: my ($dom) = @_;
5854: my ($homeserver,%validations);
5855: if ($dom =~ /^$match_domain$/) {
5856: $homeserver = &domain($dom,'primary');
5857: }
5858: unless ($homeserver eq 'no_host') {
5859: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
5860: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
5861: my @items = split(/&/,$response);
5862: foreach my $item (@items) {
5863: my ($key,$value) = split('=',$item);
5864: $validations{&unescape($key)} = &thaw_unescape($value);
5865: }
5866: }
5867: }
5868: return %validations;
5869: }
5870:
5871: sub auto_courserequest_validation {
5872: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
5873: my ($homeserver,$response);
5874: if ($dom =~ /^$match_domain$/) {
5875: $homeserver = &domain($dom,'primary');
5876: }
5877: unless ($homeserver eq 'no_host') {
5878:
5879: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
5880: ':'.&escape($crstype).':'.&escape($inststatuslist).
5881: ':'.&escape($instcode).':'.&escape($instseclist),
5882: $homeserver));
5883: }
5884: return $response;
5885: }
5886:
5887: sub auto_validate_class_sec {
5888: my ($cdom,$cnum,$owners,$inst_class) = @_;
5889: my $homeserver = &homeserver($cnum,$cdom);
5890: my $ownerlist;
5891: if (ref($owners) eq 'ARRAY') {
5892: $ownerlist = join(',',@{$owners});
5893: } else {
5894: $ownerlist = $owners;
5895: }
5896: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
5897: &escape($ownerlist).':'.$cdom,$homeserver);
5898: return $response;
5899: }
5900:
5901: # ------------------------------------------------------- Course Group routines
5902:
5903: sub get_coursegroups {
5904: my ($cdom,$cnum,$group,$namespace) = @_;
5905: return(&dump($namespace,$cdom,$cnum,$group));
5906: }
5907:
5908: sub modify_coursegroup {
5909: my ($cdom,$cnum,$groupsettings) = @_;
5910: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5911: }
5912:
5913: sub toggle_coursegroup_status {
5914: my ($cdom,$cnum,$group,$action) = @_;
5915: my ($from_namespace,$to_namespace);
5916: if ($action eq 'delete') {
5917: $from_namespace = 'coursegroups';
5918: $to_namespace = 'deleted_groups';
5919: } else {
5920: $from_namespace = 'deleted_groups';
5921: $to_namespace = 'coursegroups';
5922: }
5923: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
5924: if (my $tmp = &error(%curr_group)) {
5925: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5926: return ('read error',$tmp);
5927: } else {
5928: my %savedsettings = %curr_group;
5929: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
5930: my $deloutcome;
5931: if ($result eq 'ok') {
5932: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
5933: } else {
5934: return ('write error',$result);
5935: }
5936: if ($deloutcome eq 'ok') {
5937: return 'ok';
5938: } else {
5939: return ('delete error',$deloutcome);
5940: }
5941: }
5942: }
5943:
5944: sub modify_group_roles {
5945: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
5946: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5947: my $role = 'gr/'.&escape($userprivs);
5948: my ($uname,$udom) = split(/:/,$user);
5949: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
5950: if ($result eq 'ok') {
5951: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5952: }
5953: return $result;
5954: }
5955:
5956: sub modify_coursegroup_membership {
5957: my ($cdom,$cnum,$membership) = @_;
5958: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5959: return $result;
5960: }
5961:
5962: sub get_active_groups {
5963: my ($udom,$uname,$cdom,$cnum) = @_;
5964: my $now = time;
5965: my %groups = ();
5966: foreach my $key (keys(%env)) {
5967: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
5968: my ($start,$end) = split(/\./,$env{$key});
5969: if (($end!=0) && ($end<$now)) { next; }
5970: if (($start!=0) && ($start>$now)) { next; }
5971: if ($1 eq $cdom && $2 eq $cnum) {
5972: $groups{$3} = $env{$key} ;
5973: }
5974: }
5975: }
5976: return %groups;
5977: }
5978:
5979: sub get_group_membership {
5980: my ($cdom,$cnum,$group) = @_;
5981: return(&dump('groupmembership',$cdom,$cnum,$group));
5982: }
5983:
5984: sub get_users_groups {
5985: my ($udom,$uname,$courseid) = @_;
5986: my @usersgroups;
5987: my $cachetime=1800;
5988:
5989: my $hashid="$udom:$uname:$courseid";
5990: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5991: if (defined($cached)) {
5992: @usersgroups = split(/:/,$grouplist);
5993: } else {
5994: $grouplist = '';
5995: my $courseurl = &courseid_to_courseurl($courseid);
5996: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
5997: my $access_end = $env{'course.'.$courseid.
5998: '.default_enrollment_end_date'};
5999: my $now = time;
6000: foreach my $key (keys(%roleshash)) {
6001: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6002: my $group = $1;
6003: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6004: my $start = $2;
6005: my $end = $1;
6006: if ($start == -1) { next; } # deleted from group
6007: if (($start!=0) && ($start>$now)) { next; }
6008: if (($end!=0) && ($end<$now)) {
6009: if ($access_end && $access_end < $now) {
6010: if ($access_end - $end < 86400) {
6011: push(@usersgroups,$group);
6012: }
6013: }
6014: next;
6015: }
6016: push(@usersgroups,$group);
6017: }
6018: }
6019: }
6020: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6021: $grouplist = join(':',@usersgroups);
6022: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
6023: }
6024: return @usersgroups;
6025: }
6026:
6027: sub devalidate_getgroups_cache {
6028: my ($udom,$uname,$cdom,$cnum)=@_;
6029: my $courseid = $cdom.'_'.$cnum;
6030:
6031: my $hashid="$udom:$uname:$courseid";
6032: &devalidate_cache_new('getgroups',$hashid);
6033: }
6034:
6035: # ------------------------------------------------------------------ Plain Text
6036:
6037: sub plaintext {
6038: my ($short,$type,$cid,$forcedefault) = @_;
6039: if ($short =~ /^cr/) {
6040: return (split('/',$short))[-1];
6041: }
6042: if (!defined($cid)) {
6043: $cid = $env{'request.course.id'};
6044: }
6045: if (defined($cid) && ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '')) {
6046: unless ($forcedefault) {
6047: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6048: &Apache::lonlocal::mt_escape(\$roletext);
6049: return &Apache::lonlocal::mt($roletext);
6050: }
6051: }
6052: my %rolenames = (
6053: Course => 'std',
6054: Community => 'alt1',
6055: );
6056: if (defined($type) &&
6057: defined($rolenames{$type}) &&
6058: defined($prp{$short}{$rolenames{$type}})) {
6059: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
6060: } else {
6061: return &Apache::lonlocal::mt($prp{$short}{'std'});
6062: }
6063: }
6064:
6065: # ----------------------------------------------------------------- Assign Role
6066:
6067: sub assignrole {
6068: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6069: $context)=@_;
6070: my $mrole;
6071: if ($role =~ /^cr\//) {
6072: my $cwosec=$url;
6073: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6074: unless (&allowed('ccr',$cwosec)) {
6075: my $refused = 1;
6076: if ($context eq 'requestcourses') {
6077: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
6078: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
6079: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
6080: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6081: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6082: if ($crsenv{'internal.courseowner'} eq
6083: $env{'user.name'}.':'.$env{'user.domain'}) {
6084: $refused = '';
6085: }
6086: }
6087: }
6088: }
6089: }
6090: if ($refused) {
6091: &logthis('Refused custom assignrole: '.
6092: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
6093: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
6094: return 'refused';
6095: }
6096: }
6097: $mrole='cr';
6098: } elsif ($role =~ /^gr\//) {
6099: my $cwogrp=$url;
6100: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
6101: unless (&allowed('mdg',$cwogrp)) {
6102: &logthis('Refused group assignrole: '.
6103: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
6104: $env{'user.name'}.' at '.$env{'user.domain'});
6105: return 'refused';
6106: }
6107: $mrole='gr';
6108: } else {
6109: my $cwosec=$url;
6110: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
6111: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
6112: my $refused;
6113: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
6114: if (!(&allowed('c'.$role,$url))) {
6115: $refused = 1;
6116: }
6117: } else {
6118: $refused = 1;
6119: }
6120: if ($refused) {
6121: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
6122: $refused = '';
6123: } elsif ($context eq 'requestcourses') {
6124: my @possroles = ('st','ta','ep','in','cc');
6125: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
6126: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
6127: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
6128: if ($crsenv{'internal.courseowner'} eq
6129: $env{'user.name'}.':'.$env{'user.domain'}) {
6130: $refused = '';
6131: }
6132: }
6133: }
6134: if ($refused) {
6135: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
6136: ' '.$role.' '.$end.' '.$start.' by '.
6137: $env{'user.name'}.' at '.$env{'user.domain'});
6138: return 'refused';
6139: }
6140: }
6141: }
6142: $mrole=$role;
6143: }
6144: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6145: "$udom:$uname:$url".'_'."$mrole=$role";
6146: if ($end) { $command.='_'.$end; }
6147: if ($start) {
6148: if ($end) {
6149: $command.='_'.$start;
6150: } else {
6151: $command.='_0_'.$start;
6152: }
6153: }
6154: my $origstart = $start;
6155: my $origend = $end;
6156: my $delflag;
6157: # actually delete
6158: if ($deleteflag) {
6159: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
6160: # modify command to delete the role
6161: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
6162: "$udom:$uname:$url".'_'."$mrole";
6163: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
6164: # set start and finish to negative values for userrolelog
6165: $start=-1;
6166: $end=-1;
6167: $delflag = 1;
6168: }
6169: }
6170: # send command
6171: my $answer=&reply($command,&homeserver($uname,$udom));
6172: # log new user role if status is ok
6173: if ($answer eq 'ok') {
6174: &userrolelog($role,$uname,$udom,$url,$start,$end);
6175: # for course roles, perform group memberships changes triggered by role change.
6176: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
6177: unless ($role =~ /^gr/) {
6178: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
6179: $origstart,$selfenroll,$context);
6180: }
6181: }
6182: return $answer;
6183: }
6184:
6185: # -------------------------------------------------- Modify user authentication
6186: # Overrides without validation
6187:
6188: sub modifyuserauth {
6189: my ($udom,$uname,$umode,$upass)=@_;
6190: my $uhome=&homeserver($uname,$udom);
6191: unless (&allowed('mau',$udom)) { return 'refused'; }
6192: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
6193: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6194: ' in domain '.$env{'request.role.domain'});
6195: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
6196: &escape($upass),$uhome);
6197: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
6198: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
6199: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6200: &log($udom,,$uname,$uhome,
6201: 'Authentication changed by '.$env{'user.domain'}.', '.
6202: $env{'user.name'}.', '.$umode.
6203: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
6204: unless ($reply eq 'ok') {
6205: &logthis('Authentication mode error: '.$reply);
6206: return 'error: '.$reply;
6207: }
6208: return 'ok';
6209: }
6210:
6211: # --------------------------------------------------------------- Modify a user
6212:
6213: sub modifyuser {
6214: my ($udom, $uname, $uid,
6215: $umode, $upass, $first,
6216: $middle, $last, $gene,
6217: $forceid, $desiredhome, $email, $inststatus)=@_;
6218: $udom= &LONCAPA::clean_domain($udom);
6219: $uname=&LONCAPA::clean_username($uname);
6220: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
6221: $umode.', '.$first.', '.$middle.', '.
6222: $last.', '.$gene.'(forceid: '.$forceid.')'.
6223: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
6224: ' desiredhome not specified').
6225: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
6226: ' in domain '.$env{'request.role.domain'});
6227: my $uhome=&homeserver($uname,$udom,'true');
6228: # ----------------------------------------------------------------- Create User
6229: if (($uhome eq 'no_host') &&
6230: (($umode && $upass) || ($umode eq 'localauth'))) {
6231: my $unhome='';
6232: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
6233: $unhome = $desiredhome;
6234: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
6235: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
6236: } else { # load balancing routine for determining $unhome
6237: my $loadm=10000000;
6238: my %servers = &get_servers($udom,'library');
6239: foreach my $tryserver (keys(%servers)) {
6240: my $answer=reply('load',$tryserver);
6241: if (($answer=~/\d+/) && ($answer<$loadm)) {
6242: $loadm=$answer;
6243: $unhome=$tryserver;
6244: }
6245: }
6246: }
6247: if (($unhome eq '') || ($unhome eq 'no_host')) {
6248: return 'error: unable to find a home server for '.$uname.
6249: ' in domain '.$udom;
6250: }
6251: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
6252: &escape($upass),$unhome);
6253: unless ($reply eq 'ok') {
6254: return 'error: '.$reply;
6255: }
6256: $uhome=&homeserver($uname,$udom,'true');
6257: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
6258: return 'error: unable verify users home machine.';
6259: }
6260: } # End of creation of new user
6261: # ---------------------------------------------------------------------- Add ID
6262: if ($uid) {
6263: $uid=~tr/A-Z/a-z/;
6264: my %uidhash=&idrget($udom,$uname);
6265: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
6266: && (!$forceid)) {
6267: unless ($uid eq $uidhash{$uname}) {
6268: return 'error: user id "'.$uid.'" does not match '.
6269: 'current user id "'.$uidhash{$uname}.'".';
6270: }
6271: } else {
6272: &idput($udom,($uname => $uid));
6273: }
6274: }
6275: # -------------------------------------------------------------- Add names, etc
6276: my @tmp=&get('environment',
6277: ['firstname','middlename','lastname','generation','id',
6278: 'permanentemail','inststatus'],
6279: $udom,$uname);
6280: my %names;
6281: if ($tmp[0] =~ m/^error:.*/) {
6282: %names=();
6283: } else {
6284: %names = @tmp;
6285: }
6286: #
6287: # Make sure to not trash student environment if instructor does not bother
6288: # to supply name and email information
6289: #
6290: if ($first) { $names{'firstname'} = $first; }
6291: if (defined($middle)) { $names{'middlename'} = $middle; }
6292: if ($last) { $names{'lastname'} = $last; }
6293: if (defined($gene)) { $names{'generation'} = $gene; }
6294: if ($email) {
6295: $email=~s/[^\w\@\.\-\,]//gs;
6296: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
6297: }
6298: if ($uid) { $names{'id'} = $uid; }
6299: if (defined($inststatus)) {
6300: $names{'inststatus'} = '';
6301: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
6302: if (ref($usertypes) eq 'HASH') {
6303: my @okstatuses;
6304: foreach my $item (split(/:/,$inststatus)) {
6305: if (defined($usertypes->{$item})) {
6306: push(@okstatuses,$item);
6307: }
6308: }
6309: if (@okstatuses) {
6310: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
6311: }
6312: }
6313: }
6314: my $reply = &put('environment', \%names, $udom,$uname);
6315: if ($reply ne 'ok') { return 'error: '.$reply; }
6316: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
6317: &devalidate_cache_new('namescache',$uname.':'.$udom);
6318: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
6319: $umode.', '.$first.', '.$middle.', '.
6320: $last.', '.$gene.', '.$email.', '.$inststatus;
6321: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
6322: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
6323: } else {
6324: $logmsg .= ' during self creation';
6325: }
6326: &logthis($logmsg);
6327: return 'ok';
6328: }
6329:
6330: # -------------------------------------------------------------- Modify student
6331:
6332: sub modifystudent {
6333: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
6334: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
6335: $selfenroll,$context,$inststatus)=@_;
6336: if (!$cid) {
6337: unless ($cid=$env{'request.course.id'}) {
6338: return 'not_in_class';
6339: }
6340: }
6341: # --------------------------------------------------------------- Make the user
6342: my $reply=&modifyuser
6343: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
6344: $desiredhome,$email,$inststatus);
6345: unless ($reply eq 'ok') { return $reply; }
6346: # This will cause &modify_student_enrollment to get the uid from the
6347: # students environment
6348: $uid = undef if (!$forceid);
6349: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
6350: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
6351: return $reply;
6352: }
6353:
6354: sub modify_student_enrollment {
6355: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
6356: my ($cdom,$cnum,$chome);
6357: if (!$cid) {
6358: unless ($cid=$env{'request.course.id'}) {
6359: return 'not_in_class';
6360: }
6361: $cdom=$env{'course.'.$cid.'.domain'};
6362: $cnum=$env{'course.'.$cid.'.num'};
6363: } else {
6364: ($cdom,$cnum)=split(/_/,$cid);
6365: }
6366: $chome=$env{'course.'.$cid.'.home'};
6367: if (!$chome) {
6368: $chome=&homeserver($cnum,$cdom);
6369: }
6370: if (!$chome) { return 'unknown_course'; }
6371: # Make sure the user exists
6372: my $uhome=&homeserver($uname,$udom);
6373: if (($uhome eq '') || ($uhome eq 'no_host')) {
6374: return 'error: no such user';
6375: }
6376: # Get student data if we were not given enough information
6377: if (!defined($first) || $first eq '' ||
6378: !defined($last) || $last eq '' ||
6379: !defined($uid) || $uid eq '' ||
6380: !defined($middle) || $middle eq '' ||
6381: !defined($gene) || $gene eq '') {
6382: # They did not supply us with enough data to enroll the student, so
6383: # we need to pick up more information.
6384: my %tmp = &get('environment',
6385: ['firstname','middlename','lastname', 'generation','id']
6386: ,$udom,$uname);
6387:
6388: #foreach my $key (keys(%tmp)) {
6389: # &logthis("key $key = ".$tmp{$key});
6390: #}
6391: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
6392: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
6393: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
6394: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
6395: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
6396: }
6397: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
6398: my $reply=cput('classlist',
6399: {"$uname:$udom" =>
6400: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
6401: $cdom,$cnum);
6402: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
6403: return 'error: '.$reply;
6404: } else {
6405: &devalidate_getsection_cache($udom,$uname,$cid);
6406: }
6407: # Add student role to user
6408: my $uurl='/'.$cid;
6409: $uurl=~s/\_/\//g;
6410: if ($usec) {
6411: $uurl.='/'.$usec;
6412: }
6413: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
6414: }
6415:
6416: sub format_name {
6417: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
6418: my $name;
6419: if ($first ne 'lastname') {
6420: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
6421: } else {
6422: if ($lastname=~/\S/) {
6423: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
6424: $name=~s/\s+,/,/;
6425: } else {
6426: $name.= $firstname.' '.$middlename.' '.$generation;
6427: }
6428: }
6429: $name=~s/^\s+//;
6430: $name=~s/\s+$//;
6431: $name=~s/\s+/ /g;
6432: return $name;
6433: }
6434:
6435: # ------------------------------------------------- Write to course preferences
6436:
6437: sub writecoursepref {
6438: my ($courseid,%prefs)=@_;
6439: $courseid=~s/^\///;
6440: $courseid=~s/\_/\//g;
6441: my ($cdomain,$cnum)=split(/\//,$courseid);
6442: my $chome=homeserver($cnum,$cdomain);
6443: if (($chome eq '') || ($chome eq 'no_host')) {
6444: return 'error: no such course';
6445: }
6446: my $cstring='';
6447: foreach my $pref (keys(%prefs)) {
6448: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
6449: }
6450: $cstring=~s/\&$//;
6451: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
6452: }
6453:
6454: # ---------------------------------------------------------- Make/modify course
6455:
6456: sub createcourse {
6457: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
6458: $course_owner,$crstype,$cnum,$context,$category)=@_;
6459: $url=&declutter($url);
6460: my $cid='';
6461: if ($context eq 'requestcourses') {
6462: my $can_create = 0;
6463: my ($ownername,$ownerdom) = split(':',$course_owner);
6464: if ($udom eq $ownerdom) {
6465: if (&usertools_access($ownername,$ownerdom,$category,undef,
6466: $context)) {
6467: $can_create = 1;
6468: }
6469: } else {
6470: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
6471: $category);
6472: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
6473: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
6474: if (@curr > 0) {
6475: my @options = qw(approval validate autolimit);
6476: my $optregex = join('|',@options);
6477: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
6478: $can_create = 1;
6479: }
6480: }
6481: }
6482: }
6483: if ($can_create) {
6484: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
6485: unless (&allowed('ccc',$udom)) {
6486: return 'refused';
6487: }
6488: }
6489: } else {
6490: return 'refused';
6491: }
6492: } elsif (!&allowed('ccc',$udom)) {
6493: return 'refused';
6494: }
6495: # --------------------------------------------------------------- Get Unique ID
6496: my $uname;
6497: if ($cnum =~ /^$match_courseid$/) {
6498: my $chome=&homeserver($cnum,$udom,'true');
6499: if (($chome eq '') || ($chome eq 'no_host')) {
6500: $uname = $cnum;
6501: } else {
6502: $uname = &generate_coursenum($udom);
6503: }
6504: } else {
6505: $uname = &generate_coursenum($udom);
6506: }
6507: return $uname if ($uname =~ /^error/);
6508: # -------------------------------------------------- Check supplied server name
6509: $course_server = $env{'user.homeserver'} if (! defined($course_server));
6510: if (! &is_library($course_server)) {
6511: return 'error:bad server name '.$course_server;
6512: }
6513: # ------------------------------------------------------------- Make the course
6514: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
6515: $course_server);
6516: unless ($reply eq 'ok') { return 'error: '.$reply; }
6517: my $uhome=&homeserver($uname,$udom,'true');
6518: if (($uhome eq '') || ($uhome eq 'no_host')) {
6519: return 'error: no such course';
6520: }
6521: # ----------------------------------------------------------------- Course made
6522: # log existence
6523: my $now = time;
6524: my $newcourse = {
6525: $udom.'_'.$uname => {
6526: description => $description,
6527: inst_code => $inst_code,
6528: owner => $course_owner,
6529: type => $crstype,
6530: creator => $env{'user.name'}.':'.
6531: $env{'user.domain'},
6532: created => $now,
6533: context => $context,
6534: },
6535: };
6536: &courseidput($udom,$newcourse,$uhome,'notime');
6537: # set toplevel url
6538: my $topurl=$url;
6539: unless ($nonstandard) {
6540: # ------------------------------------------ For standard courses, make top url
6541: my $mapurl=&clutter($url);
6542: if ($mapurl eq '/res/') { $mapurl=''; }
6543: $env{'form.initmap'}=(<<ENDINITMAP);
6544: <map>
6545: <resource id="1" type="start"></resource>
6546: <resource id="2" src="$mapurl"></resource>
6547: <resource id="3" type="finish"></resource>
6548: <link index="1" from="1" to="2"></link>
6549: <link index="2" from="2" to="3"></link>
6550: </map>
6551: ENDINITMAP
6552: $topurl=&declutter(
6553: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
6554: );
6555: }
6556: # ----------------------------------------------------------- Write preferences
6557: &writecoursepref($udom.'_'.$uname,
6558: ('description' => $description,
6559: 'url' => $topurl));
6560: return '/'.$udom.'/'.$uname;
6561: }
6562:
6563: # ------------------------------------------------------------------- Create ID
6564: sub generate_coursenum {
6565: my ($udom) = @_;
6566: my $domdesc = &domain($udom);
6567: return 'error: invalid domain' if ($domdesc eq '');
6568: my $uname=int(1+rand(9)).
6569: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6570: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6571: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6572: # ----------------------------------------------- Make sure that does not exist
6573: my $uhome=&homeserver($uname,$udom,'true');
6574: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6575: $uname=int(1+rand(9)).
6576: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
6577: substr($$.time,0,5).unpack("H8",pack("I32",time)).
6578: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
6579: $uhome=&homeserver($uname,$udom,'true');
6580: unless (($uhome eq '') || ($uhome eq 'no_host')) {
6581: return 'error: unable to generate unique course-ID';
6582: }
6583: }
6584: return $uname;
6585: }
6586:
6587: sub is_course {
6588: my ($cdom,$cnum) = @_;
6589: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
6590: undef,'.');
6591: if (exists($courses{$cdom.'_'.$cnum})) {
6592: return 1;
6593: }
6594: return 0;
6595: }
6596:
6597: sub store_userdata {
6598: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
6599: my $result;
6600: if ($datakey ne '') {
6601: if (ref($storehash) eq 'HASH') {
6602: if ($udom eq '' || $uname eq '') {
6603: $udom = $env{'user.domain'};
6604: $uname = $env{'user.name'};
6605: }
6606: my $uhome=&homeserver($uname,$udom);
6607: if (($uhome eq '') || ($uhome eq 'no_host')) {
6608: $result = 'error: no_host';
6609: } else {
6610: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
6611: $storehash->{'host'} = $perlvar{'lonHostID'};
6612:
6613: my $namevalue='';
6614: foreach my $key (keys(%{$storehash})) {
6615: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
6616: }
6617: $namevalue=~s/\&$//;
6618: $result = &reply("store:$env{'user.domain'}:$env{'user.name'}:".
6619: "$namespace:$datakey:$namevalue",$uhome);
6620: }
6621: } else {
6622: $result = 'error: data to store was not a hash reference';
6623: }
6624: } else {
6625: $result= 'error: invalid requestkey';
6626: }
6627: return $result;
6628: }
6629:
6630: # ---------------------------------------------------------- Assign Custom Role
6631:
6632: sub assigncustomrole {
6633: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
6634: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
6635: $end,$start,$deleteflag,$selfenroll,$context);
6636: }
6637:
6638: # ----------------------------------------------------------------- Revoke Role
6639:
6640: sub revokerole {
6641: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
6642: my $now=time;
6643: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
6644: }
6645:
6646: # ---------------------------------------------------------- Revoke Custom Role
6647:
6648: sub revokecustomrole {
6649: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
6650: my $now=time;
6651: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
6652: $deleteflag,$selfenroll,$context);
6653: }
6654:
6655: # ------------------------------------------------------------ Disk usage
6656: sub diskusage {
6657: my ($udom,$uname,$directorypath,$getpropath)=@_;
6658: $directorypath =~ s/\/$//;
6659: my $listing=&reply('du2:'.&escape($directorypath).':'
6660: .&escape($getpropath).':'.&escape($uname).':'
6661: .&escape($udom),homeserver($uname,$udom));
6662: if ($listing eq 'unknown_cmd') {
6663: if ($getpropath) {
6664: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6665: }
6666: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6667: }
6668: return $listing;
6669: }
6670:
6671: sub is_locked {
6672: my ($file_name, $domain, $user) = @_;
6673: my @check;
6674: my $is_locked;
6675: push @check, $file_name;
6676: my %locked = &get('file_permissions',\@check,
6677: $env{'user.domain'},$env{'user.name'});
6678: my ($tmp)=keys(%locked);
6679: if ($tmp=~/^error:/) { undef(%locked); }
6680:
6681: if (ref($locked{$file_name}) eq 'ARRAY') {
6682: $is_locked = 'false';
6683: foreach my $entry (@{$locked{$file_name}}) {
6684: if (ref($entry) eq 'ARRAY') {
6685: $is_locked = 'true';
6686: last;
6687: }
6688: }
6689: } else {
6690: $is_locked = 'false';
6691: }
6692: }
6693:
6694: sub declutter_portfile {
6695: my ($file) = @_;
6696: $file =~ s{^(/portfolio/|portfolio/)}{/};
6697: return $file;
6698: }
6699:
6700: # ------------------------------------------------------------- Mark as Read Only
6701:
6702: sub mark_as_readonly {
6703: my ($domain,$user,$files,$what) = @_;
6704: my %current_permissions = &dump('file_permissions',$domain,$user);
6705: my ($tmp)=keys(%current_permissions);
6706: if ($tmp=~/^error:/) { undef(%current_permissions); }
6707: foreach my $file (@{$files}) {
6708: $file = &declutter_portfile($file);
6709: push(@{$current_permissions{$file}},$what);
6710: }
6711: &put('file_permissions',\%current_permissions,$domain,$user);
6712: return;
6713: }
6714:
6715: # ------------------------------------------------------------Save Selected Files
6716:
6717: sub save_selected_files {
6718: my ($user, $path, @files) = @_;
6719: my $filename = $user."savedfiles";
6720: my @other_files = &files_not_in_path($user, $path);
6721: open (OUT, '>'.$tmpdir.$filename);
6722: foreach my $file (@files) {
6723: print (OUT $env{'form.currentpath'}.$file."\n");
6724: }
6725: foreach my $file (@other_files) {
6726: print (OUT $file."\n");
6727: }
6728: close (OUT);
6729: return 'ok';
6730: }
6731:
6732: sub clear_selected_files {
6733: my ($user) = @_;
6734: my $filename = $user."savedfiles";
6735: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6736: print (OUT undef);
6737: close (OUT);
6738: return ("ok");
6739: }
6740:
6741: sub files_in_path {
6742: my ($user, $path) = @_;
6743: my $filename = $user."savedfiles";
6744: my %return_files;
6745: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6746: while (my $line_in = <IN>) {
6747: chomp ($line_in);
6748: my @paths_and_file = split (m!/!, $line_in);
6749: my $file_part = pop (@paths_and_file);
6750: my $path_part = join ('/', @paths_and_file);
6751: $path_part.='/';
6752: my $path_and_file = $path_part.$file_part;
6753: if ($path_part eq $path) {
6754: $return_files{$file_part}= 'selected';
6755: }
6756: }
6757: close (IN);
6758: return (\%return_files);
6759: }
6760:
6761: # called in portfolio select mode, to show files selected NOT in current directory
6762: sub files_not_in_path {
6763: my ($user, $path) = @_;
6764: my $filename = $user."savedfiles";
6765: my @return_files;
6766: my $path_part;
6767: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6768: while (my $line = <IN>) {
6769: #ok, I know it's clunky, but I want it to work
6770: my @paths_and_file = split(m|/|, $line);
6771: my $file_part = pop(@paths_and_file);
6772: chomp($file_part);
6773: my $path_part = join('/', @paths_and_file);
6774: $path_part .= '/';
6775: my $path_and_file = $path_part.$file_part;
6776: if ($path_part ne $path) {
6777: push(@return_files, ($path_and_file));
6778: }
6779: }
6780: close(OUT);
6781: return (@return_files);
6782: }
6783:
6784: #----------------------------------------------Get portfolio file permissions
6785:
6786: sub get_portfile_permissions {
6787: my ($domain,$user) = @_;
6788: my %current_permissions = &dump('file_permissions',$domain,$user);
6789: my ($tmp)=keys(%current_permissions);
6790: if ($tmp=~/^error:/) { undef(%current_permissions); }
6791: return \%current_permissions;
6792: }
6793:
6794: #---------------------------------------------Get portfolio file access controls
6795:
6796: sub get_access_controls {
6797: my ($current_permissions,$group,$file) = @_;
6798: my %access;
6799: my $real_file = $file;
6800: $file =~ s/\.meta$//;
6801: if (defined($file)) {
6802: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6803: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
6804: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
6805: }
6806: }
6807: } else {
6808: foreach my $key (keys(%{$current_permissions})) {
6809: if ($key =~ /\0accesscontrol$/) {
6810: if (defined($group)) {
6811: if ($key !~ m-^\Q$group\E/-) {
6812: next;
6813: }
6814: }
6815: my ($fullpath) = split(/\0/,$key);
6816: if (ref($$current_permissions{$key}) eq 'HASH') {
6817: foreach my $control (keys(%{$$current_permissions{$key}})) {
6818: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6819: }
6820: }
6821: }
6822: }
6823: }
6824: return %access;
6825: }
6826:
6827: sub modify_access_controls {
6828: my ($file_name,$changes,$domain,$user)=@_;
6829: my ($outcome,$deloutcome);
6830: my %store_permissions;
6831: my %new_values;
6832: my %new_control;
6833: my %translation;
6834: my @deletions = ();
6835: my $now = time;
6836: if (exists($$changes{'activate'})) {
6837: if (ref($$changes{'activate'}) eq 'HASH') {
6838: my @newitems = sort(keys(%{$$changes{'activate'}}));
6839: my $numnew = scalar(@newitems);
6840: for (my $i=0; $i<$numnew; $i++) {
6841: my $newkey = $newitems[$i];
6842: my $newid = &Apache::loncommon::get_cgi_id();
6843: if ($newkey =~ /^\d+:/) {
6844: $newkey =~ s/^(\d+)/$newid/;
6845: $translation{$1} = $newid;
6846: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6847: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6848: $translation{$1} = $newid;
6849: }
6850: $new_values{$file_name."\0".$newkey} =
6851: $$changes{'activate'}{$newitems[$i]};
6852: $new_control{$newkey} = $now;
6853: }
6854: }
6855: }
6856: my %todelete;
6857: my %changed_items;
6858: foreach my $action ('delete','update') {
6859: if (exists($$changes{$action})) {
6860: if (ref($$changes{$action}) eq 'HASH') {
6861: foreach my $key (keys(%{$$changes{$action}})) {
6862: my ($itemnum) = ($key =~ /^([^:]+):/);
6863: if ($action eq 'delete') {
6864: $todelete{$itemnum} = 1;
6865: } else {
6866: $changed_items{$itemnum} = $key;
6867: }
6868: }
6869: }
6870: }
6871: }
6872: # get lock on access controls for file.
6873: my $lockhash = {
6874: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6875: ':'.$env{'user.domain'},
6876: };
6877: my $tries = 0;
6878: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6879:
6880: while (($gotlock ne 'ok') && $tries <3) {
6881: $tries ++;
6882: sleep 1;
6883: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6884: }
6885: if ($gotlock eq 'ok') {
6886: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6887: my ($tmp)=keys(%curr_permissions);
6888: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6889: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6890: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6891: if (ref($curr_controls) eq 'HASH') {
6892: foreach my $control_item (keys(%{$curr_controls})) {
6893: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6894: if (defined($todelete{$itemnum})) {
6895: push(@deletions,$file_name."\0".$control_item);
6896: } else {
6897: if (defined($changed_items{$itemnum})) {
6898: $new_control{$changed_items{$itemnum}} = $now;
6899: push(@deletions,$file_name."\0".$control_item);
6900: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6901: } else {
6902: $new_control{$control_item} = $$curr_controls{$control_item};
6903: }
6904: }
6905: }
6906: }
6907: }
6908: my ($group);
6909: if (&is_course($domain,$user)) {
6910: ($group,my $file) = split(/\//,$file_name,2);
6911: }
6912: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6913: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6914: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6915: # remove lock
6916: my @del_lock = ($file_name."\0".'locked_access_records');
6917: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
6918: my $sqlresult =
6919: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
6920: $group);
6921: } else {
6922: $outcome = "error: could not obtain lockfile\n";
6923: }
6924: return ($outcome,$deloutcome,\%new_values,\%translation);
6925: }
6926:
6927: sub make_public_indefinitely {
6928: my ($requrl) = @_;
6929: my $now = time;
6930: my $action = 'activate';
6931: my $aclnum = 0;
6932: if (&is_portfolio_url($requrl)) {
6933: my (undef,$udom,$unum,$file_name,$group) =
6934: &parse_portfolio_url($requrl);
6935: my $current_perms = &get_portfile_permissions($udom,$unum);
6936: my %access_controls = &get_access_controls($current_perms,
6937: $group,$file_name);
6938: foreach my $key (keys(%{$access_controls{$file_name}})) {
6939: my ($num,$scope,$end,$start) =
6940: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6941: if ($scope eq 'public') {
6942: if ($start <= $now && $end == 0) {
6943: $action = 'none';
6944: } else {
6945: $action = 'update';
6946: $aclnum = $num;
6947: }
6948: last;
6949: }
6950: }
6951: if ($action eq 'none') {
6952: return 'ok';
6953: } else {
6954: my %changes;
6955: my $newend = 0;
6956: my $newstart = $now;
6957: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6958: $changes{$action}{$newkey} = {
6959: type => 'public',
6960: time => {
6961: start => $newstart,
6962: end => $newend,
6963: },
6964: };
6965: my ($outcome,$deloutcome,$new_values,$translation) =
6966: &modify_access_controls($file_name,\%changes,$udom,$unum);
6967: return $outcome;
6968: }
6969: } else {
6970: return 'invalid';
6971: }
6972: }
6973:
6974: #------------------------------------------------------Get Marked as Read Only
6975:
6976: sub get_marked_as_readonly {
6977: my ($domain,$user,$what,$group) = @_;
6978: my $current_permissions = &get_portfile_permissions($domain,$user);
6979: my @readonly_files;
6980: my $cmp1=$what;
6981: if (ref($what)) { $cmp1=join('',@{$what}) };
6982: while (my ($file_name,$value) = each(%{$current_permissions})) {
6983: if (defined($group)) {
6984: if ($file_name !~ m-^\Q$group\E/-) {
6985: next;
6986: }
6987: }
6988: if (ref($value) eq "ARRAY"){
6989: foreach my $stored_what (@{$value}) {
6990: my $cmp2=$stored_what;
6991: if (ref($stored_what) eq 'ARRAY') {
6992: $cmp2=join('',@{$stored_what});
6993: }
6994: if ($cmp1 eq $cmp2) {
6995: push(@readonly_files, $file_name);
6996: last;
6997: } elsif (!defined($what)) {
6998: push(@readonly_files, $file_name);
6999: last;
7000: }
7001: }
7002: }
7003: }
7004: return @readonly_files;
7005: }
7006: #-----------------------------------------------------------Get Marked as Read Only Hash
7007:
7008: sub get_marked_as_readonly_hash {
7009: my ($current_permissions,$group,$what) = @_;
7010: my %readonly_files;
7011: while (my ($file_name,$value) = each(%{$current_permissions})) {
7012: if (defined($group)) {
7013: if ($file_name !~ m-^\Q$group\E/-) {
7014: next;
7015: }
7016: }
7017: if (ref($value) eq "ARRAY"){
7018: foreach my $stored_what (@{$value}) {
7019: if (ref($stored_what) eq 'ARRAY') {
7020: foreach my $lock_descriptor(@{$stored_what}) {
7021: if ($lock_descriptor eq 'graded') {
7022: $readonly_files{$file_name} = 'graded';
7023: } elsif ($lock_descriptor eq 'handback') {
7024: $readonly_files{$file_name} = 'handback';
7025: } else {
7026: if (!exists($readonly_files{$file_name})) {
7027: $readonly_files{$file_name} = 'locked';
7028: }
7029: }
7030: }
7031: }
7032: }
7033: }
7034: }
7035: return %readonly_files;
7036: }
7037: # ------------------------------------------------------------ Unmark as Read Only
7038:
7039: sub unmark_as_readonly {
7040: # unmarks $file_name (if $file_name is defined), or all files locked by $what
7041: # for portfolio submissions, $what contains [$symb,$crsid]
7042: my ($domain,$user,$what,$file_name,$group) = @_;
7043: $file_name = &declutter_portfile($file_name);
7044: my $symb_crs = $what;
7045: if (ref($what)) { $symb_crs=join('',@$what); }
7046: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
7047: my ($tmp)=keys(%current_permissions);
7048: if ($tmp=~/^error:/) { undef(%current_permissions); }
7049: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
7050: foreach my $file (@readonly_files) {
7051: my $clean_file = &declutter_portfile($file);
7052: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
7053: my $current_locks = $current_permissions{$file};
7054: my @new_locks;
7055: my @del_keys;
7056: if (ref($current_locks) eq "ARRAY"){
7057: foreach my $locker (@{$current_locks}) {
7058: my $compare=$locker;
7059: if (ref($locker) eq 'ARRAY') {
7060: $compare=join('',@{$locker});
7061: if ($compare ne $symb_crs) {
7062: push(@new_locks, $locker);
7063: }
7064: }
7065: }
7066: if (scalar(@new_locks) > 0) {
7067: $current_permissions{$file} = \@new_locks;
7068: } else {
7069: push(@del_keys, $file);
7070: &del('file_permissions',\@del_keys, $domain, $user);
7071: delete($current_permissions{$file});
7072: }
7073: }
7074: }
7075: &put('file_permissions',\%current_permissions,$domain,$user);
7076: return;
7077: }
7078:
7079: # ------------------------------------------------------------ Directory lister
7080:
7081: sub dirlist {
7082: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
7083: $uri=~s/^\///;
7084: $uri=~s/\/$//;
7085: my ($udom, $uname);
7086: if ($getuserdir) {
7087: $udom = $userdomain;
7088: $uname = $username;
7089: } else {
7090: (undef,$udom,$uname)=split(/\//,$uri);
7091: if(defined($userdomain)) {
7092: $udom = $userdomain;
7093: }
7094: if(defined($username)) {
7095: $uname = $username;
7096: }
7097: }
7098: my ($dirRoot,$listing,@listing_results);
7099:
7100: $dirRoot = $perlvar{'lonDocRoot'};
7101: if (defined($getpropath)) {
7102: $dirRoot = &propath($udom,$uname);
7103: $dirRoot =~ s/\/$//;
7104: } elsif (defined($getuserdir)) {
7105: my $subdir=$uname.'__';
7106: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
7107: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
7108: ."/$udom/$subdir/$uname";
7109: } elsif (defined($alternateRoot)) {
7110: $dirRoot = $alternateRoot;
7111: }
7112:
7113: if($udom) {
7114: if($uname) {
7115: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
7116: .$getuserdir.':'.&escape($dirRoot)
7117: .':'.&escape($uname).':'.&escape($udom),
7118: &homeserver($uname,$udom));
7119: if ($listing eq 'unknown_cmd') {
7120: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
7121: &homeserver($uname,$udom));
7122: } else {
7123: @listing_results = map { &unescape($_); } split(/:/,$listing);
7124: }
7125: if ($listing eq 'unknown_cmd') {
7126: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
7127: &homeserver($uname,$udom));
7128: @listing_results = split(/:/,$listing);
7129: } else {
7130: @listing_results = map { &unescape($_); } split(/:/,$listing);
7131: }
7132: return @listing_results;
7133: } elsif(!$alternateRoot) {
7134: my %allusers;
7135: my %servers = &get_servers($udom,'library');
7136: foreach my $tryserver (keys(%servers)) {
7137: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
7138: &escape($udom),$tryserver);
7139: if ($listing eq 'unknown_cmd') {
7140: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
7141: $udom, $tryserver);
7142: } else {
7143: @listing_results = map { &unescape($_); } split(/:/,$listing);
7144: }
7145: if ($listing eq 'unknown_cmd') {
7146: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
7147: $udom, $tryserver);
7148: @listing_results = split(/:/,$listing);
7149: } else {
7150: @listing_results =
7151: map { &unescape($_); } split(/:/,$listing);
7152: }
7153: if ($listing_results[0] ne 'no_such_dir' &&
7154: $listing_results[0] ne 'empty' &&
7155: $listing_results[0] ne 'con_lost') {
7156: foreach my $line (@listing_results) {
7157: my ($entry) = split(/&/,$line,2);
7158: $allusers{$entry} = 1;
7159: }
7160: }
7161: }
7162: my $alluserstr='';
7163: foreach my $user (sort(keys(%allusers))) {
7164: $alluserstr.=$user.'&user:';
7165: }
7166: $alluserstr=~s/:$//;
7167: return split(/:/,$alluserstr);
7168: } else {
7169: return ('missing user name');
7170: }
7171: } elsif(!defined($getpropath)) {
7172: my @all_domains = sort(&all_domains());
7173: foreach my $domain (@all_domains) {
7174: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
7175: }
7176: return @all_domains;
7177: } else {
7178: return ('missing domain');
7179: }
7180: }
7181:
7182: # --------------------------------------------- GetFileTimestamp
7183: # This function utilizes dirlist and returns the date stamp for
7184: # when it was last modified. It will also return an error of -1
7185: # if an error occurs
7186:
7187: sub GetFileTimestamp {
7188: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
7189: $studentDomain = &LONCAPA::clean_domain($studentDomain);
7190: $studentName = &LONCAPA::clean_username($studentName);
7191: my ($fileStat) =
7192: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
7193: undef,$getuserdir);
7194: my @stats = split('&', $fileStat);
7195: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7196: # @stats contains first the filename, then the stat output
7197: return $stats[10]; # so this is 10 instead of 9.
7198: } else {
7199: return -1;
7200: }
7201: }
7202:
7203: sub stat_file {
7204: my ($uri) = @_;
7205: $uri = &clutter_with_no_wrapper($uri);
7206:
7207: my ($udom,$uname,$file);
7208: if ($uri =~ m-^/(uploaded|editupload)/-) {
7209: ($udom,$uname,$file) =
7210: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
7211: $file = 'userfiles/'.$file;
7212: }
7213: if ($uri =~ m-^/res/-) {
7214: ($udom,$uname) =
7215: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
7216: $file = $uri;
7217: }
7218:
7219: if (!$udom || !$uname || !$file) {
7220: # unable to handle the uri
7221: return ();
7222: }
7223: my $getpropath;
7224: if ($file =~ /^userfiles\//) {
7225: $getpropath = 1;
7226: }
7227: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
7228: my @stats = split('&', $result);
7229:
7230: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
7231: shift(@stats); #filename is first
7232: return @stats;
7233: }
7234: return ();
7235: }
7236:
7237: # -------------------------------------------------------- Value of a Condition
7238:
7239: # gets the value of a specific preevaluated condition
7240: # stored in the string $env{user.state.<cid>}
7241: # or looks up a condition reference in the bighash and if if hasn't
7242: # already been evaluated recurses into docondval to get the value of
7243: # the condition, then memoizing it to
7244: # $env{user.state.<cid>.<condition>}
7245: sub directcondval {
7246: my $number=shift;
7247: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
7248: &Apache::lonuserstate::evalstate();
7249: }
7250: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
7251: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
7252: } elsif ($number =~ /^_/) {
7253: my $sub_condition;
7254: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7255: &GDBM_READER(),0640)) {
7256: $sub_condition=$bighash{'conditions'.$number};
7257: untie(%bighash);
7258: }
7259: my $value = &docondval($sub_condition);
7260: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
7261: return $value;
7262: }
7263: if ($env{'user.state.'.$env{'request.course.id'}}) {
7264: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
7265: } else {
7266: return 2;
7267: }
7268: }
7269:
7270: # get the collection of conditions for this resource
7271: sub condval {
7272: my $condidx=shift;
7273: my $allpathcond='';
7274: foreach my $cond (split(/\|/,$condidx)) {
7275: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
7276: $allpathcond.=
7277: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
7278: }
7279: }
7280: $allpathcond=~s/\|$//;
7281: return &docondval($allpathcond);
7282: }
7283:
7284: #evaluates an expression of conditions
7285: sub docondval {
7286: my ($allpathcond) = @_;
7287: my $result=0;
7288: if ($env{'request.course.id'}
7289: && defined($allpathcond)) {
7290: my $operand='|';
7291: my @stack;
7292: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
7293: if ($chunk eq '(') {
7294: push @stack,($operand,$result);
7295: } elsif ($chunk eq ')') {
7296: my $before=pop @stack;
7297: if (pop @stack eq '&') {
7298: $result=$result>$before?$before:$result;
7299: } else {
7300: $result=$result>$before?$result:$before;
7301: }
7302: } elsif (($chunk eq '&') || ($chunk eq '|')) {
7303: $operand=$chunk;
7304: } else {
7305: my $new=directcondval($chunk);
7306: if ($operand eq '&') {
7307: $result=$result>$new?$new:$result;
7308: } else {
7309: $result=$result>$new?$result:$new;
7310: }
7311: }
7312: }
7313: }
7314: return $result;
7315: }
7316:
7317: # ---------------------------------------------------- Devalidate courseresdata
7318:
7319: sub devalidatecourseresdata {
7320: my ($coursenum,$coursedomain)=@_;
7321: my $hashid=$coursenum.':'.$coursedomain;
7322: &devalidate_cache_new('courseres',$hashid);
7323: }
7324:
7325:
7326: # --------------------------------------------------- Course Resourcedata Query
7327: #
7328: # Parameters:
7329: # $coursenum - Number of the course.
7330: # $coursedomain - Domain at which the course was created.
7331: # Returns:
7332: # A hash of the course parameters along (I think) with timestamps
7333: # and version info.
7334:
7335: sub get_courseresdata {
7336: my ($coursenum,$coursedomain)=@_;
7337: my $coursehom=&homeserver($coursenum,$coursedomain);
7338: my $hashid=$coursenum.':'.$coursedomain;
7339: my ($result,$cached)=&is_cached_new('courseres',$hashid);
7340: my %dumpreply;
7341: unless (defined($cached)) {
7342: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
7343: $result=\%dumpreply;
7344: my ($tmp) = keys(%dumpreply);
7345: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
7346: &do_cache_new('courseres',$hashid,$result,600);
7347: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
7348: return $tmp;
7349: } elsif ($tmp =~ /^(error)/) {
7350: $result=undef;
7351: &do_cache_new('courseres',$hashid,$result,600);
7352: }
7353: }
7354: return $result;
7355: }
7356:
7357: sub devalidateuserresdata {
7358: my ($uname,$udom)=@_;
7359: my $hashid="$udom:$uname";
7360: &devalidate_cache_new('userres',$hashid);
7361: }
7362:
7363: sub get_userresdata {
7364: my ($uname,$udom)=@_;
7365: #most student don\'t have any data set, check if there is some data
7366: if (&EXT_cache_status($udom,$uname)) { return undef; }
7367:
7368: my $hashid="$udom:$uname";
7369: my ($result,$cached)=&is_cached_new('userres',$hashid);
7370: if (!defined($cached)) {
7371: my %resourcedata=&dump('resourcedata',$udom,$uname);
7372: $result=\%resourcedata;
7373: &do_cache_new('userres',$hashid,$result,600);
7374: }
7375: my ($tmp)=keys(%$result);
7376: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
7377: return $result;
7378: }
7379: #error 2 occurs when the .db doesn't exist
7380: if ($tmp!~/error: 2 /) {
7381: &logthis("<font color=\"blue\">WARNING:".
7382: " Trying to get resource data for ".
7383: $uname." at ".$udom.": ".
7384: $tmp."</font>");
7385: } elsif ($tmp=~/error: 2 /) {
7386: #&EXT_cache_set($udom,$uname);
7387: &do_cache_new('userres',$hashid,undef,600);
7388: undef($tmp); # not really an error so don't send it back
7389: }
7390: return $tmp;
7391: }
7392: #----------------------------------------------- resdata - return resource data
7393: # Purpose:
7394: # Return resource data for either users or for a course.
7395: # Parameters:
7396: # $name - Course/user name.
7397: # $domain - Name of the domain the user/course is registered on.
7398: # $type - Type of thing $name is (must be 'course' or 'user'
7399: # @which - Array of names of resources desired.
7400: # Returns:
7401: # The value of the first reasource in @which that is found in the
7402: # resource hash.
7403: # Exceptional Conditions:
7404: # If the $type passed in is not valid (not the string 'course' or
7405: # 'user', an undefined reference is returned.
7406: # If none of the resources are found, an undef is returned
7407: sub resdata {
7408: my ($name,$domain,$type,@which)=@_;
7409: my $result;
7410: if ($type eq 'course') {
7411: $result=&get_courseresdata($name,$domain);
7412: } elsif ($type eq 'user') {
7413: $result=&get_userresdata($name,$domain);
7414: }
7415: if (!ref($result)) { return $result; }
7416: foreach my $item (@which) {
7417: if (defined($result->{$item->[0]})) {
7418: return [$result->{$item->[0]},$item->[1]];
7419: }
7420: }
7421: return undef;
7422: }
7423:
7424: #
7425: # EXT resource caching routines
7426: #
7427:
7428: sub clear_EXT_cache_status {
7429: &delenv('cache.EXT.');
7430: }
7431:
7432: sub EXT_cache_status {
7433: my ($target_domain,$target_user) = @_;
7434: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7435: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
7436: # We know already the user has no data
7437: return 1;
7438: } else {
7439: return 0;
7440: }
7441: }
7442:
7443: sub EXT_cache_set {
7444: my ($target_domain,$target_user) = @_;
7445: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
7446: #&appenv({$cachename => time});
7447: }
7448:
7449: # --------------------------------------------------------- Value of a Variable
7450: sub EXT {
7451:
7452: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
7453: unless ($varname) { return ''; }
7454: #get real user name/domain, courseid and symb
7455: my $courseid;
7456: my $publicuser;
7457: if ($symbparm) {
7458: $symbparm=&get_symb_from_alias($symbparm);
7459: }
7460: if (!($uname && $udom)) {
7461: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
7462: if (!$symbparm) { $symbparm=$cursymb; }
7463: } else {
7464: $courseid=$env{'request.course.id'};
7465: }
7466: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
7467: my $rest;
7468: if (defined($therest[0])) {
7469: $rest=join('.',@therest);
7470: } else {
7471: $rest='';
7472: }
7473:
7474: my $qualifierrest=$qualifier;
7475: if ($rest) { $qualifierrest.='.'.$rest; }
7476: my $spacequalifierrest=$space;
7477: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
7478: if ($realm eq 'user') {
7479: # --------------------------------------------------------------- user.resource
7480: if ($space eq 'resource') {
7481: if ( (defined($Apache::lonhomework::parsing_a_problem)
7482: || defined($Apache::lonhomework::parsing_a_task))
7483: &&
7484: ($symbparm eq &symbread()) ) {
7485: # if we are in the middle of processing the resource the
7486: # get the value we are planning on committing
7487: if (defined($Apache::lonhomework::results{$qualifierrest})) {
7488: return $Apache::lonhomework::results{$qualifierrest};
7489: } else {
7490: return $Apache::lonhomework::history{$qualifierrest};
7491: }
7492: } else {
7493: my %restored;
7494: if ($publicuser || $env{'request.state'} eq 'construct') {
7495: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
7496: } else {
7497: %restored=&restore($symbparm,$courseid,$udom,$uname);
7498: }
7499: return $restored{$qualifierrest};
7500: }
7501: # ----------------------------------------------------------------- user.access
7502: } elsif ($space eq 'access') {
7503: # FIXME - not supporting calls for a specific user
7504: return &allowed($qualifier,$rest);
7505: # ------------------------------------------ user.preferences, user.environment
7506: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
7507: if (($uname eq $env{'user.name'}) &&
7508: ($udom eq $env{'user.domain'})) {
7509: return $env{join('.',('environment',$qualifierrest))};
7510: } else {
7511: my %returnhash;
7512: if (!$publicuser) {
7513: %returnhash=&userenvironment($udom,$uname,
7514: $qualifierrest);
7515: }
7516: return $returnhash{$qualifierrest};
7517: }
7518: # ----------------------------------------------------------------- user.course
7519: } elsif ($space eq 'course') {
7520: # FIXME - not supporting calls for a specific user
7521: return $env{join('.',('request.course',$qualifier))};
7522: # ------------------------------------------------------------------- user.role
7523: } elsif ($space eq 'role') {
7524: # FIXME - not supporting calls for a specific user
7525: my ($role,$where)=split(/\./,$env{'request.role'});
7526: if ($qualifier eq 'value') {
7527: return $role;
7528: } elsif ($qualifier eq 'extent') {
7529: return $where;
7530: }
7531: # ----------------------------------------------------------------- user.domain
7532: } elsif ($space eq 'domain') {
7533: return $udom;
7534: # ------------------------------------------------------------------- user.name
7535: } elsif ($space eq 'name') {
7536: return $uname;
7537: # ---------------------------------------------------- Any other user namespace
7538: } else {
7539: my %reply;
7540: if (!$publicuser) {
7541: %reply=&get($space,[$qualifierrest],$udom,$uname);
7542: }
7543: return $reply{$qualifierrest};
7544: }
7545: } elsif ($realm eq 'query') {
7546: # ---------------------------------------------- pull stuff out of query string
7547: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
7548: [$spacequalifierrest]);
7549: return $env{'form.'.$spacequalifierrest};
7550: } elsif ($realm eq 'request') {
7551: # ------------------------------------------------------------- request.browser
7552: if ($space eq 'browser') {
7553: if ($qualifier eq 'textremote') {
7554: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
7555: return 1;
7556: } else {
7557: return 0;
7558: }
7559: } else {
7560: return $env{'browser.'.$qualifier};
7561: }
7562: # ------------------------------------------------------------ request.filename
7563: } else {
7564: return $env{'request.'.$spacequalifierrest};
7565: }
7566: } elsif ($realm eq 'course') {
7567: # ---------------------------------------------------------- course.description
7568: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
7569: } elsif ($realm eq 'resource') {
7570:
7571: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
7572: if (!$symbparm) { $symbparm=&symbread(); }
7573: }
7574:
7575: if ($space eq 'title') {
7576: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
7577: return &gettitle($symbparm);
7578: }
7579:
7580: if ($space eq 'map') {
7581: my ($map) = &decode_symb($symbparm);
7582: return &symbread($map);
7583: }
7584: if ($space eq 'filename') {
7585: if ($symbparm) {
7586: return &clutter((&decode_symb($symbparm))[2]);
7587: }
7588: return &hreflocation('',$env{'request.filename'});
7589: }
7590:
7591: my ($section, $group, @groups);
7592: my ($courselevelm,$courselevel);
7593: if ($symbparm && defined($courseid) &&
7594: $courseid eq $env{'request.course.id'}) {
7595:
7596: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
7597:
7598: # ----------------------------------------------------- Cascading lookup scheme
7599: my $symbp=$symbparm;
7600: my $mapp=&deversion((&decode_symb($symbp))[0]);
7601:
7602: my $symbparm=$symbp.'.'.$spacequalifierrest;
7603: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7604:
7605: if (($env{'user.name'} eq $uname) &&
7606: ($env{'user.domain'} eq $udom)) {
7607: $section=$env{'request.course.sec'};
7608: @groups = split(/:/,$env{'request.course.groups'});
7609: @groups=&sort_course_groups($courseid,@groups);
7610: } else {
7611: if (! defined($usection)) {
7612: $section=&getsection($udom,$uname,$courseid);
7613: } else {
7614: $section = $usection;
7615: }
7616: @groups = &get_users_groups($udom,$uname,$courseid);
7617: }
7618:
7619: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7620: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7621: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7622:
7623: $courselevel=$courseid.'.'.$spacequalifierrest;
7624: my $courselevelr=$courseid.'.'.$symbparm;
7625: $courselevelm=$courseid.'.'.$mapparm;
7626:
7627: # ----------------------------------------------------------- first, check user
7628:
7629: my $userreply=&resdata($uname,$udom,'user',
7630: ([$courselevelr,'resource'],
7631: [$courselevelm,'map' ],
7632: [$courselevel, 'course' ]));
7633: if (defined($userreply)) { return &get_reply($userreply); }
7634:
7635: # ------------------------------------------------ second, check some of course
7636: my $coursereply;
7637: if (@groups > 0) {
7638: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7639: $mapparm,$spacequalifierrest);
7640: if (defined($coursereply)) { return &get_reply($coursereply); }
7641: }
7642:
7643: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7644: $env{'course.'.$courseid.'.domain'},
7645: 'course',
7646: ([$seclevelr, 'resource'],
7647: [$seclevelm, 'map' ],
7648: [$seclevel, 'course' ],
7649: [$courselevelr,'resource']));
7650: if (defined($coursereply)) { return &get_reply($coursereply); }
7651:
7652: # ------------------------------------------------------ third, check map parms
7653: my %parmhash=();
7654: my $thisparm='';
7655: if (tie(%parmhash,'GDBM_File',
7656: $env{'request.course.fn'}.'_parms.db',
7657: &GDBM_READER(),0640)) {
7658: $thisparm=$parmhash{$symbparm};
7659: untie(%parmhash);
7660: }
7661: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
7662: }
7663: # ------------------------------------------ fourth, look in resource metadata
7664:
7665: $spacequalifierrest=~s/\./\_/;
7666: my $filename;
7667: if (!$symbparm) { $symbparm=&symbread(); }
7668: if ($symbparm) {
7669: $filename=(&decode_symb($symbparm))[2];
7670: } else {
7671: $filename=$env{'request.filename'};
7672: }
7673: my $metadata=&metadata($filename,$spacequalifierrest);
7674: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7675: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
7676: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7677:
7678: # ---------------------------------------------- fourth, look in rest of course
7679: if ($symbparm && defined($courseid) &&
7680: $courseid eq $env{'request.course.id'}) {
7681: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7682: $env{'course.'.$courseid.'.domain'},
7683: 'course',
7684: ([$courselevelm,'map' ],
7685: [$courselevel, 'course']));
7686: if (defined($coursereply)) { return &get_reply($coursereply); }
7687: }
7688: # ------------------------------------------------------------------ Cascade up
7689: unless ($space eq '0') {
7690: my @parts=split(/_/,$space);
7691: my $id=pop(@parts);
7692: my $part=join('_',@parts);
7693: if ($part eq '') { $part='0'; }
7694: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
7695: $symbparm,$udom,$uname,$section,1);
7696: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
7697: }
7698: if ($recurse) { return undef; }
7699: my $pack_def=&packages_tab_default($filename,$varname);
7700: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
7701: # ---------------------------------------------------- Any other user namespace
7702: } elsif ($realm eq 'environment') {
7703: # ----------------------------------------------------------------- environment
7704: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7705: return $env{'environment.'.$spacequalifierrest};
7706: } else {
7707: if ($uname eq 'anonymous' && $udom eq '') {
7708: return '';
7709: }
7710: my %returnhash=&userenvironment($udom,$uname,
7711: $spacequalifierrest);
7712: return $returnhash{$spacequalifierrest};
7713: }
7714: } elsif ($realm eq 'system') {
7715: # ----------------------------------------------------------------- system.time
7716: if ($space eq 'time') {
7717: return time;
7718: }
7719: } elsif ($realm eq 'server') {
7720: # ----------------------------------------------------------------- system.time
7721: if ($space eq 'name') {
7722: return $ENV{'SERVER_NAME'};
7723: }
7724: }
7725: return '';
7726: }
7727:
7728: sub get_reply {
7729: my ($reply_value) = @_;
7730: if (ref($reply_value) eq 'ARRAY') {
7731: if (wantarray) {
7732: return @$reply_value;
7733: }
7734: return $reply_value->[0];
7735: } else {
7736: return $reply_value;
7737: }
7738: }
7739:
7740: sub check_group_parms {
7741: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7742: my @groupitems = ();
7743: my $resultitem;
7744: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
7745: foreach my $group (@{$groups}) {
7746: foreach my $level (@levels) {
7747: my $item = $courseid.'.['.$group.'].'.$level->[0];
7748: push(@groupitems,[$item,$level->[1]]);
7749: }
7750: }
7751: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7752: $env{'course.'.$courseid.'.domain'},
7753: 'course',@groupitems);
7754: return $coursereply;
7755: }
7756:
7757: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
7758: my ($courseid,@groups) = @_;
7759: @groups = sort(@groups);
7760: return @groups;
7761: }
7762:
7763: sub packages_tab_default {
7764: my ($uri,$varname)=@_;
7765: my (undef,$part,$name)=split(/\./,$varname);
7766:
7767: my (@extension,@specifics,$do_default);
7768: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
7769: my ($pack_type,$pack_part)=split(/_/,$package,2);
7770: if ($pack_type eq 'default') {
7771: $do_default=1;
7772: } elsif ($pack_type eq 'extension') {
7773: push(@extension,[$package,$pack_type,$pack_part]);
7774: } elsif ($pack_part eq $part || $pack_type eq 'part') {
7775: # only look at packages defaults for packages that this id is
7776: push(@specifics,[$package,$pack_type,$pack_part]);
7777: }
7778: }
7779: # first look for a package that matches the requested part id
7780: foreach my $package (@specifics) {
7781: my (undef,$pack_type,$pack_part)=@{$package};
7782: next if ($pack_part ne $part);
7783: if (defined($packagetab{"$pack_type&$name&default"})) {
7784: return $packagetab{"$pack_type&$name&default"};
7785: }
7786: }
7787: # look for any possible matching non extension_ package
7788: foreach my $package (@specifics) {
7789: my (undef,$pack_type,$pack_part)=@{$package};
7790: if (defined($packagetab{"$pack_type&$name&default"})) {
7791: return $packagetab{"$pack_type&$name&default"};
7792: }
7793: if ($pack_type eq 'part') { $pack_part='0'; }
7794: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7795: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
7796: }
7797: }
7798: # look for any posible extension_ match
7799: foreach my $package (@extension) {
7800: my ($package,$pack_type)=@{$package};
7801: if (defined($packagetab{"$pack_type&$name&default"})) {
7802: return $packagetab{"$pack_type&$name&default"};
7803: }
7804: if (defined($packagetab{$package."&$name&default"})) {
7805: return $packagetab{$package."&$name&default"};
7806: }
7807: }
7808: # look for a global default setting
7809: if ($do_default && defined($packagetab{"default&$name&default"})) {
7810: return $packagetab{"default&$name&default"};
7811: }
7812: return undef;
7813: }
7814:
7815: sub add_prefix_and_part {
7816: my ($prefix,$part)=@_;
7817: my $keyroot;
7818: if (defined($prefix) && $prefix !~ /^__/) {
7819: # prefix that has a part already
7820: $keyroot=$prefix;
7821: } elsif (defined($prefix)) {
7822: # prefix that is missing a part
7823: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7824: } else {
7825: # no prefix at all
7826: if (defined($part)) { $keyroot='_'.$part; }
7827: }
7828: return $keyroot;
7829: }
7830:
7831: # ---------------------------------------------------------------- Get metadata
7832:
7833: my %metaentry;
7834: sub metadata {
7835: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
7836: $uri=&declutter($uri);
7837: # if it is a non metadata possible uri return quickly
7838: if (($uri eq '') ||
7839: (($uri =~ m|^/*adm/|) &&
7840: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
7841: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7842: return undef;
7843: }
7844: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7845: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
7846: return undef;
7847: }
7848: my $filename=$uri;
7849: $uri=~s/\.meta$//;
7850: #
7851: # Is the metadata already cached?
7852: # Look at timestamp of caching
7853: # Everything is cached by the main uri, libraries are never directly cached
7854: #
7855: if (!defined($liburi)) {
7856: my ($result,$cached)=&is_cached_new('meta',$uri);
7857: if (defined($cached)) { return $result->{':'.$what}; }
7858: }
7859: {
7860: #
7861: # Is this a recursive call for a library?
7862: #
7863: # if (! exists($metacache{$uri})) {
7864: # $metacache{$uri}={};
7865: # }
7866: my $cachetime = 60*60;
7867: if ($liburi) {
7868: $liburi=&declutter($liburi);
7869: $filename=$liburi;
7870: } else {
7871: &devalidate_cache_new('meta',$uri);
7872: undef(%metaentry);
7873: }
7874: my %metathesekeys=();
7875: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
7876: my $metastring;
7877: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
7878: my $which = &hreflocation('','/'.($liburi || $uri));
7879: $metastring =
7880: &Apache::lonnet::ssi_body($which,
7881: ('grade_target' => 'meta'));
7882: $cachetime = 1; # only want this cached in the child not long term
7883: } elsif ($uri !~ m -^(editupload)/-) {
7884: my $file=&filelocation('',&clutter($filename));
7885: #push(@{$metaentry{$uri.'.file'}},$file);
7886: $metastring=&getfile($file);
7887: }
7888: my $parser=HTML::LCParser->new(\$metastring);
7889: my $token;
7890: undef %metathesekeys;
7891: while ($token=$parser->get_token) {
7892: if ($token->[0] eq 'S') {
7893: if (defined($token->[2]->{'package'})) {
7894: #
7895: # This is a package - get package info
7896: #
7897: my $package=$token->[2]->{'package'};
7898: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7899: if (defined($token->[2]->{'id'})) {
7900: $keyroot.='_'.$token->[2]->{'id'};
7901: }
7902: if ($metaentry{':packages'}) {
7903: $metaentry{':packages'}.=','.$package.$keyroot;
7904: } else {
7905: $metaentry{':packages'}=$package.$keyroot;
7906: }
7907: foreach my $pack_entry (keys(%packagetab)) {
7908: my $part=$keyroot;
7909: $part=~s/^\_//;
7910: if ($pack_entry=~/^\Q$package\E\&/ ||
7911: $pack_entry=~/^\Q$package\E_0\&/) {
7912: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
7913: # ignore package.tab specified default values
7914: # here &package_tab_default() will fetch those
7915: if ($subp eq 'default') { next; }
7916: my $value=$packagetab{$pack_entry};
7917: my $unikey;
7918: if ($pack =~ /_0$/) {
7919: $unikey='parameter_0_'.$name;
7920: $part=0;
7921: } else {
7922: $unikey='parameter'.$keyroot.'_'.$name;
7923: }
7924: if ($subp eq 'display') {
7925: $value.=' [Part: '.$part.']';
7926: }
7927: $metaentry{':'.$unikey.'.part'}=$part;
7928: $metathesekeys{$unikey}=1;
7929: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7930: $metaentry{':'.$unikey.'.'.$subp}=$value;
7931: }
7932: if (defined($metaentry{':'.$unikey.'.default'})) {
7933: $metaentry{':'.$unikey}=
7934: $metaentry{':'.$unikey.'.default'};
7935: }
7936: }
7937: }
7938: } else {
7939: #
7940: # This is not a package - some other kind of start tag
7941: #
7942: my $entry=$token->[1];
7943: my $unikey;
7944: if ($entry eq 'import') {
7945: $unikey='';
7946: } else {
7947: $unikey=$entry;
7948: }
7949: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7950:
7951: if (defined($token->[2]->{'id'})) {
7952: $unikey.='_'.$token->[2]->{'id'};
7953: }
7954:
7955: if ($entry eq 'import') {
7956: #
7957: # Importing a library here
7958: #
7959: if ($depthcount<20) {
7960: my $location=$parser->get_text('/import');
7961: my $dir=$filename;
7962: $dir=~s|[^/]*$||;
7963: $location=&filelocation($dir,$location);
7964: my $metadata =
7965: &metadata($uri,'keys', $location,$unikey,
7966: $depthcount+1);
7967: foreach my $meta (split(',',$metadata)) {
7968: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7969: $metathesekeys{$meta}=1;
7970: }
7971: }
7972: } else {
7973:
7974: if (defined($token->[2]->{'name'})) {
7975: $unikey.='_'.$token->[2]->{'name'};
7976: }
7977: $metathesekeys{$unikey}=1;
7978: foreach my $param (@{$token->[3]}) {
7979: $metaentry{':'.$unikey.'.'.$param} =
7980: $token->[2]->{$param};
7981: }
7982: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
7983: my $default=$metaentry{':'.$unikey.'.default'};
7984: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7985: # only ws inside the tag, and not in default, so use default
7986: # as value
7987: $metaentry{':'.$unikey}=$default;
7988: } elsif ( $internaltext =~ /\S/ ) {
7989: # something interesting inside the tag
7990: $metaentry{':'.$unikey}=$internaltext;
7991: } else {
7992: # no interesting values, don't set a default
7993: }
7994: # end of not-a-package not-a-library import
7995: }
7996: # end of not-a-package start tag
7997: }
7998: # the next is the end of "start tag"
7999: }
8000: }
8001: my ($extension) = ($uri =~ /\.(\w+)$/);
8002: $extension = lc($extension);
8003: if ($extension eq 'htm') { $extension='html'; }
8004:
8005: foreach my $key (keys(%packagetab)) {
8006: #no specific packages #how's our extension
8007: if ($key!~/^extension_\Q$extension\E&/) { next; }
8008: &metadata_create_package_def($uri,$key,'extension_'.$extension,
8009: \%metathesekeys);
8010: }
8011:
8012: if (!exists($metaentry{':packages'})
8013: || $packagetab{"import_defaults&extension_$extension"}) {
8014: foreach my $key (keys(%packagetab)) {
8015: #no specific packages well let's get default then
8016: if ($key!~/^default&/) { next; }
8017: &metadata_create_package_def($uri,$key,'default',
8018: \%metathesekeys);
8019: }
8020: }
8021: # are there custom rights to evaluate
8022: if ($metaentry{':copyright'} eq 'custom') {
8023:
8024: #
8025: # Importing a rights file here
8026: #
8027: unless ($depthcount) {
8028: my $location=$metaentry{':customdistributionfile'};
8029: my $dir=$filename;
8030: $dir=~s|[^/]*$||;
8031: $location=&filelocation($dir,$location);
8032: my $rights_metadata =
8033: &metadata($uri,'keys',$location,'_rights',
8034: $depthcount+1);
8035: foreach my $rights (split(',',$rights_metadata)) {
8036: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
8037: $metathesekeys{$rights}=1;
8038: }
8039: }
8040: }
8041: # uniqifiy package listing
8042: my %seen;
8043: my @uniq_packages =
8044: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
8045: $metaentry{':packages'} = join(',',@uniq_packages);
8046:
8047: $metaentry{':keys'} = join(',',keys(%metathesekeys));
8048: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
8049: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
8050: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
8051: # this is the end of "was not already recently cached
8052: }
8053: return $metaentry{':'.$what};
8054: }
8055:
8056: sub metadata_create_package_def {
8057: my ($uri,$key,$package,$metathesekeys)=@_;
8058: my ($pack,$name,$subp)=split(/\&/,$key);
8059: if ($subp eq 'default') { next; }
8060:
8061: if (defined($metaentry{':packages'})) {
8062: $metaentry{':packages'}.=','.$package;
8063: } else {
8064: $metaentry{':packages'}=$package;
8065: }
8066: my $value=$packagetab{$key};
8067: my $unikey;
8068: $unikey='parameter_0_'.$name;
8069: $metaentry{':'.$unikey.'.part'}=0;
8070: $$metathesekeys{$unikey}=1;
8071: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
8072: $metaentry{':'.$unikey.'.'.$subp}=$value;
8073: }
8074: if (defined($metaentry{':'.$unikey.'.default'})) {
8075: $metaentry{':'.$unikey}=
8076: $metaentry{':'.$unikey.'.default'};
8077: }
8078: }
8079:
8080: sub metadata_generate_part0 {
8081: my ($metadata,$metacache,$uri) = @_;
8082: my %allnames;
8083: foreach my $metakey (keys(%$metadata)) {
8084: if ($metakey=~/^parameter\_(.*)/) {
8085: my $part=$$metacache{':'.$metakey.'.part'};
8086: my $name=$$metacache{':'.$metakey.'.name'};
8087: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
8088: $allnames{$name}=$part;
8089: }
8090: }
8091: }
8092: foreach my $name (keys(%allnames)) {
8093: $$metadata{"parameter_0_$name"}=1;
8094: my $key=":parameter_0_$name";
8095: $$metacache{"$key.part"}='0';
8096: $$metacache{"$key.name"}=$name;
8097: $$metacache{"$key.type"}=$$metacache{':parameter_'.
8098: $allnames{$name}.'_'.$name.
8099: '.type'};
8100: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
8101: '.display'};
8102: my $expr='[Part: '.$allnames{$name}.']';
8103: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
8104: $$metacache{"$key.display"}=$olddis;
8105: }
8106: }
8107:
8108: # ------------------------------------------------------ Devalidate title cache
8109:
8110: sub devalidate_title_cache {
8111: my ($url)=@_;
8112: if (!$env{'request.course.id'}) { return; }
8113: my $symb=&symbread($url);
8114: if (!$symb) { return; }
8115: my $key=$env{'request.course.id'}."\0".$symb;
8116: &devalidate_cache_new('title',$key);
8117: }
8118:
8119: # ------------------------------------------------- Get the title of a course
8120:
8121: sub current_course_title {
8122: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
8123: }
8124: # ------------------------------------------------- Get the title of a resource
8125:
8126: sub gettitle {
8127: my $urlsymb=shift;
8128: my $symb=&symbread($urlsymb);
8129: if ($symb) {
8130: my $key=$env{'request.course.id'}."\0".$symb;
8131: my ($result,$cached)=&is_cached_new('title',$key);
8132: if (defined($cached)) {
8133: return $result;
8134: }
8135: my ($map,$resid,$url)=&decode_symb($symb);
8136: my $title='';
8137: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
8138: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
8139: } else {
8140: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8141: &GDBM_READER(),0640)) {
8142: my $mapid=$bighash{'map_pc_'.&clutter($map)};
8143: $title=$bighash{'title_'.$mapid.'.'.$resid};
8144: untie(%bighash);
8145: }
8146: }
8147: $title=~s/\&colon\;/\:/gs;
8148: if ($title) {
8149: return &do_cache_new('title',$key,$title,600);
8150: }
8151: $urlsymb=$url;
8152: }
8153: my $title=&metadata($urlsymb,'title');
8154: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
8155: return $title;
8156: }
8157:
8158: sub get_slot {
8159: my ($which,$cnum,$cdom)=@_;
8160: if (!$cnum || !$cdom) {
8161: (undef,my $courseid)=&whichuser();
8162: $cdom=$env{'course.'.$courseid.'.domain'};
8163: $cnum=$env{'course.'.$courseid.'.num'};
8164: }
8165: my $key=join("\0",'slots',$cdom,$cnum,$which);
8166: my %slotinfo;
8167: if (exists($remembered{$key})) {
8168: $slotinfo{$which} = $remembered{$key};
8169: } else {
8170: %slotinfo=&get('slots',[$which],$cdom,$cnum);
8171: &Apache::lonhomework::showhash(%slotinfo);
8172: my ($tmp)=keys(%slotinfo);
8173: if ($tmp=~/^error:/) { return (); }
8174: $remembered{$key} = $slotinfo{$which};
8175: }
8176: if (ref($slotinfo{$which}) eq 'HASH') {
8177: return %{$slotinfo{$which}};
8178: }
8179: return $slotinfo{$which};
8180: }
8181: # ------------------------------------------------- Update symbolic store links
8182:
8183: sub symblist {
8184: my ($mapname,%newhash)=@_;
8185: $mapname=&deversion(&declutter($mapname));
8186: my %hash;
8187: if (($env{'request.course.fn'}) && (%newhash)) {
8188: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8189: &GDBM_WRCREAT(),0640)) {
8190: foreach my $url (keys(%newhash)) {
8191: next if ($url eq 'last_known'
8192: && $env{'form.no_update_last_known'});
8193: $hash{declutter($url)}=&encode_symb($mapname,
8194: $newhash{$url}->[1],
8195: $newhash{$url}->[0]);
8196: }
8197: if (untie(%hash)) {
8198: return 'ok';
8199: }
8200: }
8201: }
8202: return 'error';
8203: }
8204:
8205: # --------------------------------------------------------------- Verify a symb
8206:
8207: sub symbverify {
8208: my ($symb,$thisurl)=@_;
8209: my $thisfn=$thisurl;
8210: $thisfn=&declutter($thisfn);
8211: # direct jump to resource in page or to a sequence - will construct own symbs
8212: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
8213: # check URL part
8214: my ($map,$resid,$url)=&decode_symb($symb);
8215:
8216: unless ($url eq $thisfn) { return 0; }
8217:
8218: $symb=&symbclean($symb);
8219: $thisurl=&deversion($thisurl);
8220: $thisfn=&deversion($thisfn);
8221:
8222: my %bighash;
8223: my $okay=0;
8224:
8225: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8226: &GDBM_READER(),0640)) {
8227: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
8228: $thisurl =~ s/\?.+$//;
8229: }
8230: my $ids=$bighash{'ids_'.&clutter($thisurl)};
8231: unless ($ids) {
8232: $ids=$bighash{'ids_/'.$thisurl};
8233: }
8234: if ($ids) {
8235: # ------------------------------------------------------------------- Has ID(s)
8236: foreach my $id (split(/\,/,$ids)) {
8237: my ($mapid,$resid)=split(/\./,$id);
8238: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
8239: $symb =~ s/\?.+$//;
8240: }
8241: if (
8242: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
8243: eq $symb) {
8244: if (($env{'request.role.adv'}) ||
8245: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
8246: $okay=1;
8247: }
8248: }
8249: }
8250: }
8251: untie(%bighash);
8252: }
8253: return $okay;
8254: }
8255:
8256: # --------------------------------------------------------------- Clean-up symb
8257:
8258: sub symbclean {
8259: my $symb=shift;
8260: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8261: # remove version from map
8262: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
8263:
8264: # remove version from URL
8265: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
8266:
8267: # remove wrapper
8268:
8269: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
8270: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
8271: return $symb;
8272: }
8273:
8274: # ---------------------------------------------- Split symb to find map and url
8275:
8276: sub encode_symb {
8277: my ($map,$resid,$url)=@_;
8278: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
8279: }
8280:
8281: sub decode_symb {
8282: my $symb=shift;
8283: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
8284: my ($map,$resid,$url)=split(/___/,$symb);
8285: return (&fixversion($map),$resid,&fixversion($url));
8286: }
8287:
8288: sub fixversion {
8289: my $fn=shift;
8290: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
8291: my %bighash;
8292: my $uri=&clutter($fn);
8293: my $key=$env{'request.course.id'}.'_'.$uri;
8294: # is this cached?
8295: my ($result,$cached)=&is_cached_new('courseresversion',$key);
8296: if (defined($cached)) { return $result; }
8297: # unfortunately not cached, or expired
8298: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8299: &GDBM_READER(),0640)) {
8300: if ($bighash{'version_'.$uri}) {
8301: my $version=$bighash{'version_'.$uri};
8302: unless (($version eq 'mostrecent') ||
8303: ($version==&getversion($uri))) {
8304: $uri=~s/\.(\w+)$/\.$version\.$1/;
8305: }
8306: }
8307: untie %bighash;
8308: }
8309: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
8310: }
8311:
8312: sub deversion {
8313: my $url=shift;
8314: $url=~s/\.\d+\.(\w+)$/\.$1/;
8315: return $url;
8316: }
8317:
8318: # ------------------------------------------------------ Return symb list entry
8319:
8320: sub symbread {
8321: my ($thisfn,$donotrecurse)=@_;
8322: my $cache_str='request.symbread.cached.'.$thisfn;
8323: if (defined($env{$cache_str})) { return $env{$cache_str}; }
8324: # no filename provided? try from environment
8325: unless ($thisfn) {
8326: if ($env{'request.symb'}) {
8327: return $env{$cache_str}=&symbclean($env{'request.symb'});
8328: }
8329: $thisfn=$env{'request.filename'};
8330: }
8331: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
8332: # is that filename actually a symb? Verify, clean, and return
8333: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
8334: if (&symbverify($thisfn,$1)) {
8335: return $env{$cache_str}=&symbclean($thisfn);
8336: }
8337: }
8338: $thisfn=declutter($thisfn);
8339: my %hash;
8340: my %bighash;
8341: my $syval='';
8342: if (($env{'request.course.fn'}) && ($thisfn)) {
8343: my $targetfn = $thisfn;
8344: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
8345: $targetfn = 'adm/wrapper/'.$thisfn;
8346: }
8347: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
8348: $targetfn=$1;
8349: }
8350: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
8351: &GDBM_READER(),0640)) {
8352: $syval=$hash{$targetfn};
8353: untie(%hash);
8354: }
8355: # ---------------------------------------------------------- There was an entry
8356: if ($syval) {
8357: #unless ($syval=~/\_\d+$/) {
8358: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
8359: #&appenv({'request.ambiguous' => $thisfn});
8360: #return $env{$cache_str}='';
8361: #}
8362: #$syval.=$1;
8363: #}
8364: } else {
8365: # ------------------------------------------------------- Was not in symb table
8366: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8367: &GDBM_READER(),0640)) {
8368: # ---------------------------------------------- Get ID(s) for current resource
8369: my $ids=$bighash{'ids_'.&clutter($thisfn)};
8370: unless ($ids) {
8371: $ids=$bighash{'ids_/'.$thisfn};
8372: }
8373: unless ($ids) {
8374: # alias?
8375: $ids=$bighash{'mapalias_'.$thisfn};
8376: }
8377: if ($ids) {
8378: # ------------------------------------------------------------------- Has ID(s)
8379: my @possibilities=split(/\,/,$ids);
8380: if ($#possibilities==0) {
8381: # ----------------------------------------------- There is only one possibility
8382: my ($mapid,$resid)=split(/\./,$ids);
8383: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8384: $resid,$thisfn);
8385: } elsif (!$donotrecurse) {
8386: # ------------------------------------------ There is more than one possibility
8387: my $realpossible=0;
8388: foreach my $id (@possibilities) {
8389: my $file=$bighash{'src_'.$id};
8390: if (&allowed('bre',$file)) {
8391: my ($mapid,$resid)=split(/\./,$id);
8392: if ($bighash{'map_type_'.$mapid} ne 'page') {
8393: $realpossible++;
8394: $syval=&encode_symb($bighash{'map_id_'.$mapid},
8395: $resid,$thisfn);
8396: }
8397: }
8398: }
8399: if ($realpossible!=1) { $syval=''; }
8400: } else {
8401: $syval='';
8402: }
8403: }
8404: untie(%bighash)
8405: }
8406: }
8407: if ($syval) {
8408: return $env{$cache_str}=$syval;
8409: }
8410: }
8411: &appenv({'request.ambiguous' => $thisfn});
8412: return $env{$cache_str}='';
8413: }
8414:
8415: # ---------------------------------------------------------- Return random seed
8416:
8417: sub numval {
8418: my $txt=shift;
8419: $txt=~tr/A-J/0-9/;
8420: $txt=~tr/a-j/0-9/;
8421: $txt=~tr/K-T/0-9/;
8422: $txt=~tr/k-t/0-9/;
8423: $txt=~tr/U-Z/0-5/;
8424: $txt=~tr/u-z/0-5/;
8425: $txt=~s/\D//g;
8426: if ($_64bit) { if ($txt > 2**32) { return -1; } }
8427: return int($txt);
8428: }
8429:
8430: sub numval2 {
8431: my $txt=shift;
8432: $txt=~tr/A-J/0-9/;
8433: $txt=~tr/a-j/0-9/;
8434: $txt=~tr/K-T/0-9/;
8435: $txt=~tr/k-t/0-9/;
8436: $txt=~tr/U-Z/0-5/;
8437: $txt=~tr/u-z/0-5/;
8438: $txt=~s/\D//g;
8439: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8440: my $total;
8441: foreach my $val (@txts) { $total+=$val; }
8442: if ($_64bit) { if ($total > 2**32) { return -1; } }
8443: return int($total);
8444: }
8445:
8446: sub numval3 {
8447: use integer;
8448: my $txt=shift;
8449: $txt=~tr/A-J/0-9/;
8450: $txt=~tr/a-j/0-9/;
8451: $txt=~tr/K-T/0-9/;
8452: $txt=~tr/k-t/0-9/;
8453: $txt=~tr/U-Z/0-5/;
8454: $txt=~tr/u-z/0-5/;
8455: $txt=~s/\D//g;
8456: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
8457: my $total;
8458: foreach my $val (@txts) { $total+=$val; }
8459: if ($_64bit) { $total=(($total<<32)>>32); }
8460: return $total;
8461: }
8462:
8463: sub digest {
8464: my ($data)=@_;
8465: my $digest=&Digest::MD5::md5($data);
8466: my ($a,$b,$c,$d)=unpack("iiii",$digest);
8467: my ($e,$f);
8468: {
8469: use integer;
8470: $e=($a+$b);
8471: $f=($c+$d);
8472: if ($_64bit) {
8473: $e=(($e<<32)>>32);
8474: $f=(($f<<32)>>32);
8475: }
8476: }
8477: if (wantarray) {
8478: return ($e,$f);
8479: } else {
8480: my $g;
8481: {
8482: use integer;
8483: $g=($e+$f);
8484: if ($_64bit) {
8485: $g=(($g<<32)>>32);
8486: }
8487: }
8488: return $g;
8489: }
8490: }
8491:
8492: sub latest_rnd_algorithm_id {
8493: return '64bit5';
8494: }
8495:
8496: sub get_rand_alg {
8497: my ($courseid)=@_;
8498: if (!$courseid) { $courseid=(&whichuser())[1]; }
8499: if ($courseid) {
8500: return $env{"course.$courseid.rndseed"};
8501: }
8502: return &latest_rnd_algorithm_id();
8503: }
8504:
8505: sub validCODE {
8506: my ($CODE)=@_;
8507: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
8508: return 0;
8509: }
8510:
8511: sub getCODE {
8512: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
8513: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
8514: defined($Apache::lonhomework::parsing_a_task) ) &&
8515: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
8516: return $Apache::lonhomework::history{'resource.CODE'};
8517: }
8518: return undef;
8519: }
8520:
8521: sub rndseed {
8522: my ($symb,$courseid,$domain,$username)=@_;
8523: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
8524: if (!defined($symb)) {
8525: unless ($symb=$wsymb) { return time; }
8526: }
8527: if (!$courseid) { $courseid=$wcourseid; }
8528: if (!$domain) { $domain=$wdomain; }
8529: if (!$username) { $username=$wusername }
8530: my $which=&get_rand_alg();
8531:
8532: if (defined(&getCODE())) {
8533: if ($which eq '64bit5') {
8534: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
8535: } elsif ($which eq '64bit4') {
8536: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
8537: } else {
8538: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
8539: }
8540: } elsif ($which eq '64bit5') {
8541: return &rndseed_64bit5($symb,$courseid,$domain,$username);
8542: } elsif ($which eq '64bit4') {
8543: return &rndseed_64bit4($symb,$courseid,$domain,$username);
8544: } elsif ($which eq '64bit3') {
8545: return &rndseed_64bit3($symb,$courseid,$domain,$username);
8546: } elsif ($which eq '64bit2') {
8547: return &rndseed_64bit2($symb,$courseid,$domain,$username);
8548: } elsif ($which eq '64bit') {
8549: return &rndseed_64bit($symb,$courseid,$domain,$username);
8550: }
8551: return &rndseed_32bit($symb,$courseid,$domain,$username);
8552: }
8553:
8554: sub rndseed_32bit {
8555: my ($symb,$courseid,$domain,$username)=@_;
8556: {
8557: use integer;
8558: my $symbchck=unpack("%32C*",$symb) << 27;
8559: my $symbseed=numval($symb) << 22;
8560: my $namechck=unpack("%32C*",$username) << 17;
8561: my $nameseed=numval($username) << 12;
8562: my $domainseed=unpack("%32C*",$domain) << 7;
8563: my $courseseed=unpack("%32C*",$courseid);
8564: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
8565: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8566: #&logthis("rndseed :$num:$symb");
8567: if ($_64bit) { $num=(($num<<32)>>32); }
8568: return $num;
8569: }
8570: }
8571:
8572: sub rndseed_64bit {
8573: my ($symb,$courseid,$domain,$username)=@_;
8574: {
8575: use integer;
8576: my $symbchck=unpack("%32S*",$symb) << 21;
8577: my $symbseed=numval($symb) << 10;
8578: my $namechck=unpack("%32S*",$username);
8579:
8580: my $nameseed=numval($username) << 21;
8581: my $domainseed=unpack("%32S*",$domain) << 10;
8582: my $courseseed=unpack("%32S*",$courseid);
8583:
8584: my $num1=$symbchck+$symbseed+$namechck;
8585: my $num2=$nameseed+$domainseed+$courseseed;
8586: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8587: #&logthis("rndseed :$num:$symb");
8588: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8589: return "$num1,$num2";
8590: }
8591: }
8592:
8593: sub rndseed_64bit2 {
8594: my ($symb,$courseid,$domain,$username)=@_;
8595: {
8596: use integer;
8597: # strings need to be an even # of cahracters long, it it is odd the
8598: # last characters gets thrown away
8599: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8600: my $symbseed=numval($symb) << 10;
8601: my $namechck=unpack("%32S*",$username.' ');
8602:
8603: my $nameseed=numval($username) << 21;
8604: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8605: my $courseseed=unpack("%32S*",$courseid.' ');
8606:
8607: my $num1=$symbchck+$symbseed+$namechck;
8608: my $num2=$nameseed+$domainseed+$courseseed;
8609: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8610: #&logthis("rndseed :$num:$symb");
8611: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8612: return "$num1,$num2";
8613: }
8614: }
8615:
8616: sub rndseed_64bit3 {
8617: my ($symb,$courseid,$domain,$username)=@_;
8618: {
8619: use integer;
8620: # strings need to be an even # of cahracters long, it it is odd the
8621: # last characters gets thrown away
8622: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8623: my $symbseed=numval2($symb) << 10;
8624: my $namechck=unpack("%32S*",$username.' ');
8625:
8626: my $nameseed=numval2($username) << 21;
8627: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8628: my $courseseed=unpack("%32S*",$courseid.' ');
8629:
8630: my $num1=$symbchck+$symbseed+$namechck;
8631: my $num2=$nameseed+$domainseed+$courseseed;
8632: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8633: #&logthis("rndseed :$num1:$num2:$_64bit");
8634: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8635:
8636: return "$num1:$num2";
8637: }
8638: }
8639:
8640: sub rndseed_64bit4 {
8641: my ($symb,$courseid,$domain,$username)=@_;
8642: {
8643: use integer;
8644: # strings need to be an even # of cahracters long, it it is odd the
8645: # last characters gets thrown away
8646: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8647: my $symbseed=numval3($symb) << 10;
8648: my $namechck=unpack("%32S*",$username.' ');
8649:
8650: my $nameseed=numval3($username) << 21;
8651: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8652: my $courseseed=unpack("%32S*",$courseid.' ');
8653:
8654: my $num1=$symbchck+$symbseed+$namechck;
8655: my $num2=$nameseed+$domainseed+$courseseed;
8656: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8657: #&logthis("rndseed :$num1:$num2:$_64bit");
8658: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8659:
8660: return "$num1:$num2";
8661: }
8662: }
8663:
8664: sub rndseed_64bit5 {
8665: my ($symb,$courseid,$domain,$username)=@_;
8666: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8667: return "$num1:$num2";
8668: }
8669:
8670: sub rndseed_CODE_64bit {
8671: my ($symb,$courseid,$domain,$username)=@_;
8672: {
8673: use integer;
8674: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8675: my $symbseed=numval2($symb);
8676: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8677: my $CODEseed=numval(&getCODE());
8678: my $courseseed=unpack("%32S*",$courseid.' ');
8679: my $num1=$symbseed+$CODEchck;
8680: my $num2=$CODEseed+$courseseed+$symbchck;
8681: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8682: #&logthis("rndseed :$num1:$num2:$symb");
8683: if ($_64bit) { $num1=(($num1<<32)>>32); }
8684: if ($_64bit) { $num2=(($num2<<32)>>32); }
8685: return "$num1:$num2";
8686: }
8687: }
8688:
8689: sub rndseed_CODE_64bit4 {
8690: my ($symb,$courseid,$domain,$username)=@_;
8691: {
8692: use integer;
8693: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8694: my $symbseed=numval3($symb);
8695: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8696: my $CODEseed=numval3(&getCODE());
8697: my $courseseed=unpack("%32S*",$courseid.' ');
8698: my $num1=$symbseed+$CODEchck;
8699: my $num2=$CODEseed+$courseseed+$symbchck;
8700: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8701: #&logthis("rndseed :$num1:$num2:$symb");
8702: if ($_64bit) { $num1=(($num1<<32)>>32); }
8703: if ($_64bit) { $num2=(($num2<<32)>>32); }
8704: return "$num1:$num2";
8705: }
8706: }
8707:
8708: sub rndseed_CODE_64bit5 {
8709: my ($symb,$courseid,$domain,$username)=@_;
8710: my $code = &getCODE();
8711: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8712: return "$num1:$num2";
8713: }
8714:
8715: sub setup_random_from_rndseed {
8716: my ($rndseed)=@_;
8717: if ($rndseed =~/([,:])/) {
8718: my ($num1,$num2)=split(/[,:]/,$rndseed);
8719: &Math::Random::random_set_seed(abs($num1),abs($num2));
8720: } else {
8721: &Math::Random::random_set_seed_from_phrase($rndseed);
8722: }
8723: }
8724:
8725: sub latest_receipt_algorithm_id {
8726: return 'receipt3';
8727: }
8728:
8729: sub recunique {
8730: my $fucourseid=shift;
8731: my $unique;
8732: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8733: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8734: $unique=$env{"course.$fucourseid.internal.encseed"};
8735: } else {
8736: $unique=$perlvar{'lonReceipt'};
8737: }
8738: return unpack("%32C*",$unique);
8739: }
8740:
8741: sub recprefix {
8742: my $fucourseid=shift;
8743: my $prefix;
8744: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8745: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8746: $prefix=$env{"course.$fucourseid.internal.encpref"};
8747: } else {
8748: $prefix=$perlvar{'lonHostID'};
8749: }
8750: return unpack("%32C*",$prefix);
8751: }
8752:
8753: sub ireceipt {
8754: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
8755:
8756: my $return =&recprefix($fucourseid).'-';
8757:
8758: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8759: $env{'request.state'} eq 'construct') {
8760: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8761: return $return;
8762: }
8763:
8764: my $cuname=unpack("%32C*",$funame);
8765: my $cudom=unpack("%32C*",$fudom);
8766: my $cucourseid=unpack("%32C*",$fucourseid);
8767: my $cusymb=unpack("%32C*",$fusymb);
8768: my $cunique=&recunique($fucourseid);
8769: my $cpart=unpack("%32S*",$part);
8770: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8771:
8772: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
8773:
8774: $return.= ($cunique%$cuname+
8775: $cunique%$cudom+
8776: $cusymb%$cuname+
8777: $cusymb%$cudom+
8778: $cucourseid%$cuname+
8779: $cucourseid%$cudom+
8780: $cpart%$cuname+
8781: $cpart%$cudom);
8782: } else {
8783: $return.= ($cunique%$cuname+
8784: $cunique%$cudom+
8785: $cusymb%$cuname+
8786: $cusymb%$cudom+
8787: $cucourseid%$cuname+
8788: $cucourseid%$cudom);
8789: }
8790: return $return;
8791: }
8792:
8793: sub receipt {
8794: my ($part)=@_;
8795: my ($symb,$courseid,$domain,$name) = &whichuser();
8796: return &ireceipt($name,$domain,$courseid,$symb,$part);
8797: }
8798:
8799: sub whichuser {
8800: my ($passedsymb)=@_;
8801: my ($symb,$courseid,$domain,$name,$publicuser);
8802: if (defined($env{'form.grade_symb'})) {
8803: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8804: my $allowed=&allowed('vgr',$tmp_courseid);
8805: if (!$allowed &&
8806: exists($env{'request.course.sec'}) &&
8807: $env{'request.course.sec'} !~ /^\s*$/) {
8808: $allowed=&allowed('vgr',$tmp_courseid.
8809: '/'.$env{'request.course.sec'});
8810: }
8811: if ($allowed) {
8812: ($symb)=&get_env_multiple('form.grade_symb');
8813: $courseid=$tmp_courseid;
8814: ($domain)=&get_env_multiple('form.grade_domain');
8815: ($name)=&get_env_multiple('form.grade_username');
8816: return ($symb,$courseid,$domain,$name,$publicuser);
8817: }
8818: }
8819: if (!$passedsymb) {
8820: $symb=&symbread();
8821: } else {
8822: $symb=$passedsymb;
8823: }
8824: $courseid=$env{'request.course.id'};
8825: $domain=$env{'user.domain'};
8826: $name=$env{'user.name'};
8827: if ($name eq 'public' && $domain eq 'public') {
8828: if (!defined($env{'form.username'})) {
8829: $env{'form.username'}.=time.rand(10000000);
8830: }
8831: $name.=$env{'form.username'};
8832: }
8833: return ($symb,$courseid,$domain,$name,$publicuser);
8834:
8835: }
8836:
8837: # ------------------------------------------------------------ Serves up a file
8838: # returns either the contents of the file or
8839: # -1 if the file doesn't exist
8840: #
8841: # if the target is a file that was uploaded via DOCS,
8842: # a check will be made to see if a current copy exists on the local server,
8843: # if it does this will be served, otherwise a copy will be retrieved from
8844: # the home server for the course and stored in /home/httpd/html/userfiles on
8845: # the local server.
8846:
8847: sub getfile {
8848: my ($file) = @_;
8849: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8850: &repcopy($file);
8851: return &readfile($file);
8852: }
8853:
8854: sub repcopy_userfile {
8855: my ($file)=@_;
8856: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8857: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
8858: my ($cdom,$cnum,$filename) =
8859: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
8860: my $uri="/uploaded/$cdom/$cnum/$filename";
8861: if (-e "$file") {
8862: # we already have a local copy, check it out
8863: my @fileinfo = stat($file);
8864: my $rtncode;
8865: my $info;
8866: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
8867: if ($lwpresp ne 'ok') {
8868: # there is no such file anymore, even though we had a local copy
8869: if ($rtncode eq '404') {
8870: unlink($file);
8871: }
8872: return -1;
8873: }
8874: if ($info < $fileinfo[9]) {
8875: # nice, the file we have is up-to-date, just say okay
8876: return 'ok';
8877: } else {
8878: # the file is outdated, get rid of it
8879: unlink($file);
8880: }
8881: }
8882: # one way or the other, at this point, we don't have the file
8883: # construct the correct path for the file
8884: my @parts = ($cdom,$cnum);
8885: if ($filename =~ m|^(.+)/[^/]+$|) {
8886: push @parts, split(/\//,$1);
8887: }
8888: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8889: foreach my $part (@parts) {
8890: $path .= '/'.$part;
8891: if (!-e $path) {
8892: mkdir($path,0770);
8893: }
8894: }
8895: # now the path exists for sure
8896: # get a user agent
8897: my $ua=new LWP::UserAgent;
8898: my $transferfile=$file.'.in.transfer';
8899: # FIXME: this should flock
8900: if (-e $transferfile) { return 'ok'; }
8901: my $request;
8902: $uri=~s/^\///;
8903: my $homeserver = &homeserver($cnum,$cdom);
8904: my $protocol = $protocol{$homeserver};
8905: $protocol = 'http' if ($protocol ne 'https');
8906: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
8907: my $response=$ua->request($request,$transferfile);
8908: # did it work?
8909: if ($response->is_error()) {
8910: unlink($transferfile);
8911: &logthis("Userfile repcopy failed for $uri");
8912: return -1;
8913: }
8914: # worked, rename the transfer file
8915: rename($transferfile,$file);
8916: return 'ok';
8917: }
8918:
8919: sub tokenwrapper {
8920: my $uri=shift;
8921: $uri=~s|^https?\://([^/]+)||;
8922: $uri=~s|^/||;
8923: $env{'user.environment'}=~/\/([^\/]+)\.id/;
8924: my $token=$1;
8925: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8926: if ($udom && $uname && $file) {
8927: $file=~s|(\?\.*)*$||;
8928: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
8929: my $homeserver = &homeserver($uname,$udom);
8930: my $protocol = $protocol{$homeserver};
8931: $protocol = 'http' if ($protocol ne 'https');
8932: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
8933: (($uri=~/\?/)?'&':'?').'token='.$token.
8934: '&tokenissued='.$perlvar{'lonHostID'};
8935: } else {
8936: return '/adm/notfound.html';
8937: }
8938: }
8939:
8940: # call with reqtype HEAD: get last modification time
8941: # call with reqtype GET: get the file contents
8942: # Do not call this with reqtype GET for large files! It loads everything into memory
8943: #
8944: sub getuploaded {
8945: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8946: $uri=~s/^\///;
8947: my $homeserver = &homeserver($cnum,$cdom);
8948: my $protocol = $protocol{$homeserver};
8949: $protocol = 'http' if ($protocol ne 'https');
8950: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
8951: my $ua=new LWP::UserAgent;
8952: my $request=new HTTP::Request($reqtype,$uri);
8953: my $response=$ua->request($request);
8954: $$rtncode = $response->code;
8955: if (! $response->is_success()) {
8956: return 'failed';
8957: }
8958: if ($reqtype eq 'HEAD') {
8959: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
8960: } elsif ($reqtype eq 'GET') {
8961: $$info = $response->content;
8962: }
8963: return 'ok';
8964: }
8965:
8966: sub readfile {
8967: my $file = shift;
8968: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8969: my $fh;
8970: open($fh,"<$file");
8971: my $a='';
8972: while (my $line = <$fh>) { $a .= $line; }
8973: return $a;
8974: }
8975:
8976: sub filelocation {
8977: my ($dir,$file) = @_;
8978: my $location;
8979: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
8980:
8981: if ($file =~ m-^/adm/-) {
8982: $file=~s-^/adm/wrapper/-/-;
8983: $file=~s-^/adm/coursedocs/showdoc/-/-;
8984: }
8985:
8986: if ($file=~m:^/~:) { # is a contruction space reference
8987: $location = $file;
8988: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
8989: } elsif ($file=~m{^/home/$match_username/public_html/}) {
8990: # is a correct contruction space reference
8991: $location = $file;
8992: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8993: $location = $file;
8994: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
8995: my ($udom,$uname,$filename)=
8996: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
8997: my $home=&homeserver($uname,$udom);
8998: my $is_me=0;
8999: my @ids=¤t_machine_ids();
9000: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
9001: if ($is_me) {
9002: $location=&propath($udom,$uname).'/userfiles/'.$filename;
9003: } else {
9004: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
9005: $udom.'/'.$uname.'/'.$filename;
9006: }
9007: } elsif ($file =~ m-^/adm/-) {
9008: $location = $perlvar{'lonDocRoot'}.'/'.$file;
9009: } else {
9010: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9011: $file=~s:^/res/:/:;
9012: if ( !( $file =~ m:^/:) ) {
9013: $location = $dir. '/'.$file;
9014: } else {
9015: $location = '/home/httpd/html/res'.$file;
9016: }
9017: }
9018: $location=~s://+:/:g; # remove duplicate /
9019: while ($location=~m{/\.\./}) {
9020: if ($location =~ m{/[^/]+/\.\./}) {
9021: $location=~ s{/[^/]+/\.\./}{/}g;
9022: } else {
9023: $location=~ s{/\.\./}{/}g;
9024: }
9025: } #remove dir/..
9026: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
9027: return $location;
9028: }
9029:
9030: sub hreflocation {
9031: my ($dir,$file)=@_;
9032: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
9033: $file=filelocation($dir,$file);
9034: } elsif ($file=~m-^/adm/-) {
9035: $file=~s-^/adm/wrapper/-/-;
9036: $file=~s-^/adm/coursedocs/showdoc/-/-;
9037: }
9038: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
9039: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
9040: } elsif ($file=~m-/home/($match_username)/public_html/-) {
9041: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
9042: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
9043: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
9044: -/uploaded/$1/$2/-x;
9045: }
9046: if ($file=~ m{^/userfiles/}) {
9047: $file =~ s{^/userfiles/}{/uploaded/};
9048: }
9049: return $file;
9050: }
9051:
9052: sub current_machine_domains {
9053: return &machine_domains(&hostname($perlvar{'lonHostID'}));
9054: }
9055:
9056: sub machine_domains {
9057: my ($hostname) = @_;
9058: my @domains;
9059: my %hostname = &all_hostnames();
9060: while( my($id, $name) = each(%hostname)) {
9061: # &logthis("-$id-$name-$hostname-");
9062: if ($hostname eq $name) {
9063: push(@domains,&host_domain($id));
9064: }
9065: }
9066: return @domains;
9067: }
9068:
9069: sub current_machine_ids {
9070: return &machine_ids(&hostname($perlvar{'lonHostID'}));
9071: }
9072:
9073: sub machine_ids {
9074: my ($hostname) = @_;
9075: $hostname ||= &hostname($perlvar{'lonHostID'});
9076: my @ids;
9077: my %name_to_host = &all_names();
9078: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
9079: return @{ $name_to_host{$hostname} };
9080: }
9081: return;
9082: }
9083:
9084: sub additional_machine_domains {
9085: my @domains;
9086: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
9087: while( my $line = <$fh>) {
9088: $line =~ s/\s//g;
9089: push(@domains,$line);
9090: }
9091: return @domains;
9092: }
9093:
9094: sub default_login_domain {
9095: my $domain = $perlvar{'lonDefDomain'};
9096: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
9097: foreach my $posdom (¤t_machine_domains(),
9098: &additional_machine_domains()) {
9099: if (lc($posdom) eq lc($testdomain)) {
9100: $domain=$posdom;
9101: last;
9102: }
9103: }
9104: return $domain;
9105: }
9106:
9107: # ------------------------------------------------------------- Declutters URLs
9108:
9109: sub declutter {
9110: my $thisfn=shift;
9111: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
9112: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
9113: $thisfn=~s/^\///;
9114: $thisfn=~s|^adm/wrapper/||;
9115: $thisfn=~s|^adm/coursedocs/showdoc/||;
9116: $thisfn=~s/^res\///;
9117: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
9118: $thisfn=~s/\?.+$//;
9119: }
9120: return $thisfn;
9121: }
9122:
9123: # ------------------------------------------------------------- Clutter up URLs
9124:
9125: sub clutter {
9126: my $thisfn='/'.&declutter(shift);
9127: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
9128: || $thisfn =~ m{^/adm/(includes|pages)} ) {
9129: $thisfn='/res'.$thisfn;
9130: }
9131: if ($thisfn !~m|^/adm|) {
9132: if ($thisfn =~ m|^/ext/|) {
9133: $thisfn='/adm/wrapper'.$thisfn;
9134: } else {
9135: my ($ext) = ($thisfn =~ /\.(\w+)$/);
9136: my $embstyle=&Apache::loncommon::fileembstyle($ext);
9137: if ($embstyle eq 'ssi'
9138: || ($embstyle eq 'hdn')
9139: || ($embstyle eq 'rat')
9140: || ($embstyle eq 'prv')
9141: || ($embstyle eq 'ign')) {
9142: #do nothing with these
9143: } elsif (($embstyle eq 'img')
9144: || ($embstyle eq 'emb')
9145: || ($embstyle eq 'wrp')) {
9146: $thisfn='/adm/wrapper'.$thisfn;
9147: } elsif ($embstyle eq 'unk'
9148: && $thisfn!~/\.(sequence|page)$/) {
9149: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
9150: } else {
9151: # &logthis("Got a blank emb style");
9152: }
9153: }
9154: }
9155: return $thisfn;
9156: }
9157:
9158: sub clutter_with_no_wrapper {
9159: my $uri = &clutter(shift);
9160: if ($uri =~ m-^/adm/-) {
9161: $uri =~ s-^/adm/wrapper/-/-;
9162: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
9163: }
9164: return $uri;
9165: }
9166:
9167: sub freeze_escape {
9168: my ($value)=@_;
9169: if (ref($value)) {
9170: $value=&nfreeze($value);
9171: return '__FROZEN__'.&escape($value);
9172: }
9173: return &escape($value);
9174: }
9175:
9176:
9177: sub thaw_unescape {
9178: my ($value)=@_;
9179: if ($value =~ /^__FROZEN__/) {
9180: substr($value,0,10,undef);
9181: $value=&unescape($value);
9182: return &thaw($value);
9183: }
9184: return &unescape($value);
9185: }
9186:
9187: sub correct_line_ends {
9188: my ($result)=@_;
9189: $$result =~s/\r\n/\n/mg;
9190: $$result =~s/\r/\n/mg;
9191: }
9192: # ================================================================ Main Program
9193:
9194: sub goodbye {
9195: &logthis("Starting Shut down");
9196: #not converted to using infrastruture and probably shouldn't be
9197: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
9198: #converted
9199: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
9200: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
9201: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
9202: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
9203: #1.1 only
9204: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
9205: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
9206: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
9207: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
9208: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
9209: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
9210: &logthis(sprintf("%-20s is %s",'hits',$hits));
9211: &flushcourselogs();
9212: &logthis("Shutting down");
9213: }
9214:
9215: sub get_dns {
9216: my ($url,$func,$ignore_cache) = @_;
9217: if (!$ignore_cache) {
9218: my ($content,$cached)=
9219: &Apache::lonnet::is_cached_new('dns',$url);
9220: if ($cached) {
9221: &$func($content);
9222: return;
9223: }
9224: }
9225:
9226: my %alldns;
9227: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9228: foreach my $dns (<$config>) {
9229: next if ($dns !~ /^\^(\S*)/x);
9230: my $line = $1;
9231: my ($host,$protocol) = split(/:/,$line);
9232: if ($protocol ne 'https') {
9233: $protocol = 'http';
9234: }
9235: $alldns{$host} = $protocol;
9236: }
9237: while (%alldns) {
9238: my ($dns) = keys(%alldns);
9239: my $ua=new LWP::UserAgent;
9240: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
9241: my $response=$ua->request($request);
9242: delete($alldns{$dns});
9243: next if ($response->is_error());
9244: my @content = split("\n",$response->content);
9245: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
9246: &$func(\@content);
9247: return;
9248: }
9249: close($config);
9250: my $which = (split('/',$url))[3];
9251: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
9252: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
9253: my @content = <$config>;
9254: &$func(\@content);
9255: return;
9256: }
9257: # ------------------------------------------------------------ Read domain file
9258: {
9259: my $loaded;
9260: my %domain;
9261:
9262: sub parse_domain_tab {
9263: my ($lines) = @_;
9264: foreach my $line (@$lines) {
9265: next if ($line =~ /^(\#|\s*$ )/x);
9266:
9267: chomp($line);
9268: my ($name,@elements) = split(/:/,$line,9);
9269: my %this_domain;
9270: foreach my $field ('description', 'auth_def', 'auth_arg_def',
9271: 'lang_def', 'city', 'longi', 'lati',
9272: 'primary') {
9273: $this_domain{$field} = shift(@elements);
9274: }
9275: $domain{$name} = \%this_domain;
9276: }
9277: }
9278:
9279: sub reset_domain_info {
9280: undef($loaded);
9281: undef(%domain);
9282: }
9283:
9284: sub load_domain_tab {
9285: my ($ignore_cache) = @_;
9286: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
9287: my $fh;
9288: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
9289: my @lines = <$fh>;
9290: &parse_domain_tab(\@lines);
9291: }
9292: close($fh);
9293: $loaded = 1;
9294: }
9295:
9296: sub domain {
9297: &load_domain_tab() if (!$loaded);
9298:
9299: my ($name,$what) = @_;
9300: return if ( !exists($domain{$name}) );
9301:
9302: if (!$what) {
9303: return $domain{$name}{'description'};
9304: }
9305: return $domain{$name}{$what};
9306: }
9307:
9308: sub domain_info {
9309: &load_domain_tab() if (!$loaded);
9310: return %domain;
9311: }
9312:
9313: }
9314:
9315:
9316: # ------------------------------------------------------------- Read hosts file
9317: {
9318: my %hostname;
9319: my %hostdom;
9320: my %libserv;
9321: my $loaded;
9322: my %name_to_host;
9323:
9324: sub parse_hosts_tab {
9325: my ($file) = @_;
9326: foreach my $configline (@$file) {
9327: next if ($configline =~ /^(\#|\s*$ )/x);
9328: next if ($configline =~ /^\^/);
9329: chomp($configline);
9330: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
9331: $name=~s/\s//g;
9332: if ($id && $domain && $role && $name) {
9333: $hostname{$id}=$name;
9334: push(@{$name_to_host{$name}}, $id);
9335: $hostdom{$id}=$domain;
9336: if ($role eq 'library') { $libserv{$id}=$name; }
9337: if (defined($protocol)) {
9338: if ($protocol eq 'https') {
9339: $protocol{$id} = $protocol;
9340: } else {
9341: $protocol{$id} = 'http';
9342: }
9343: } else {
9344: $protocol{$id} = 'http';
9345: }
9346: }
9347: }
9348: }
9349:
9350: sub reset_hosts_info {
9351: &purge_remembered();
9352: &reset_domain_info();
9353: &reset_hosts_ip_info();
9354: undef(%name_to_host);
9355: undef(%hostname);
9356: undef(%hostdom);
9357: undef(%libserv);
9358: undef($loaded);
9359: }
9360:
9361: sub load_hosts_tab {
9362: my ($ignore_cache) = @_;
9363: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
9364: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
9365: my @config = <$config>;
9366: &parse_hosts_tab(\@config);
9367: close($config);
9368: $loaded=1;
9369: }
9370:
9371: sub hostname {
9372: &load_hosts_tab() if (!$loaded);
9373:
9374: my ($lonid) = @_;
9375: return $hostname{$lonid};
9376: }
9377:
9378: sub all_hostnames {
9379: &load_hosts_tab() if (!$loaded);
9380:
9381: return %hostname;
9382: }
9383:
9384: sub all_names {
9385: &load_hosts_tab() if (!$loaded);
9386:
9387: return %name_to_host;
9388: }
9389:
9390: sub all_host_domain {
9391: &load_hosts_tab() if (!$loaded);
9392: return %hostdom;
9393: }
9394:
9395: sub is_library {
9396: &load_hosts_tab() if (!$loaded);
9397:
9398: return exists($libserv{$_[0]});
9399: }
9400:
9401: sub all_library {
9402: &load_hosts_tab() if (!$loaded);
9403:
9404: return %libserv;
9405: }
9406:
9407: sub get_servers {
9408: &load_hosts_tab() if (!$loaded);
9409:
9410: my ($domain,$type) = @_;
9411: my %possible_hosts = ($type eq 'library') ? %libserv
9412: : %hostname;
9413: my %result;
9414: if (ref($domain) eq 'ARRAY') {
9415: while ( my ($host,$hostname) = each(%possible_hosts)) {
9416: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
9417: $result{$host} = $hostname;
9418: }
9419: }
9420: } else {
9421: while ( my ($host,$hostname) = each(%possible_hosts)) {
9422: if ($hostdom{$host} eq $domain) {
9423: $result{$host} = $hostname;
9424: }
9425: }
9426: }
9427: return %result;
9428: }
9429:
9430: sub host_domain {
9431: &load_hosts_tab() if (!$loaded);
9432:
9433: my ($lonid) = @_;
9434: return $hostdom{$lonid};
9435: }
9436:
9437: sub all_domains {
9438: &load_hosts_tab() if (!$loaded);
9439:
9440: my %seen;
9441: my @uniq = grep(!$seen{$_}++, values(%hostdom));
9442: return @uniq;
9443: }
9444: }
9445:
9446: {
9447: my %iphost;
9448: my %name_to_ip;
9449: my %lonid_to_ip;
9450:
9451: sub get_hosts_from_ip {
9452: my ($ip) = @_;
9453: my %iphosts = &get_iphost();
9454: if (ref($iphosts{$ip})) {
9455: return @{$iphosts{$ip}};
9456: }
9457: return;
9458: }
9459:
9460: sub reset_hosts_ip_info {
9461: undef(%iphost);
9462: undef(%name_to_ip);
9463: undef(%lonid_to_ip);
9464: }
9465:
9466: sub get_host_ip {
9467: my ($lonid) = @_;
9468: if (exists($lonid_to_ip{$lonid})) {
9469: return $lonid_to_ip{$lonid};
9470: }
9471: my $name=&hostname($lonid);
9472: my $ip = gethostbyname($name);
9473: return if (!$ip || length($ip) ne 4);
9474: $ip=inet_ntoa($ip);
9475: $name_to_ip{$name} = $ip;
9476: $lonid_to_ip{$lonid} = $ip;
9477: return $ip;
9478: }
9479:
9480: sub get_iphost {
9481: my ($ignore_cache) = @_;
9482:
9483: if (!$ignore_cache) {
9484: if (%iphost) {
9485: return %iphost;
9486: }
9487: my ($ip_info,$cached)=
9488: &Apache::lonnet::is_cached_new('iphost','iphost');
9489: if ($cached) {
9490: %iphost = %{$ip_info->[0]};
9491: %name_to_ip = %{$ip_info->[1]};
9492: %lonid_to_ip = %{$ip_info->[2]};
9493: return %iphost;
9494: }
9495: }
9496:
9497: # get yesterday's info for fallback
9498: my %old_name_to_ip;
9499: my ($ip_info,$cached)=
9500: &Apache::lonnet::is_cached_new('iphost','iphost');
9501: if ($cached) {
9502: %old_name_to_ip = %{$ip_info->[1]};
9503: }
9504:
9505: my %name_to_host = &all_names();
9506: foreach my $name (keys(%name_to_host)) {
9507: my $ip;
9508: if (!exists($name_to_ip{$name})) {
9509: $ip = gethostbyname($name);
9510: if (!$ip || length($ip) ne 4) {
9511: if (defined($old_name_to_ip{$name})) {
9512: $ip = $old_name_to_ip{$name};
9513: &logthis("Can't find $name defaulting to old $ip");
9514: } else {
9515: &logthis("Name $name no IP found");
9516: next;
9517: }
9518: } else {
9519: $ip=inet_ntoa($ip);
9520: }
9521: $name_to_ip{$name} = $ip;
9522: } else {
9523: $ip = $name_to_ip{$name};
9524: }
9525: foreach my $id (@{ $name_to_host{$name} }) {
9526: $lonid_to_ip{$id} = $ip;
9527: }
9528: push(@{$iphost{$ip}},@{$name_to_host{$name}});
9529: }
9530: &Apache::lonnet::do_cache_new('iphost','iphost',
9531: [\%iphost,\%name_to_ip,\%lonid_to_ip],
9532: 48*60*60);
9533:
9534: return %iphost;
9535: }
9536:
9537: #
9538: # Given a DNS returns the loncapa host name for that DNS
9539: #
9540: sub host_from_dns {
9541: my ($dns) = @_;
9542: my @hosts;
9543: my $ip;
9544:
9545: if (exists($name_to_ip{$dns})) {
9546: $ip = $name_to_ip{$dns};
9547: }
9548: if (!$ip) {
9549: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
9550: if (length($ip) == 4) {
9551: $ip = &IO::Socket::inet_ntoa($ip);
9552: }
9553: }
9554: if ($ip) {
9555: @hosts = get_hosts_from_ip($ip);
9556: return $hosts[0];
9557: }
9558: return undef;
9559: }
9560:
9561: }
9562:
9563: BEGIN {
9564:
9565: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
9566: unless ($readit) {
9567: {
9568: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
9569: %perlvar = (%perlvar,%{$configvars});
9570: }
9571:
9572:
9573: # ------------------------------------------------------ Read spare server file
9574: {
9575: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
9576:
9577: while (my $configline=<$config>) {
9578: chomp($configline);
9579: if ($configline) {
9580: my ($host,$type) = split(':',$configline,2);
9581: if (!defined($type) || $type eq '') { $type = 'default' };
9582: push(@{ $spareid{$type} }, $host);
9583: }
9584: }
9585: close($config);
9586: }
9587: # ------------------------------------------------------------ Read permissions
9588: {
9589: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
9590:
9591: while (my $configline=<$config>) {
9592: chomp($configline);
9593: if ($configline) {
9594: my ($role,$perm)=split(/ /,$configline);
9595: if ($perm ne '') { $pr{$role}=$perm; }
9596: }
9597: }
9598: close($config);
9599: }
9600:
9601: # -------------------------------------------- Read plain texts for permissions
9602: {
9603: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
9604:
9605: while (my $configline=<$config>) {
9606: chomp($configline);
9607: if ($configline) {
9608: my ($short,@plain)=split(/:/,$configline);
9609: %{$prp{$short}} = ();
9610: if (@plain > 0) {
9611: $prp{$short}{'std'} = $plain[0];
9612: for (my $i=1; $i<@plain; $i++) {
9613: $prp{$short}{'alt'.$i} = $plain[$i];
9614: }
9615: }
9616: }
9617: }
9618: close($config);
9619: }
9620:
9621: # ---------------------------------------------------------- Read package table
9622: {
9623: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
9624:
9625: while (my $configline=<$config>) {
9626: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
9627: chomp($configline);
9628: my ($short,$plain)=split(/:/,$configline);
9629: my ($pack,$name)=split(/\&/,$short);
9630: if ($plain ne '') {
9631: $packagetab{$pack.'&'.$name.'&name'}=$name;
9632: $packagetab{$short}=$plain;
9633: }
9634: }
9635: close($config);
9636: }
9637:
9638: # ------------- set up temporary directory
9639: {
9640: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9641:
9642: }
9643:
9644: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9645: 'compress_threshold'=> 20_000,
9646: });
9647:
9648: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
9649: $dumpcount=0;
9650: $locknum=0;
9651:
9652: &logtouch();
9653: &logthis('<font color="yellow">INFO: Read configuration</font>');
9654: $readit=1;
9655: {
9656: use integer;
9657: my $test=(2**32)+1;
9658: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
9659: &logthis(" Detected 64bit platform ($_64bit)");
9660: }
9661: }
9662: }
9663:
9664: 1;
9665: __END__
9666:
9667: =pod
9668:
9669: =head1 NAME
9670:
9671: Apache::lonnet - Subroutines to ask questions about things in the network.
9672:
9673: =head1 SYNOPSIS
9674:
9675: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
9676:
9677: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9678:
9679: Common parameters:
9680:
9681: =over 4
9682:
9683: =item *
9684:
9685: $uname : an internal username (if $cname expecting a course Id specifically)
9686:
9687: =item *
9688:
9689: $udom : a domain (if $cdom expecting a course's domain specifically)
9690:
9691: =item *
9692:
9693: $symb : a resource instance identifier
9694:
9695: =item *
9696:
9697: $namespace : the name of a .db file that contains the data needed or
9698: being set.
9699:
9700: =back
9701:
9702: =head1 OVERVIEW
9703:
9704: lonnet provides subroutines which interact with the
9705: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9706: about classes, users, and resources.
9707:
9708: For many of these objects you can also use this to store data about
9709: them or modify them in various ways.
9710:
9711: =head2 Symbs
9712:
9713: To identify a specific instance of a resource, LON-CAPA uses symbols
9714: or "symbs"X<symb>. These identifiers are built from the URL of the
9715: map, the resource number of the resource in the map, and the URL of
9716: the resource itself. The latter is somewhat redundant, but might help
9717: if maps change.
9718:
9719: An example is
9720:
9721: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9722:
9723: The respective map entry is
9724:
9725: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9726: title="Problem 2">
9727: </resource>
9728:
9729: Symbs are used by the random number generator, as well as to store and
9730: restore data specific to a certain instance of for example a problem.
9731:
9732: =head2 Storing And Retrieving Data
9733:
9734: X<store()>X<cstore()>X<restore()>Three of the most important functions
9735: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9736: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9737: is is the non-critical message twin of cstore. These functions are for
9738: handlers to store a perl hash to a user's permanent data space in an
9739: easy manner, and to retrieve it again on another call. It is expected
9740: that a handler would use this once at the beginning to retrieve data,
9741: and then again once at the end to send only the new data back.
9742:
9743: The data is stored in the user's data directory on the user's
9744: homeserver under the ID of the course.
9745:
9746: The hash that is returned by restore will have all of the previous
9747: value for all of the elements of the hash.
9748:
9749: Example:
9750:
9751: #creating a hash
9752: my %hash;
9753: $hash{'foo'}='bar';
9754:
9755: #storing it
9756: &Apache::lonnet::cstore(\%hash);
9757:
9758: #changing a value
9759: $hash{'foo'}='notbar';
9760:
9761: #adding a new value
9762: $hash{'bar'}='foo';
9763: &Apache::lonnet::cstore(\%hash);
9764:
9765: #retrieving the hash
9766: my %history=&Apache::lonnet::restore();
9767:
9768: #print the hash
9769: foreach my $key (sort(keys(%history))) {
9770: print("\%history{$key} = $history{$key}");
9771: }
9772:
9773: Will print out:
9774:
9775: %history{1:foo} = bar
9776: %history{1:keys} = foo:timestamp
9777: %history{1:timestamp} = 990455579
9778: %history{2:bar} = foo
9779: %history{2:foo} = notbar
9780: %history{2:keys} = foo:bar:timestamp
9781: %history{2:timestamp} = 990455580
9782: %history{bar} = foo
9783: %history{foo} = notbar
9784: %history{timestamp} = 990455580
9785: %history{version} = 2
9786:
9787: Note that the special hash entries C<keys>, C<version> and
9788: C<timestamp> were added to the hash. C<version> will be equal to the
9789: total number of versions of the data that have been stored. The
9790: C<timestamp> attribute will be the UNIX time the hash was
9791: stored. C<keys> is available in every historical section to list which
9792: keys were added or changed at a specific historical revision of a
9793: hash.
9794:
9795: B<Warning>: do not store the hash that restore returns directly. This
9796: will cause a mess since it will restore the historical keys as if the
9797: were new keys. I.E. 1:foo will become 1:1:foo etc.
9798:
9799: Calling convention:
9800:
9801: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9802: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
9803:
9804: For more detailed information, see lonnet specific documentation.
9805:
9806: =head1 RETURN MESSAGES
9807:
9808: =over 4
9809:
9810: =item * B<con_lost>: unable to contact remote host
9811:
9812: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9813: when the connection is brought back up
9814:
9815: =item * B<con_failed>: unable to contact remote host and unable to save message
9816: for later delivery
9817:
9818: =item * B<error:>: an error a occurred, a description of the error follows the :
9819:
9820: =item * B<no_such_host>: unable to fund a host associated with the user/domain
9821: that was requested
9822:
9823: =back
9824:
9825: =head1 PUBLIC SUBROUTINES
9826:
9827: =head2 Session Environment Functions
9828:
9829: =over 4
9830:
9831: =item *
9832: X<appenv()>
9833: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
9834: the user envirnoment file, and will be restored for each access this
9835: user makes during this session, also modifies the %env for the current
9836: process. Optional rolesarrayref - if defined contains a reference to an array
9837: of roles which are exempt from the restriction on modifying user.role entries
9838: in the user's environment.db and in %env.
9839:
9840: =item *
9841: X<delenv()>
9842: B<delenv($delthis,$regexp)>: removes all items from the session
9843: environment file that begin with $delthis. If the
9844: optional second arg - $regexp - is true, $delthis is treated as a
9845: regular expression, otherwise \Q$delthis\E is used.
9846: The values are also deleted from the current processes %env.
9847:
9848: =item * get_env_multiple($name)
9849:
9850: gets $name from the %env hash, it seemlessly handles the cases where multiple
9851: values may be defined and end up as an array ref.
9852:
9853: returns an array of values
9854:
9855: =back
9856:
9857: =head2 User Information
9858:
9859: =over 4
9860:
9861: =item *
9862: X<queryauthenticate()>
9863: B<queryauthenticate($uname,$udom)>: try to determine user's current
9864: authentication scheme
9865:
9866: =item *
9867: X<authenticate()>
9868: B<authenticate($uname,$upass,$udom)>: try to
9869: authenticate user from domain's lib servers (first use the current
9870: one). C<$upass> should be the users password.
9871:
9872: =item *
9873: X<homeserver()>
9874: B<homeserver($uname,$udom)>: find the server which has
9875: the user's directory and files (there must be only one), this caches
9876: the answer, and also caches if there is a borken connection.
9877:
9878: =item *
9879: X<idget()>
9880: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9881: (IDs are a unique resource in a domain, there must be only 1 ID per
9882: username, and only 1 username per ID in a specific domain) (returns
9883: hash: id=>name,id=>name)
9884:
9885: =item *
9886: X<idrget()>
9887: B<idrget($udom,@unames)>: find the IDs behind a list of
9888: usernames (returns hash: name=>id,name=>id)
9889:
9890: =item *
9891: X<idput()>
9892: B<idput($udom,%ids)>: store away a list of names and associated IDs
9893:
9894: =item *
9895: X<rolesinit()>
9896: B<rolesinit($udom,$username,$authhost)>: get user privileges
9897:
9898: =item *
9899: X<getsection()>
9900: B<getsection($udom,$uname,$cname)>: finds the section of student in the
9901: course $cname, return section name/number or '' for "not in course"
9902: and '-1' for "no section"
9903:
9904: =item *
9905: X<userenvironment()>
9906: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
9907: passed in @what from the requested user's environment, returns a hash
9908:
9909: =item *
9910: X<userlog_query()>
9911: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9912: activity.log file. %filters defines filters applied when parsing the
9913: log file. These can be start or end timestamps, or the type of action
9914: - log to look for Login or Logout events, check for Checkin or
9915: Checkout, role for role selection. The response is in the form
9916: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9917: escaped strings of the action recorded in the activity.log file.
9918:
9919: =back
9920:
9921: =head2 User Roles
9922:
9923: =over 4
9924:
9925: =item *
9926:
9927: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
9928: F: full access
9929: U,I,K: authentication modes (cxx only)
9930: '': forbidden
9931: 1: user needs to choose course
9932: 2: browse allowed
9933: A: passphrase authentication needed
9934:
9935: =item *
9936:
9937: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9938: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9939: and course level
9940:
9941: =item *
9942:
9943: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
9944: (rolesplain.tab); plain text explanation of a user role term.
9945: $type is Course (default) or Community.
9946: If $forcedefault evaluates to true, text returned will be default
9947: text for $type. Otherwise, if this is a course, the text returned
9948: will be a custom name for the role (if defined in the course's
9949: environment). If no custom name is defined the default is returned.
9950:
9951: =item *
9952:
9953: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
9954: All arguments are optional. Returns a hash of a roles, either for
9955: co-author/assistant author roles for a user's Construction Space
9956: (default), or if $context is 'userroles', roles for the user himself,
9957: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9958: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9959: For each key, value is set to colon-separated start and end times for
9960: the role. If no username and domain are specified, will default to
9961: current user/domain. Types, roles, and roledoms are references to arrays
9962: of role statuses (active, future or previous), roles
9963: (e.g., cc,in, st etc.) and domains of the roles which can be used
9964: to restrict the list of roles reported. If no array ref is
9965: provided for types, will default to return only active roles.
9966:
9967: =back
9968:
9969: =head2 User Modification
9970:
9971: =over 4
9972:
9973: =item *
9974:
9975: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
9976: user for the level given by URL. Optional start and end dates (leave empty
9977: string or zero for "no date")
9978:
9979: =item *
9980:
9981: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9982: change a users, password, possible return values are: ok,
9983: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9984: refused
9985:
9986: =item *
9987:
9988: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
9989:
9990: =item *
9991:
9992: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9993: $forceid,$desiredhome,$email,$inststatus) :
9994: modify user
9995:
9996: =item *
9997:
9998: modifystudent
9999:
10000: modify a student's enrollment and identification information.
10001: The course id is resolved based on the current users environment.
10002: This means the envoking user must be a course coordinator or otherwise
10003: associated with a course.
10004:
10005: This call is essentially a wrapper for lonnet::modifyuser and
10006: lonnet::modify_student_enrollment
10007:
10008: Inputs:
10009:
10010: =over 4
10011:
10012: =item B<$udom> Student's loncapa domain
10013:
10014: =item B<$uname> Student's loncapa login name
10015:
10016: =item B<$uid> Student/Employee ID
10017:
10018: =item B<$umode> Student's authentication mode
10019:
10020: =item B<$upass> Student's password
10021:
10022: =item B<$first> Student's first name
10023:
10024: =item B<$middle> Student's middle name
10025:
10026: =item B<$last> Student's last name
10027:
10028: =item B<$gene> Student's generation
10029:
10030: =item B<$usec> Student's section in course
10031:
10032: =item B<$end> Unix time of the roles expiration
10033:
10034: =item B<$start> Unix time of the roles start date
10035:
10036: =item B<$forceid> If defined, allow $uid to be changed
10037:
10038: =item B<$desiredhome> server to use as home server for student
10039:
10040: =item B<$email> Student's permanent e-mail address
10041:
10042: =item B<$type> Type of enrollment (auto or manual)
10043:
10044: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
10045:
10046: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
10047:
10048: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
10049:
10050: =item B<$context> role change context (shown in User Management Logs display in a course)
10051:
10052: =item B<$inststatus> institutional status of user - : separated string of escaped status types
10053:
10054: =back
10055:
10056: =item *
10057:
10058: modify_student_enrollment
10059:
10060: Change a students enrollment status in a class. The environment variable
10061: 'role.request.course' must be defined for this function to proceed.
10062:
10063: Inputs:
10064:
10065: =over 4
10066:
10067: =item $udom, students domain
10068:
10069: =item $uname, students name
10070:
10071: =item $uid, students user id
10072:
10073: =item $first, students first name
10074:
10075: =item $middle
10076:
10077: =item $last
10078:
10079: =item $gene
10080:
10081: =item $usec
10082:
10083: =item $end
10084:
10085: =item $start
10086:
10087: =item $type
10088:
10089: =item $locktype
10090:
10091: =item $cid
10092:
10093: =item $selfenroll
10094:
10095: =item $context
10096:
10097: =back
10098:
10099:
10100: =item *
10101:
10102: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
10103: custom role; give a custom role to a user for the level given by URL. Specify
10104: name and domain of role author, and role name
10105:
10106: =item *
10107:
10108: revokerole($udom,$uname,$url,$role) : revoke a role for url
10109:
10110: =item *
10111:
10112: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
10113:
10114: =back
10115:
10116: =head2 Course Infomation
10117:
10118: =over 4
10119:
10120: =item *
10121:
10122: coursedescription($courseid) : returns a hash of information about the
10123: specified course id, including all environment settings for the
10124: course, the description of the course will be in the hash under the
10125: key 'description'
10126:
10127: =item *
10128:
10129: resdata($name,$domain,$type,@which) : request for current parameter
10130: setting for a specific $type, where $type is either 'course' or 'user',
10131: @what should be a list of parameters to ask about. This routine caches
10132: answers for 5 minutes.
10133:
10134: =item *
10135:
10136: get_courseresdata($courseid, $domain) : dump the entire course resource
10137: data base, returning a hash that is keyed by the resource name and has
10138: values that are the resource value. I believe that the timestamps and
10139: versions are also returned.
10140:
10141:
10142: =back
10143:
10144: =head2 Course Modification
10145:
10146: =over 4
10147:
10148: =item *
10149:
10150: writecoursepref($courseid,%prefs) : write preferences (environment
10151: database) for a course
10152:
10153: =item *
10154:
10155: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
10156:
10157: =item *
10158:
10159: generate_coursenum($udom) : get a unique (unused) course number in domain $udom
10160:
10161: =back
10162:
10163: =head2 Resource Subroutines
10164:
10165: =over 4
10166:
10167: =item *
10168:
10169: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
10170:
10171: =item *
10172:
10173: repcopy($filename) : subscribes to the requested file, and attempts to
10174: replicate from the owning library server, Might return
10175: 'unavailable', 'not_found', 'forbidden', 'ok', or
10176: 'bad_request', also attempts to grab the metadata for the
10177: resource. Expects the local filesystem pathname
10178: (/home/httpd/html/res/....)
10179:
10180: =back
10181:
10182: =head2 Resource Information
10183:
10184: =over 4
10185:
10186: =item *
10187:
10188: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
10189: a vairety of different possible values, $varname should be a request
10190: string, and the other parameters can be used to specify who and what
10191: one is asking about.
10192:
10193: Possible values for $varname are environment.lastname (or other item
10194: from the envirnment hash), user.name (or someother aspect about the
10195: user), resource.0.maxtries (or some other part and parameter of a
10196: resource)
10197:
10198: =item *
10199:
10200: directcondval($number) : get current value of a condition; reads from a state
10201: string
10202:
10203: =item *
10204:
10205: condval($condidx) : value of condition index based on state
10206:
10207: =item *
10208:
10209: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
10210: resource's metadata, $what should be either a specific key, or either
10211: 'keys' (to get a list of possible keys) or 'packages' to get a list of
10212: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
10213:
10214: this function automatically caches all requests
10215:
10216: =item *
10217:
10218: metadata_query($query,$custom,$customshow) : make a metadata query against the
10219: network of library servers; returns file handle of where SQL and regex results
10220: will be stored for query
10221:
10222: =item *
10223:
10224: symbread($filename) : return symbolic list entry (filename argument optional);
10225: returns the data handle
10226:
10227: =item *
10228:
10229: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
10230: a possible symb for the URL in $thisfn, and if is an encryypted
10231: resource that the user accessed using /enc/ returns a 1 on success, 0
10232: on failure, user must be in a course, as it assumes the existance of
10233: the course initial hash, and uses $env('request.course.id'}
10234:
10235:
10236: =item *
10237:
10238: symbclean($symb) : removes versions numbers from a symb, returns the
10239: cleaned symb
10240:
10241: =item *
10242:
10243: is_on_map($uri) : checks if the $uri is somewhere on the current
10244: course map, user must be in a course for it to work.
10245:
10246: =item *
10247:
10248: numval($salt) : return random seed value (addend for rndseed)
10249:
10250: =item *
10251:
10252: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
10253: a random seed, all arguments are optional, if they aren't sent it uses the
10254: environment to derive them. Note: if symb isn't sent and it can't get one
10255: from &symbread it will use the current time as its return value
10256:
10257: =item *
10258:
10259: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
10260: unfakeable, receipt
10261:
10262: =item *
10263:
10264: receipt() : API to ireceipt working off of env values; given out to users
10265:
10266: =item *
10267:
10268: countacc($url) : count the number of accesses to a given URL
10269:
10270: =item *
10271:
10272: 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
10273:
10274: =item *
10275:
10276: 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)
10277:
10278: =item *
10279:
10280: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
10281:
10282: =item *
10283:
10284: devalidate($symb) : devalidate temporary spreadsheet calculations,
10285: forcing spreadsheet to reevaluate the resource scores next time.
10286:
10287: =back
10288:
10289: =head2 Storing/Retreiving Data
10290:
10291: =over 4
10292:
10293: =item *
10294:
10295: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
10296: for this url; hashref needs to be given and should be a \%hashname; the
10297: remaining args aren't required and if they aren't passed or are '' they will
10298: be derived from the env
10299:
10300: =item *
10301:
10302: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
10303: uses critical subroutine
10304:
10305: =item *
10306:
10307: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
10308: all args are optional
10309:
10310: =item *
10311:
10312: dumpstore($namespace,$udom,$uname,$regexp,$range) :
10313: dumps the complete (or key matching regexp) namespace into a hash
10314: ($udom, $uname, $regexp, $range are optional) for a namespace that is
10315: normally &store()ed into
10316:
10317: $range should be either an integer '100' (give me the first 100
10318: matching records)
10319: or be two integers sperated by a - with no spaces
10320: '30-50' (give me the 30th through the 50th matching
10321: records)
10322:
10323:
10324: =item *
10325:
10326: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
10327: replaces a &store() version of data with a replacement set of data
10328: for a particular resource in a namespace passed in the $storehash hash
10329: reference
10330:
10331: =item *
10332:
10333: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
10334: works very similar to store/cstore, but all data is stored in a
10335: temporary location and can be reset using tmpreset, $storehash should
10336: be a hash reference, returns nothing on success
10337:
10338: =item *
10339:
10340: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
10341: similar to restore, but all data is stored in a temporary location and
10342: can be reset using tmpreset. Returns a hash of values on success,
10343: error string otherwise.
10344:
10345: =item *
10346:
10347: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
10348: deltes all keys for $symb form the temporary storage hash.
10349:
10350: =item *
10351:
10352: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10353: reference filled in from namesp ($udom and $uname are optional)
10354:
10355: =item *
10356:
10357: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
10358: namesp ($udom and $uname are optional)
10359:
10360: =item *
10361:
10362: dump($namespace,$udom,$uname,$regexp,$range) :
10363: dumps the complete (or key matching regexp) namespace into a hash
10364: ($udom, $uname, $regexp, $range are optional)
10365:
10366: $range should be either an integer '100' (give me the first 100
10367: matching records)
10368: or be two integers sperated by a - with no spaces
10369: '30-50' (give me the 30th through the 50th matching
10370: records)
10371: =item *
10372:
10373: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
10374: $store can be a scalar, an array reference, or if the amount to be
10375: incremented is > 1, a hash reference.
10376:
10377: ($udom and $uname are optional)
10378:
10379: =item *
10380:
10381: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
10382: ($udom and $uname are optional)
10383:
10384: =item *
10385:
10386: cput($namespace,$storehash,$udom,$uname) : critical put
10387: ($udom and $uname are optional)
10388:
10389: =item *
10390:
10391: newput($namespace,$storehash,$udom,$uname) :
10392:
10393: Attempts to store the items in the $storehash, but only if they don't
10394: currently exist, if this succeeds you can be certain that you have
10395: successfully created a new key value pair in the $namespace db.
10396:
10397:
10398: Args:
10399: $namespace: name of database to store values to
10400: $storehash: hashref to store to the db
10401: $udom: (optional) domain of user containing the db
10402: $uname: (optional) name of user caontaining the db
10403:
10404: Returns:
10405: 'ok' -> succeeded in storing all keys of $storehash
10406: 'key_exists: <key>' -> failed to anything out of $storehash, as at
10407: least <key> already existed in the db (other
10408: requested keys may also already exist)
10409: 'error: <msg>' -> unable to tie the DB or other error occurred
10410: 'con_lost' -> unable to contact request server
10411: 'refused' -> action was not allowed by remote machine
10412:
10413:
10414: =item *
10415:
10416: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
10417: reference filled in from namesp (encrypts the return communication)
10418: ($udom and $uname are optional)
10419:
10420: =item *
10421:
10422: log($udom,$name,$home,$message) : write to permanent log for user; use
10423: critical subroutine
10424:
10425: =item *
10426:
10427: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
10428: array reference filled in from namespace found in domain level on either
10429: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
10430:
10431: =item *
10432:
10433: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
10434: domain level either on specified domain server ($uhome) or primary domain
10435: server ($udom and $uhome are optional)
10436:
10437: =item *
10438:
10439: get_domain_defaults($target_domain) : returns hash with defaults for
10440: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
10441: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
10442: or localauth), initial password or a kerberos realm, language (e.g., en-us).
10443: Values are retrieved from cache (if current), or from domain's configuration.db
10444: (if available), or lastly from values in lonTabs/dns_domain,tab,
10445: or lonTabs/domain.tab.
10446:
10447: %domdefaults = &get_auth_defaults($target_domain);
10448:
10449: =back
10450:
10451: =head2 Network Status Functions
10452:
10453: =over 4
10454:
10455: =item *
10456:
10457: dirlist($uri) : return directory list based on URI
10458:
10459: =item *
10460:
10461: spareserver() : find server with least workload from spare.tab
10462:
10463:
10464: =item *
10465:
10466: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
10467: if there is no corresponding loncapa host.
10468:
10469: =back
10470:
10471:
10472: =head2 Apache Request
10473:
10474: =over 4
10475:
10476: =item *
10477:
10478: ssi($url,%hash) : server side include, does a complete request cycle on url to
10479: localhost, posts hash
10480:
10481: =back
10482:
10483: =head2 Data to String to Data
10484:
10485: =over 4
10486:
10487: =item *
10488:
10489: hash2str(%hash) : convert a hash into a string complete with escaping and '='
10490: and '&' separators, supports elements that are arrayrefs and hashrefs
10491:
10492: =item *
10493:
10494: hashref2str($hashref) : convert a hashref into a string complete with
10495: escaping and '=' and '&' separators, supports elements that are
10496: arrayrefs and hashrefs
10497:
10498: =item *
10499:
10500: arrayref2str($arrayref) : convert an arrayref into a string complete
10501: with escaping and '&' separators, supports elements that are arrayrefs
10502: and hashrefs
10503:
10504: =item *
10505:
10506: str2hash($string) : convert string to hash using unescaping and
10507: splitting on '=' and '&', supports elements that are arrayrefs and
10508: hashrefs
10509:
10510: =item *
10511:
10512: str2array($string) : convert string to hash using unescaping and
10513: splitting on '&', supports elements that are arrayrefs and hashrefs
10514:
10515: =back
10516:
10517: =head2 Logging Routines
10518:
10519: =over 4
10520:
10521: These routines allow one to make log messages in the lonnet.log and
10522: lonnet.perm logfiles.
10523:
10524: =item *
10525:
10526: logtouch() : make sure the logfile, lonnet.log, exists
10527:
10528: =item *
10529:
10530: logthis() : append message to the normal lonnet.log file, it gets
10531: preiodically rolled over and deleted.
10532:
10533: =item *
10534:
10535: logperm() : append a permanent message to lonnet.perm.log, this log
10536: file never gets deleted by any automated portion of the system, only
10537: messages of critical importance should go in here.
10538:
10539: =back
10540:
10541: =head2 General File Helper Routines
10542:
10543: =over 4
10544:
10545: =item *
10546:
10547: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
10548: (a) files in /uploaded
10549: (i) If a local copy of the file exists -
10550: compares modification date of local copy with last-modified date for
10551: definitive version stored on home server for course. If local copy is
10552: stale, requests a new version from the home server and stores it.
10553: If the original has been removed from the home server, then local copy
10554: is unlinked.
10555: (ii) If local copy does not exist -
10556: requests the file from the home server and stores it.
10557:
10558: If $caller is 'uploadrep':
10559: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
10560: for request for files originally uploaded via DOCS.
10561: - returns 'ok' if fresh local copy now available, -1 otherwise.
10562:
10563: Otherwise:
10564: This indicates a call from the content generation phase of the request.
10565: - returns the entire contents of the file or -1.
10566:
10567: (b) files in /res
10568: - returns the entire contents of a file or -1;
10569: it properly subscribes to and replicates the file if neccessary.
10570:
10571:
10572: =item *
10573:
10574: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
10575: reference
10576:
10577: returns either a stat() list of data about the file or an empty list
10578: if the file doesn't exist or couldn't find out about it (connection
10579: problems or user unknown)
10580:
10581: =item *
10582:
10583: filelocation($dir,$file) : returns file system location of a file
10584: based on URI; meant to be "fairly clean" absolute reference, $dir is a
10585: directory that relative $file lookups are to looked in ($dir of /a/dir
10586: and a file of ../bob will become /a/bob)
10587:
10588: =item *
10589:
10590: hreflocation($dir,$file) : returns file system location or a URL; same as
10591: filelocation except for hrefs
10592:
10593: =item *
10594:
10595: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
10596:
10597: =back
10598:
10599: =head2 Usererfile file routines (/uploaded*)
10600:
10601: =over 4
10602:
10603: =item *
10604:
10605: userfileupload(): main rotine for putting a file in a user or course's
10606: filespace, arguments are,
10607:
10608: formname - required - this is the name of the element in $env where the
10609: filename, and the contents of the file to create/modifed exist
10610: the filename is in $env{'form.'.$formname.'.filename'} and the
10611: contents of the file is located in $env{'form.'.$formname}
10612: coursedoc - if true, store the file in the course of the active role
10613: of the current user
10614: subdir - required - subdirectory to put the file in under ../userfiles/
10615: if undefined, it will be placed in "unknown"
10616:
10617: (This routine calls clean_filename() to remove any dangerous
10618: characters from the filename, and then calls finuserfileupload() to
10619: complete the transaction)
10620:
10621: returns either the url of the uploaded file (/uploaded/....) if successful
10622: and /adm/notfound.html if unsuccessful
10623:
10624: =item *
10625:
10626: clean_filename(): routine for cleaing a filename up for storage in
10627: userfile space, argument is:
10628:
10629: filename - proposed filename
10630:
10631: returns: the new clean filename
10632:
10633: =item *
10634:
10635: finishuserfileupload(): routine that creaes and sends the file to
10636: userspace, probably shouldn't be called directly
10637:
10638: docuname: username or courseid of destination for the file
10639: docudom: domain of user/course of destination for the file
10640: formname: same as for userfileupload()
10641: fname: filename (inculding subdirectories) for the file
10642:
10643: returns either the url of the uploaded file (/uploaded/....) if successful
10644: and /adm/notfound.html if unsuccessful
10645:
10646: =item *
10647:
10648: renameuserfile(): renames an existing userfile to a new name
10649:
10650: Args:
10651: docuname: username or courseid of destination for the file
10652: docudom: domain of user/course of destination for the file
10653: old: current file name (including any subdirs under userfiles)
10654: new: desired file name (including any subdirs under userfiles)
10655:
10656: =item *
10657:
10658: mkdiruserfile(): creates a directory is a userfiles dir
10659:
10660: Args:
10661: docuname: username or courseid of destination for the file
10662: docudom: domain of user/course of destination for the file
10663: dir: dir to create (including any subdirs under userfiles)
10664:
10665: =item *
10666:
10667: removeuserfile(): removes a file that exists in userfiles
10668:
10669: Args:
10670: docuname: username or courseid of destination for the file
10671: docudom: domain of user/course of destination for the file
10672: fname: filname to delete (including any subdirs under userfiles)
10673:
10674: =item *
10675:
10676: removeuploadedurl(): convience function for removeuserfile()
10677:
10678: Args:
10679: url: a full /uploaded/... url to delete
10680:
10681: =item *
10682:
10683: get_portfile_permissions():
10684: Args:
10685: domain: domain of user or course contain the portfolio files
10686: user: name of user or num of course contain the portfolio files
10687: Returns:
10688: hashref of a dump of the proper file_permissions.db
10689:
10690:
10691: =item *
10692:
10693: get_access_controls():
10694:
10695: Args:
10696: current_permissions: the hash ref returned from get_portfile_permissions()
10697: group: (optional) the group you want the files associated with
10698: file: (optional) the file you want access info on
10699:
10700: Returns:
10701: a hash (keys are file names) of hashes containing
10702: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10703: values are XML containing access control settings (see below)
10704:
10705: Internal notes:
10706:
10707: access controls are stored in file_permissions.db as key=value pairs.
10708: key -> path to file/file_name\0uniqueID:scope_end_start
10709: where scope -> public,guest,course,group,domains or users.
10710: end -> UNIX time for end of access (0 -> no end date)
10711: start -> UNIX time for start of access
10712:
10713: value -> XML description of access control
10714: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10715: <start></start>
10716: <end></end>
10717:
10718: <password></password> for scope type = guest
10719:
10720: <domain></domain> for scope type = course or group
10721: <number></number>
10722: <roles id="">
10723: <role></role>
10724: <access></access>
10725: <section></section>
10726: <group></group>
10727: </roles>
10728:
10729: <dom></dom> for scope type = domains
10730:
10731: <users> for scope type = users
10732: <user>
10733: <uname></uname>
10734: <udom></udom>
10735: </user>
10736: </users>
10737: </scope>
10738:
10739: Access data is also aggregated for each file in an additional key=value pair:
10740: key -> path to file/file_name\0accesscontrol
10741: value -> reference to hash
10742: hash contains key = value pairs
10743: where key = uniqueID:scope_end_start
10744: value = UNIX time record was last updated
10745:
10746: Used to improve speed of look-ups of access controls for each file.
10747:
10748: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10749:
10750: modify_access_controls():
10751:
10752: Modifies access controls for a portfolio file
10753: Args
10754: 1. file name
10755: 2. reference to hash of required changes,
10756: 3. domain
10757: 4. username
10758: where domain,username are the domain of the portfolio owner
10759: (either a user or a course)
10760:
10761: Returns:
10762: 1. result of additions or updates ('ok' or 'error', with error message).
10763: 2. result of deletions ('ok' or 'error', with error message).
10764: 3. reference to hash of any new or updated access controls.
10765: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10766: key = integer (inbound ID)
10767: value = uniqueID
10768:
10769: =back
10770:
10771: =head2 HTTP Helper Routines
10772:
10773: =over 4
10774:
10775: =item *
10776:
10777: escape() : unpack non-word characters into CGI-compatible hex codes
10778:
10779: =item *
10780:
10781: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10782:
10783: =back
10784:
10785: =head1 PRIVATE SUBROUTINES
10786:
10787: =head2 Underlying communication routines (Shouldn't call)
10788:
10789: =over 4
10790:
10791: =item *
10792:
10793: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10794:
10795: =item *
10796:
10797: reply() : uses subreply to send a message to remote machine, logs all failures
10798:
10799: =item *
10800:
10801: critical() : passes a critical message to another server; if cannot
10802: get through then place message in connection buffer directory and
10803: returns con_delayed, if incapable of saving message, returns
10804: con_failed
10805:
10806: =item *
10807:
10808: reconlonc() : tries to reconnect lonc client processes.
10809:
10810: =back
10811:
10812: =head2 Resource Access Logging
10813:
10814: =over 4
10815:
10816: =item *
10817:
10818: flushcourselogs() : flush (save) buffer logs and access logs
10819:
10820: =item *
10821:
10822: courselog($what) : save message for course in hash
10823:
10824: =item *
10825:
10826: courseacclog($what) : save message for course using &courselog(). Perform
10827: special processing for specific resource types (problems, exams, quizzes, etc).
10828:
10829: =item *
10830:
10831: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10832: as a PerlChildExitHandler
10833:
10834: =back
10835:
10836: =head2 Other
10837:
10838: =over 4
10839:
10840: =item *
10841:
10842: symblist($mapname,%newhash) : update symbolic storage links
10843:
10844: =back
10845:
10846: =cut
10847:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>