1: # The LearningOnline Network
2: # TCP networking package
3: #
4: # $Id: lonnet.pm,v 1.976.2.4 2008/12/31 18:26:53 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 Date::Parse;
77: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
78: $_64bit %env %protocol);
79:
80: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
81: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
82: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
83: %courseownerbuf, %coursetypebuf,$locknum);
84:
85: use IO::Socket;
86: use GDBM_File;
87: use HTML::LCParser;
88: use Fcntl qw(:flock);
89: use Storable qw(thaw nfreeze);
90: use Time::HiRes qw( gettimeofday tv_interval );
91: use Cache::Memcached;
92: use Digest::MD5;
93: use Math::Random;
94: use LONCAPA qw(:DEFAULT :match);
95: use LONCAPA::Configuration;
96:
97: my $readit;
98: my $max_connection_retries = 10; # Or some such value.
99:
100: require Exporter;
101:
102: our @ISA = qw (Exporter);
103: our @EXPORT = qw(%env);
104:
105:
106: # --------------------------------------------------------------------- Logging
107: {
108: my $logid;
109: sub instructor_log {
110: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
111: if (($cnum eq '') || ($cdom eq '')) {
112: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
113: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
114: }
115: $logid++;
116: my $now = time();
117: my $id=$now.'00000'.$$.'00000'.$logid;
118: return &Apache::lonnet::put('nohist_'.$hash_name,
119: { $id => {
120: 'exe_uname' => $env{'user.name'},
121: 'exe_udom' => $env{'user.domain'},
122: 'exe_time' => $now,
123: 'exe_ip' => $ENV{'REMOTE_ADDR'},
124: 'delflag' => $delflag,
125: 'logentry' => $storehash,
126: 'uname' => $uname,
127: 'udom' => $udom,
128: }
129: },$cdom,$cnum);
130: }
131: }
132:
133: sub logtouch {
134: my $execdir=$perlvar{'lonDaemons'};
135: unless (-e "$execdir/logs/lonnet.log") {
136: open(my $fh,">>$execdir/logs/lonnet.log");
137: close $fh;
138: }
139: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
140: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
141: }
142:
143: sub logthis {
144: my $message=shift;
145: my $execdir=$perlvar{'lonDaemons'};
146: my $now=time;
147: my $local=localtime($now);
148: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
149: print $fh "$local ($$): $message\n";
150: close($fh);
151: }
152: return 1;
153: }
154:
155: sub logperm {
156: my $message=shift;
157: my $execdir=$perlvar{'lonDaemons'};
158: my $now=time;
159: my $local=localtime($now);
160: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
161: print $fh "$now:$message:$local\n";
162: close($fh);
163: }
164: return 1;
165: }
166:
167: sub create_connection {
168: my ($hostname,$lonid) = @_;
169: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
170: Type => SOCK_STREAM,
171: Timeout => 10);
172: return 0 if (!$client);
173: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
174: my $result = <$client>;
175: chomp($result);
176: return 1 if ($result eq 'done');
177: return 0;
178: }
179:
180:
181: # -------------------------------------------------- Non-critical communication
182: sub subreply {
183: my ($cmd,$server)=@_;
184: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
185: #
186: # With loncnew process trimming, there's a timing hole between lonc server
187: # process exit and the master server picking up the listen on the AF_UNIX
188: # socket. In that time interval, a lock file will exist:
189:
190: my $lockfile=$peerfile.".lock";
191: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
192: sleep(1);
193: }
194: # At this point, either a loncnew parent is listening or an old lonc
195: # or loncnew child is listening so we can connect or everything's dead.
196: #
197: # We'll give the connection a few tries before abandoning it. If
198: # connection is not possible, we'll con_lost back to the client.
199: #
200: my $client;
201: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
202: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
203: Type => SOCK_STREAM,
204: Timeout => 10);
205: if ($client) {
206: last; # Connected!
207: } else {
208: &create_connection(&hostname($server),$server);
209: }
210: sleep(1); # Try again later if failed connection.
211: }
212: my $answer;
213: if ($client) {
214: print $client "sethost:$server:$cmd\n";
215: $answer=<$client>;
216: if (!$answer) { $answer="con_lost"; }
217: chomp($answer);
218: } else {
219: $answer = 'con_lost'; # Failed connection.
220: }
221: return $answer;
222: }
223:
224: sub reply {
225: my ($cmd,$server)=@_;
226: unless (defined(&hostname($server))) { return 'no_such_host'; }
227: my $answer=subreply($cmd,$server);
228: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
229: &logthis("<font color=\"blue\">WARNING:".
230: " $cmd to $server returned $answer</font>");
231: }
232: return $answer;
233: }
234:
235: # ----------------------------------------------------------- Send USR1 to lonc
236:
237: sub reconlonc {
238: my ($lonid) = @_;
239: my $hostname = &hostname($lonid);
240: if ($lonid) {
241: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
242: if ($hostname && -e $peerfile) {
243: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
244: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
245: Type => SOCK_STREAM,
246: Timeout => 10);
247: if ($client) {
248: print $client ("reset_retries\n");
249: my $answer=<$client>;
250: #reset just this one.
251: }
252: }
253: return;
254: }
255:
256: &logthis("Trying to reconnect lonc");
257: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
258: if (open(my $fh,"<$loncfile")) {
259: my $loncpid=<$fh>;
260: chomp($loncpid);
261: if (kill 0 => $loncpid) {
262: &logthis("lonc at pid $loncpid responding, sending USR1");
263: kill USR1 => $loncpid;
264: sleep 1;
265: } else {
266: &logthis(
267: "<font color=\"blue\">WARNING:".
268: " lonc at pid $loncpid not responding, giving up</font>");
269: }
270: } else {
271: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
272: }
273: }
274:
275: # ------------------------------------------------------ Critical communication
276:
277: sub critical {
278: my ($cmd,$server)=@_;
279: unless (&hostname($server)) {
280: &logthis("<font color=\"blue\">WARNING:".
281: " Critical message to unknown server ($server)</font>");
282: return 'no_such_host';
283: }
284: my $answer=reply($cmd,$server);
285: if ($answer eq 'con_lost') {
286: &reconlonc("$perlvar{'lonSockDir'}/$server");
287: my $answer=reply($cmd,$server);
288: if ($answer eq 'con_lost') {
289: my $now=time;
290: my $middlename=$cmd;
291: $middlename=substr($middlename,0,16);
292: $middlename=~s/\W//g;
293: my $dfilename=
294: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
295: $dumpcount++;
296: {
297: my $dfh;
298: if (open($dfh,">$dfilename")) {
299: print $dfh "$cmd\n";
300: close($dfh);
301: }
302: }
303: sleep 2;
304: my $wcmd='';
305: {
306: my $dfh;
307: if (open($dfh,"<$dfilename")) {
308: $wcmd=<$dfh>;
309: close($dfh);
310: }
311: }
312: chomp($wcmd);
313: if ($wcmd eq $cmd) {
314: &logthis("<font color=\"blue\">WARNING: ".
315: "Connection buffer $dfilename: $cmd</font>");
316: &logperm("D:$server:$cmd");
317: return 'con_delayed';
318: } else {
319: &logthis("<font color=\"red\">CRITICAL:"
320: ." Critical connection failed: $server $cmd</font>");
321: &logperm("F:$server:$cmd");
322: return 'con_failed';
323: }
324: }
325: }
326: return $answer;
327: }
328:
329: # ------------------------------------------- check if return value is an error
330:
331: sub error {
332: my ($result) = @_;
333: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
334: if ($2 == 2) { return undef; }
335: return $1;
336: }
337: return undef;
338: }
339:
340: sub convert_and_load_session_env {
341: my ($lonidsdir,$handle)=@_;
342: my @profile;
343: {
344: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
345: if (!$opened) {
346: return 0;
347: }
348: flock($idf,LOCK_SH);
349: @profile=<$idf>;
350: close($idf);
351: }
352: my %temp_env;
353: foreach my $line (@profile) {
354: if ($line !~ m/=/) {
355: return 0;
356: }
357: chomp($line);
358: my ($envname,$envvalue)=split(/=/,$line,2);
359: $temp_env{&unescape($envname)} = &unescape($envvalue);
360: }
361: unlink("$lonidsdir/$handle.id");
362: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
363: 0640)) {
364: %disk_env = %temp_env;
365: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
366: untie(%disk_env);
367: }
368: return 1;
369: }
370:
371: # ------------------------------------------- Transfer profile into environment
372: my $env_loaded;
373: sub transfer_profile_to_env {
374: my ($lonidsdir,$handle,$force_transfer) = @_;
375: if (!$force_transfer && $env_loaded) { return; }
376:
377: if (!defined($lonidsdir)) {
378: $lonidsdir = $perlvar{'lonIDsDir'};
379: }
380: if (!defined($handle)) {
381: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
382: }
383:
384: my $convert;
385: {
386: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
387: if (!$opened) {
388: return;
389: }
390: flock($idf,LOCK_SH);
391: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
392: &GDBM_READER(),0640)) {
393: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
394: untie(%disk_env);
395: } else {
396: $convert = 1;
397: }
398: }
399: if ($convert) {
400: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
401: &logthis("Failed to load session, or convert session.");
402: }
403: }
404:
405: my %remove;
406: while ( my $envname = each(%env) ) {
407: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
408: if ($time < time-300) {
409: $remove{$key}++;
410: }
411: }
412: }
413:
414: $env{'user.environment'} = "$lonidsdir/$handle.id";
415: $env_loaded=1;
416: foreach my $expired_key (keys(%remove)) {
417: &delenv($expired_key);
418: }
419: }
420:
421: # ---------------------------------------------------- Check for valid session
422: sub check_for_valid_session {
423: my ($r) = @_;
424: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
425: my $lonid=$cookies{'lonID'};
426: return undef if (!$lonid);
427:
428: my $handle=&LONCAPA::clean_handle($lonid->value);
429: my $lonidsdir=$r->dir_config('lonIDsDir');
430: return undef if (!-e "$lonidsdir/$handle.id");
431:
432: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
433: return undef if (!$opened);
434:
435: flock($idf,LOCK_SH);
436: my %disk_env;
437: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
438: &GDBM_READER(),0640)) {
439: return undef;
440: }
441:
442: if (!defined($disk_env{'user.name'})
443: || !defined($disk_env{'user.domain'})) {
444: return undef;
445: }
446: return $handle;
447: }
448:
449: sub timed_flock {
450: my ($file,$lock_type) = @_;
451: my $failed=0;
452: eval {
453: local $SIG{__DIE__}='DEFAULT';
454: local $SIG{ALRM}=sub {
455: $failed=1;
456: die("failed lock");
457: };
458: alarm(13);
459: flock($file,$lock_type);
460: alarm(0);
461: };
462: if ($failed) {
463: return undef;
464: } else {
465: return 1;
466: }
467: }
468:
469: # ---------------------------------------------------------- Append Environment
470:
471: sub appenv {
472: my ($newenv,$roles) = @_;
473: if (ref($newenv) eq 'HASH') {
474: foreach my $key (keys(%{$newenv})) {
475: my $refused = 0;
476: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
477: $refused = 1;
478: if (ref($roles) eq 'ARRAY') {
479: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
480: if (grep(/^\Q$role\E$/,@{$roles})) {
481: $refused = 0;
482: }
483: }
484: }
485: if ($refused) {
486: &logthis("<font color=\"blue\">WARNING: ".
487: "Attempt to modify environment ".$key." to ".$newenv->{$key}
488: .'</font>');
489: delete($newenv->{$key});
490: } else {
491: $env{$key}=$newenv->{$key};
492: }
493: }
494: my $opened = open(my $env_file,'+<',$env{'user.environment'});
495: if ($opened
496: && &timed_flock($env_file,LOCK_EX)
497: &&
498: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
499: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
500: while (my ($key,$value) = each(%{$newenv})) {
501: $disk_env{$key} = $value;
502: }
503: untie(%disk_env);
504: }
505: }
506: return 'ok';
507: }
508: # ----------------------------------------------------- Delete from Environment
509:
510: sub delenv {
511: my $delthis=shift;
512: if (($delthis=~/user\.role/) || ($delthis=~/user\.priv/)) {
513: &logthis("<font color=\"blue\">WARNING: ".
514: "Attempt to delete from environment ".$delthis);
515: return 'error';
516: }
517: my $opened = open(my $env_file,'+<',$env{'user.environment'});
518: if ($opened
519: && &timed_flock($env_file,LOCK_EX)
520: &&
521: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
522: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
523: foreach my $key (keys(%disk_env)) {
524: if ($key=~/^\Q$delthis\E/) {
525: delete($env{$key});
526: delete($disk_env{$key});
527: }
528: }
529: untie(%disk_env);
530: }
531: return 'ok';
532: }
533:
534: sub get_env_multiple {
535: my ($name) = @_;
536: my @values;
537: if (defined($env{$name})) {
538: # exists is it an array
539: if (ref($env{$name})) {
540: @values=@{ $env{$name} };
541: } else {
542: $values[0]=$env{$name};
543: }
544: }
545: return(@values);
546: }
547:
548: # ------------------------------------------------------------------- Locking
549:
550: sub set_lock {
551: my ($text)=@_;
552: $locknum++;
553: my $id=$$.'-'.$locknum;
554: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
555: 'session.lock.'.$id => $text});
556: return $id;
557: }
558:
559: sub get_locks {
560: my $num=0;
561: my %texts=();
562: foreach my $lock (split(/\,/,$env{'session.locks'})) {
563: if ($lock=~/\w/) {
564: $num++;
565: $texts{$lock}=$env{'session.lock.'.$lock};
566: }
567: }
568: return ($num,%texts);
569: }
570:
571: sub remove_lock {
572: my ($id)=@_;
573: my $newlocks='';
574: foreach my $lock (split(/\,/,$env{'session.locks'})) {
575: if (($lock=~/\w/) && ($lock ne $id)) {
576: $newlocks.=','.$lock;
577: }
578: }
579: &appenv({'session.locks' => $newlocks});
580: &delenv('session.lock.'.$id);
581: }
582:
583: sub remove_all_locks {
584: my $activelocks=$env{'session.locks'};
585: foreach my $lock (split(/\,/,$env{'session.locks'})) {
586: if ($lock=~/\w/) {
587: &remove_lock($lock);
588: }
589: }
590: }
591:
592:
593: # ------------------------------------------ Find out current server userload
594: sub userload {
595: my $numusers=0;
596: {
597: opendir(LONIDS,$perlvar{'lonIDsDir'});
598: my $filename;
599: my $curtime=time;
600: while ($filename=readdir(LONIDS)) {
601: next if ($filename eq '.' || $filename eq '..');
602: next if ($filename =~ /publicuser_\d+\.id/);
603: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
604: if ($curtime-$mtime < 1800) { $numusers++; }
605: }
606: closedir(LONIDS);
607: }
608: my $userloadpercent=0;
609: my $maxuserload=$perlvar{'lonUserLoadLim'};
610: if ($maxuserload) {
611: $userloadpercent=100*$numusers/$maxuserload;
612: }
613: $userloadpercent=sprintf("%.2f",$userloadpercent);
614: return $userloadpercent;
615: }
616:
617: # ------------------------------------------ Fight off request when overloaded
618:
619: sub overloaderror {
620: my ($r,$checkserver)=@_;
621: unless ($checkserver) { $checkserver=$perlvar{'lonHostID'}; }
622: my $loadavg;
623: if ($checkserver eq $perlvar{'lonHostID'}) {
624: open(my $loadfile,'/proc/loadavg');
625: $loadavg=<$loadfile>;
626: $loadavg =~ s/\s.*//g;
627: $loadavg = 100*$loadavg/$perlvar{'lonLoadLim'};
628: close($loadfile);
629: } else {
630: $loadavg=&reply('load',$checkserver);
631: }
632: my $overload=$loadavg-100;
633: if ($overload>0) {
634: $r->err_headers_out->{'Retry-After'}=$overload;
635: $r->log_error('Overload of '.$overload.' on '.$checkserver);
636: return 413;
637: }
638: return '';
639: }
640:
641: # ------------------------------ Find server with least workload from spare.tab
642:
643: sub spareserver {
644: my ($loadpercent,$userloadpercent,$want_server_name) = @_;
645: my $spare_server;
646: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
647: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
648: : $userloadpercent;
649:
650: foreach my $try_server (@{ $spareid{'primary'} }) {
651: ($spare_server, $lowest_load) =
652: &compare_server_load($try_server, $spare_server, $lowest_load);
653: }
654:
655: my $found_server = ($spare_server ne '' && $lowest_load < 100);
656:
657: if (!$found_server) {
658: foreach my $try_server (@{ $spareid{'default'} }) {
659: ($spare_server, $lowest_load) =
660: &compare_server_load($try_server, $spare_server, $lowest_load);
661: }
662: }
663:
664: if (!$want_server_name) {
665: my $protocol = 'http';
666: if ($protocol{$spare_server} eq 'https') {
667: $protocol = $protocol{$spare_server};
668: }
669: $spare_server = $protocol.'://'.&hostname($spare_server);
670: }
671: return $spare_server;
672: }
673:
674: sub compare_server_load {
675: my ($try_server, $spare_server, $lowest_load) = @_;
676:
677: my $loadans = &reply('load', $try_server);
678: my $userloadans = &reply('userload',$try_server);
679:
680: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
681: next; #didn't get a number from the server
682: }
683:
684: my $load;
685: if ($loadans =~ /\d/) {
686: if ($userloadans =~ /\d/) {
687: #both are numbers, pick the bigger one
688: $load = ($loadans > $userloadans) ? $loadans
689: : $userloadans;
690: } else {
691: $load = $loadans;
692: }
693: } else {
694: $load = $userloadans;
695: }
696:
697: if (($load =~ /\d/) && ($load < $lowest_load)) {
698: $spare_server = $try_server;
699: $lowest_load = $load;
700: }
701: return ($spare_server,$lowest_load);
702: }
703:
704: # --------------------------- ask offload servers if user already has a session
705: sub find_existing_session {
706: my ($udom,$uname) = @_;
707: foreach my $try_server (@{ $spareid{'primary'} },
708: @{ $spareid{'default'} }) {
709: return $try_server if (&has_user_session($try_server, $udom, $uname));
710: }
711: return;
712: }
713:
714: # -------------------------------- ask if server already has a session for user
715: sub has_user_session {
716: my ($lonid,$udom,$uname) = @_;
717: my $result = &reply(join(':','userhassession',
718: map {&escape($_)} ($udom,$uname)),$lonid);
719: return 1 if ($result eq 'ok');
720:
721: return 0;
722: }
723:
724: # --------------------------------------------- Try to change a user's password
725:
726: sub changepass {
727: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
728: $currentpass = &escape($currentpass);
729: $newpass = &escape($newpass);
730: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context",
731: $server);
732: if (! $answer) {
733: &logthis("No reply on password change request to $server ".
734: "by $uname in domain $udom.");
735: } elsif ($answer =~ "^ok") {
736: &logthis("$uname in $udom successfully changed their password ".
737: "on $server.");
738: } elsif ($answer =~ "^pwchange_failure") {
739: &logthis("$uname in $udom was unable to change their password ".
740: "on $server. The action was blocked by either lcpasswd ".
741: "or pwchange");
742: } elsif ($answer =~ "^non_authorized") {
743: &logthis("$uname in $udom did not get their password correct when ".
744: "attempting to change it on $server.");
745: } elsif ($answer =~ "^auth_mode_error") {
746: &logthis("$uname in $udom attempted to change their password despite ".
747: "not being locally or internally authenticated on $server.");
748: } elsif ($answer =~ "^unknown_user") {
749: &logthis("$uname in $udom attempted to change their password ".
750: "on $server but were unable to because $server is not ".
751: "their home server.");
752: } elsif ($answer =~ "^refused") {
753: &logthis("$server refused to change $uname in $udom password because ".
754: "it was sent an unencrypted request to change the password.");
755: }
756: return $answer;
757: }
758:
759: # ----------------------- Try to determine user's current authentication scheme
760:
761: sub queryauthenticate {
762: my ($uname,$udom)=@_;
763: my $uhome=&homeserver($uname,$udom);
764: if (!$uhome) {
765: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
766: return 'no_host';
767: }
768: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
769: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
770: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
771: }
772: return $answer;
773: }
774:
775: # --------- Try to authenticate user from domain's lib servers (first this one)
776:
777: sub authenticate {
778: my ($uname,$upass,$udom,$checkdefauth)=@_;
779: $upass=&escape($upass);
780: $uname= &LONCAPA::clean_username($uname);
781: my $uhome=&homeserver($uname,$udom,1);
782: my $newhome;
783: if ((!$uhome) || ($uhome eq 'no_host')) {
784: # Maybe the machine was offline and only re-appeared again recently?
785: &reconlonc();
786: # One more
787: $uhome=&homeserver($uname,$udom,1);
788: if (($uhome eq 'no_host') && $checkdefauth) {
789: if (defined(&domain($udom,'primary'))) {
790: $newhome=&domain($udom,'primary');
791: }
792: if ($newhome ne '') {
793: $uhome = $newhome;
794: }
795: }
796: if ((!$uhome) || ($uhome eq 'no_host')) {
797: &logthis("User $uname at $udom is unknown in authenticate");
798: return 'no_host';
799: }
800: }
801: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth",$uhome);
802: if ($answer eq 'authorized') {
803: if ($newhome) {
804: &logthis("User $uname at $udom authorized by $uhome, but needs account");
805: return 'no_account_on_host';
806: } else {
807: &logthis("User $uname at $udom authorized by $uhome");
808: return $uhome;
809: }
810: }
811: if ($answer eq 'non_authorized') {
812: &logthis("User $uname at $udom rejected by $uhome");
813: return 'no_host';
814: }
815: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
816: return 'no_host';
817: }
818:
819: # ---------------------- Find the homebase for a user from domain's lib servers
820:
821: my %homecache;
822: sub homeserver {
823: my ($uname,$udom,$ignoreBadCache)=@_;
824: my $index="$uname:$udom";
825:
826: if (exists($homecache{$index})) { return $homecache{$index}; }
827:
828: my %servers = &get_servers($udom,'library');
829: foreach my $tryserver (keys(%servers)) {
830: next if ($ignoreBadCache ne 'true' &&
831: exists($badServerCache{$tryserver}));
832:
833: my $answer=reply("home:$udom:$uname",$tryserver);
834: if ($answer eq 'found') {
835: delete($badServerCache{$tryserver});
836: return $homecache{$index}=$tryserver;
837: } elsif ($answer eq 'no_host') {
838: $badServerCache{$tryserver}=1;
839: }
840: }
841: return 'no_host';
842: }
843:
844: # ------------------------------------- Find the usernames behind a list of IDs
845:
846: sub idget {
847: my ($udom,@ids)=@_;
848: my %returnhash=();
849:
850: my %servers = &get_servers($udom,'library');
851: foreach my $tryserver (keys(%servers)) {
852: my $idlist=join('&',@ids);
853: $idlist=~tr/A-Z/a-z/;
854: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
855: my @answer=();
856: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
857: @answer=split(/\&/,$reply);
858: } ;
859: my $i;
860: for ($i=0;$i<=$#ids;$i++) {
861: if ($answer[$i]) {
862: $returnhash{$ids[$i]}=$answer[$i];
863: }
864: }
865: }
866: return %returnhash;
867: }
868:
869: # ------------------------------------- Find the IDs behind a list of usernames
870:
871: sub idrget {
872: my ($udom,@unames)=@_;
873: my %returnhash=();
874: foreach my $uname (@unames) {
875: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
876: }
877: return %returnhash;
878: }
879:
880: # ------------------------------- Store away a list of names and associated IDs
881:
882: sub idput {
883: my ($udom,%ids)=@_;
884: my %servers=();
885: foreach my $uname (keys(%ids)) {
886: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
887: my $uhom=&homeserver($uname,$udom);
888: if ($uhom ne 'no_host') {
889: my $id=&escape($ids{$uname});
890: $id=~tr/A-Z/a-z/;
891: my $esc_unam=&escape($uname);
892: if ($servers{$uhom}) {
893: $servers{$uhom}.='&'.$id.'='.$esc_unam;
894: } else {
895: $servers{$uhom}=$id.'='.$esc_unam;
896: }
897: }
898: }
899: foreach my $server (keys(%servers)) {
900: &critical('idput:'.$udom.':'.$servers{$server},$server);
901: }
902: }
903:
904: # ------------------------------------------- get items from domain db files
905:
906: sub get_dom {
907: my ($namespace,$storearr,$udom,$uhome)=@_;
908: my $items='';
909: foreach my $item (@$storearr) {
910: $items.=&escape($item).'&';
911: }
912: $items=~s/\&$//;
913: if (!$udom) {
914: $udom=$env{'user.domain'};
915: if (defined(&domain($udom,'primary'))) {
916: $uhome=&domain($udom,'primary');
917: } else {
918: undef($uhome);
919: }
920: } else {
921: if (!$uhome) {
922: if (defined(&domain($udom,'primary'))) {
923: $uhome=&domain($udom,'primary');
924: }
925: }
926: }
927: if ($udom && $uhome && ($uhome ne 'no_host')) {
928: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
929: my %returnhash;
930: if ($rep eq '' || $rep =~ /^error: 2 /) {
931: return %returnhash;
932: }
933: my @pairs=split(/\&/,$rep);
934: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
935: return @pairs;
936: }
937: my $i=0;
938: foreach my $item (@$storearr) {
939: $returnhash{$item}=&thaw_unescape($pairs[$i]);
940: $i++;
941: }
942: return %returnhash;
943: } else {
944: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
945: }
946: }
947:
948: # -------------------------------------------- put items in domain db files
949:
950: sub put_dom {
951: my ($namespace,$storehash,$udom,$uhome)=@_;
952: if (!$udom) {
953: $udom=$env{'user.domain'};
954: if (defined(&domain($udom,'primary'))) {
955: $uhome=&domain($udom,'primary');
956: } else {
957: undef($uhome);
958: }
959: } else {
960: if (!$uhome) {
961: if (defined(&domain($udom,'primary'))) {
962: $uhome=&domain($udom,'primary');
963: }
964: }
965: }
966: if ($udom && $uhome && ($uhome ne 'no_host')) {
967: my $items='';
968: foreach my $item (keys(%$storehash)) {
969: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
970: }
971: $items=~s/\&$//;
972: return &reply("putdom:$udom:$namespace:$items",$uhome);
973: } else {
974: &logthis("put_dom failed - no homeserver and/or domain");
975: }
976: }
977:
978: sub retrieve_inst_usertypes {
979: my ($udom) = @_;
980: my (%returnhash,@order);
981: if (defined(&domain($udom,'primary'))) {
982: my $uhome=&domain($udom,'primary');
983: my $rep=&reply("inst_usertypes:$udom",$uhome);
984: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
985: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
986: return (\%returnhash,\@order);
987: }
988: my ($hashitems,$orderitems) = split(/:/,$rep);
989: my @pairs=split(/\&/,$hashitems);
990: foreach my $item (@pairs) {
991: my ($key,$value)=split(/=/,$item,2);
992: $key = &unescape($key);
993: next if ($key =~ /^error: 2 /);
994: $returnhash{$key}=&thaw_unescape($value);
995: }
996: my @esc_order = split(/\&/,$orderitems);
997: foreach my $item (@esc_order) {
998: push(@order,&unescape($item));
999: }
1000: } else {
1001: &logthis("get_dom failed - no primary domain server for $udom");
1002: }
1003: return (\%returnhash,\@order);
1004: }
1005:
1006: sub is_domainimage {
1007: my ($url) = @_;
1008: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1009: if (&domain($1) ne '') {
1010: return '1';
1011: }
1012: }
1013: return;
1014: }
1015:
1016: sub inst_directory_query {
1017: my ($srch) = @_;
1018: my $udom = $srch->{'srchdomain'};
1019: my %results;
1020: my $homeserver = &domain($udom,'primary');
1021: my $outcome;
1022: if ($homeserver ne '') {
1023: my $queryid=&reply("querysend:instdirsearch:".
1024: &escape($srch->{'srchby'}).':'.
1025: &escape($srch->{'srchterm'}).':'.
1026: &escape($srch->{'srchtype'}),$homeserver);
1027: my $host=&hostname($homeserver);
1028: if ($queryid !~/^\Q$host\E\_/) {
1029: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1030: return;
1031: }
1032: my $response = &get_query_reply($queryid);
1033: my $maxtries = 5;
1034: my $tries = 1;
1035: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1036: $response = &get_query_reply($queryid);
1037: $tries ++;
1038: }
1039:
1040: if (!&error($response) && $response ne 'refused') {
1041: if ($response eq 'unavailable') {
1042: $outcome = $response;
1043: } else {
1044: $outcome = 'ok';
1045: my @matches = split(/\n/,$response);
1046: foreach my $match (@matches) {
1047: my ($key,$value) = split(/=/,$match);
1048: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1049: }
1050: }
1051: }
1052: }
1053: return ($outcome,%results);
1054: }
1055:
1056: sub usersearch {
1057: my ($srch) = @_;
1058: my $dom = $srch->{'srchdomain'};
1059: my %results;
1060: my %libserv = &all_library();
1061: my $query = 'usersearch';
1062: foreach my $tryserver (keys(%libserv)) {
1063: if (&host_domain($tryserver) eq $dom) {
1064: my $host=&hostname($tryserver);
1065: my $queryid=
1066: &reply("querysend:".&escape($query).':'.
1067: &escape($srch->{'srchby'}).':'.
1068: &escape($srch->{'srchtype'}).':'.
1069: &escape($srch->{'srchterm'}),$tryserver);
1070: if ($queryid !~/^\Q$host\E\_/) {
1071: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1072: next;
1073: }
1074: my $reply = &get_query_reply($queryid);
1075: my $maxtries = 1;
1076: my $tries = 1;
1077: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1078: $reply = &get_query_reply($queryid);
1079: $tries ++;
1080: }
1081: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1082: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1083: } else {
1084: my @matches;
1085: if ($reply =~ /\n/) {
1086: @matches = split(/\n/,$reply);
1087: } else {
1088: @matches = split(/\&/,$reply);
1089: }
1090: foreach my $match (@matches) {
1091: my ($uname,$udom,%userhash);
1092: foreach my $entry (split(/:/,$match)) {
1093: my ($key,$value) =
1094: map {&unescape($_);} split(/=/,$entry);
1095: $userhash{$key} = $value;
1096: if ($key eq 'username') {
1097: $uname = $value;
1098: } elsif ($key eq 'domain') {
1099: $udom = $value;
1100: }
1101: }
1102: $results{$uname.':'.$udom} = \%userhash;
1103: }
1104: }
1105: }
1106: }
1107: return %results;
1108: }
1109:
1110: sub get_instuser {
1111: my ($udom,$uname,$id) = @_;
1112: my $homeserver = &domain($udom,'primary');
1113: my ($outcome,%results);
1114: if ($homeserver ne '') {
1115: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1116: &escape($id).':'.&escape($udom),$homeserver);
1117: my $host=&hostname($homeserver);
1118: if ($queryid !~/^\Q$host\E\_/) {
1119: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1120: return;
1121: }
1122: my $response = &get_query_reply($queryid);
1123: my $maxtries = 5;
1124: my $tries = 1;
1125: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1126: $response = &get_query_reply($queryid);
1127: $tries ++;
1128: }
1129: if (!&error($response) && $response ne 'refused') {
1130: if ($response eq 'unavailable') {
1131: $outcome = $response;
1132: } else {
1133: $outcome = 'ok';
1134: my @matches = split(/\n/,$response);
1135: foreach my $match (@matches) {
1136: my ($key,$value) = split(/=/,$match);
1137: $results{&unescape($key)} = &thaw_unescape($value);
1138: }
1139: }
1140: }
1141: }
1142: my %userinfo;
1143: if (ref($results{$uname}) eq 'HASH') {
1144: %userinfo = %{$results{$uname}};
1145: }
1146: return ($outcome,%userinfo);
1147: }
1148:
1149: sub inst_rulecheck {
1150: my ($udom,$uname,$id,$item,$rules) = @_;
1151: my %returnhash;
1152: if ($udom ne '') {
1153: if (ref($rules) eq 'ARRAY') {
1154: @{$rules} = map {&escape($_);} (@{$rules});
1155: my $rulestr = join(':',@{$rules});
1156: my $homeserver=&domain($udom,'primary');
1157: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1158: my $response;
1159: if ($item eq 'username') {
1160: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1161: ':'.&escape($uname).':'.$rulestr,
1162: $homeserver));
1163: } elsif ($item eq 'id') {
1164: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1165: ':'.&escape($id).':'.$rulestr,
1166: $homeserver));
1167: } elsif ($item eq 'selfcreate') {
1168: $response=&unescape(&reply('instselfcreatecheck:'.
1169: &escape($udom).':'.&escape($uname).
1170: ':'.$rulestr,$homeserver));
1171: }
1172: if ($response ne 'refused') {
1173: my @pairs=split(/\&/,$response);
1174: foreach my $item (@pairs) {
1175: my ($key,$value)=split(/=/,$item,2);
1176: $key = &unescape($key);
1177: next if ($key =~ /^error: 2 /);
1178: $returnhash{$key}=&thaw_unescape($value);
1179: }
1180: }
1181: }
1182: }
1183: }
1184: return %returnhash;
1185: }
1186:
1187: sub inst_userrules {
1188: my ($udom,$check) = @_;
1189: my (%ruleshash,@ruleorder);
1190: if ($udom ne '') {
1191: my $homeserver=&domain($udom,'primary');
1192: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1193: my $response;
1194: if ($check eq 'id') {
1195: $response=&reply('instidrules:'.&escape($udom),
1196: $homeserver);
1197: } elsif ($check eq 'email') {
1198: $response=&reply('instemailrules:'.&escape($udom),
1199: $homeserver);
1200: } else {
1201: $response=&reply('instuserrules:'.&escape($udom),
1202: $homeserver);
1203: }
1204: if (($response ne 'refused') && ($response ne 'error') &&
1205: ($response ne 'unknown_cmd') &&
1206: ($response ne 'no_such_host')) {
1207: my ($hashitems,$orderitems) = split(/:/,$response);
1208: my @pairs=split(/\&/,$hashitems);
1209: foreach my $item (@pairs) {
1210: my ($key,$value)=split(/=/,$item,2);
1211: $key = &unescape($key);
1212: next if ($key =~ /^error: 2 /);
1213: $ruleshash{$key}=&thaw_unescape($value);
1214: }
1215: my @esc_order = split(/\&/,$orderitems);
1216: foreach my $item (@esc_order) {
1217: push(@ruleorder,&unescape($item));
1218: }
1219: }
1220: }
1221: }
1222: return (\%ruleshash,\@ruleorder);
1223: }
1224:
1225: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1226:
1227: sub get_domain_defaults {
1228: my ($domain) = @_;
1229: my $cachetime = 60*60*24;
1230: my ($defauthtype,$defautharg,$deflang,%deftools);
1231: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1232: if (defined($cached)) {
1233: if (ref($result) eq 'HASH') {
1234: return %{$result};
1235: }
1236: }
1237: my %domdefaults;
1238: my %domconfig =
1239: &Apache::lonnet::get_dom('configuration',['defaults','quotas'],$domain);
1240: if (ref($domconfig{'defaults'}) eq 'HASH') {
1241: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1242: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1243: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1244: } else {
1245: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1246: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1247: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1248: }
1249: if (ref($domconfig{'quotas'}) eq 'HASH') {
1250: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1251: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1252: } else {
1253: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1254: }
1255: my @usertools = ('aboutme','blog','portfolio');
1256: foreach my $item (@usertools) {
1257: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1258: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1259: }
1260: }
1261: }
1262: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1263: $cachetime);
1264: return %domdefaults;
1265: }
1266:
1267: # --------------------------------------------------- Assign a key to a student
1268:
1269: sub assign_access_key {
1270: #
1271: # a valid key looks like uname:udom#comments
1272: # comments are being appended
1273: #
1274: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1275: $kdom=
1276: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1277: $knum=
1278: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1279: $cdom=
1280: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1281: $cnum=
1282: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1283: $udom=$env{'user.name'} unless (defined($udom));
1284: $uname=$env{'user.domain'} unless (defined($uname));
1285: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1286: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1287: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1288: # assigned to this person
1289: # - this should not happen,
1290: # unless something went wrong
1291: # the first time around
1292: # ready to assign
1293: $logentry=$1.'; '.$logentry;
1294: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1295: $kdom,$knum) eq 'ok') {
1296: # key now belongs to user
1297: my $envkey='key.'.$cdom.'_'.$cnum;
1298: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1299: &appenv({'environment.'.$envkey => $ckey});
1300: return 'ok';
1301: } else {
1302: return
1303: 'error: Count not permanently assign key, will need to be re-entered later.';
1304: }
1305: } else {
1306: return 'error: Could not assign key, try again later.';
1307: }
1308: } elsif (!$existing{$ckey}) {
1309: # the key does not exist
1310: return 'error: The key does not exist';
1311: } else {
1312: # the key is somebody else's
1313: return 'error: The key is already in use';
1314: }
1315: }
1316:
1317: # ------------------------------------------ put an additional comment on a key
1318:
1319: sub comment_access_key {
1320: #
1321: # a valid key looks like uname:udom#comments
1322: # comments are being appended
1323: #
1324: my ($ckey,$cdom,$cnum,$logentry)=@_;
1325: $cdom=
1326: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1327: $cnum=
1328: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1329: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1330: if ($existing{$ckey}) {
1331: $existing{$ckey}.='; '.$logentry;
1332: # ready to assign
1333: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1334: $cdom,$cnum) eq 'ok') {
1335: return 'ok';
1336: } else {
1337: return 'error: Count not store comment.';
1338: }
1339: } else {
1340: # the key does not exist
1341: return 'error: The key does not exist';
1342: }
1343: }
1344:
1345: # ------------------------------------------------------ Generate a set of keys
1346:
1347: sub generate_access_keys {
1348: my ($number,$cdom,$cnum,$logentry)=@_;
1349: $cdom=
1350: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1351: $cnum=
1352: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1353: unless (&allowed('mky',$cdom)) { return 0; }
1354: unless (($cdom) && ($cnum)) { return 0; }
1355: if ($number>10000) { return 0; }
1356: sleep(2); # make sure don't get same seed twice
1357: srand(time()^($$+($$<<15))); # from "Programming Perl"
1358: my $total=0;
1359: for (my $i=1;$i<=$number;$i++) {
1360: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
1361: sprintf("%lx",int(100000*rand)).'-'.
1362: sprintf("%lx",int(100000*rand));
1363: $newkey=~s/1/g/g; # folks mix up 1 and l
1364: $newkey=~s/0/h/g; # and also 0 and O
1365: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
1366: if ($existing{$newkey}) {
1367: $i--;
1368: } else {
1369: if (&put('accesskeys',
1370: { $newkey => '# generated '.localtime().
1371: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1372: '; '.$logentry },
1373: $cdom,$cnum) eq 'ok') {
1374: $total++;
1375: }
1376: }
1377: }
1378: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1379: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
1380: return $total;
1381: }
1382:
1383: # ------------------------------------------------------- Validate an accesskey
1384:
1385: sub validate_access_key {
1386: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
1387: $cdom=
1388: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1389: $cnum=
1390: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1391: $udom=$env{'user.domain'} unless (defined($udom));
1392: $uname=$env{'user.name'} unless (defined($uname));
1393: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1394: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1395: }
1396:
1397: # ------------------------------------- Find the section of student in a course
1398: sub devalidate_getsection_cache {
1399: my ($udom,$unam,$courseid)=@_;
1400: my $hashid="$udom:$unam:$courseid";
1401: &devalidate_cache_new('getsection',$hashid);
1402: }
1403:
1404: sub courseid_to_courseurl {
1405: my ($courseid) = @_;
1406: #already url style courseid
1407: return $courseid if ($courseid =~ m{^/});
1408:
1409: if (exists($env{'course.'.$courseid.'.num'})) {
1410: my $cnum = $env{'course.'.$courseid.'.num'};
1411: my $cdom = $env{'course.'.$courseid.'.domain'};
1412: return "/$cdom/$cnum";
1413: }
1414:
1415: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
1416: if (exists($courseinfo{'num'})) {
1417: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
1418: }
1419:
1420: return undef;
1421: }
1422:
1423: sub getsection {
1424: my ($udom,$unam,$courseid)=@_;
1425: my $cachetime=1800;
1426:
1427: my $hashid="$udom:$unam:$courseid";
1428: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1429: if (defined($cached)) { return $result; }
1430:
1431: my %Pending;
1432: my %Expired;
1433: #
1434: # Each role can either have not started yet (pending), be active,
1435: # or have expired.
1436: #
1437: # If there is an active role, we are done.
1438: #
1439: # If there is more than one role which has not started yet,
1440: # choose the one which will start sooner
1441: # If there is one role which has not started yet, return it.
1442: #
1443: # If there is more than one expired role, choose the one which ended last.
1444: # If there is a role which has expired, return it.
1445: #
1446: $courseid = &courseid_to_courseurl($courseid);
1447: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1448: foreach my $key (keys(%roleshash)) {
1449: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1450: my $section=$1;
1451: if ($key eq $courseid.'_st') { $section=''; }
1452: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1453: my $now=time;
1454: if (defined($end) && $end && ($now > $end)) {
1455: $Expired{$end}=$section;
1456: next;
1457: }
1458: if (defined($start) && $start && ($now < $start)) {
1459: $Pending{$start}=$section;
1460: next;
1461: }
1462: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1463: }
1464: #
1465: # Presumedly there will be few matching roles from the above
1466: # loop and the sorting time will be negligible.
1467: if (scalar(keys(%Pending))) {
1468: my ($time) = sort {$a <=> $b} keys(%Pending);
1469: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1470: }
1471: if (scalar(keys(%Expired))) {
1472: my @sorted = sort {$a <=> $b} keys(%Expired);
1473: my $time = pop(@sorted);
1474: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1475: }
1476: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1477: }
1478:
1479: sub save_cache {
1480: &purge_remembered();
1481: #&Apache::loncommon::validate_page();
1482: undef(%env);
1483: undef($env_loaded);
1484: }
1485:
1486: my $to_remember=-1;
1487: my %remembered;
1488: my %accessed;
1489: my $kicks=0;
1490: my $hits=0;
1491: sub make_key {
1492: my ($name,$id) = @_;
1493: if (length($id) > 65
1494: && length(&escape($id)) > 200) {
1495: $id=length($id).':'.&Digest::MD5::md5_hex($id);
1496: }
1497: return &escape($name.':'.$id);
1498: }
1499:
1500: sub devalidate_cache_new {
1501: my ($name,$id,$debug) = @_;
1502: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1503: $id=&make_key($name,$id);
1504: $memcache->delete($id);
1505: delete($remembered{$id});
1506: delete($accessed{$id});
1507: }
1508:
1509: sub is_cached_new {
1510: my ($name,$id,$debug) = @_;
1511: $id=&make_key($name,$id);
1512: if (exists($remembered{$id})) {
1513: if ($debug) { &Apache::lonnet::logthis("Earyl return $id of $remembered{$id} "); }
1514: $accessed{$id}=[&gettimeofday()];
1515: $hits++;
1516: return ($remembered{$id},1);
1517: }
1518: my $value = $memcache->get($id);
1519: if (!(defined($value))) {
1520: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1521: return (undef,undef);
1522: }
1523: if ($value eq '__undef__') {
1524: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
1525: $value=undef;
1526: }
1527: &make_room($id,$value,$debug);
1528: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
1529: return ($value,1);
1530: }
1531:
1532: sub do_cache_new {
1533: my ($name,$id,$value,$time,$debug) = @_;
1534: $id=&make_key($name,$id);
1535: my $setvalue=$value;
1536: if (!defined($setvalue)) {
1537: $setvalue='__undef__';
1538: }
1539: if (!defined($time) ) {
1540: $time=600;
1541: }
1542: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1543: my $result = $memcache->set($id,$setvalue,$time);
1544: if (! $result) {
1545: &logthis("caching of id -> $id failed");
1546: $memcache->disconnect_all();
1547: }
1548: # need to make a copy of $value
1549: &make_room($id,$value,$debug);
1550: return $value;
1551: }
1552:
1553: sub make_room {
1554: my ($id,$value,$debug)=@_;
1555:
1556: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
1557: : $value;
1558: if ($to_remember<0) { return; }
1559: $accessed{$id}=[&gettimeofday()];
1560: if (scalar(keys(%remembered)) <= $to_remember) { return; }
1561: my $to_kick;
1562: my $max_time=0;
1563: foreach my $other (keys(%accessed)) {
1564: if (&tv_interval($accessed{$other}) > $max_time) {
1565: $to_kick=$other;
1566: $max_time=&tv_interval($accessed{$other});
1567: }
1568: }
1569: delete($remembered{$to_kick});
1570: delete($accessed{$to_kick});
1571: $kicks++;
1572: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1573: return;
1574: }
1575:
1576: sub purge_remembered {
1577: #&logthis("Tossing ".scalar(keys(%remembered)));
1578: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1579: undef(%remembered);
1580: undef(%accessed);
1581: }
1582: # ------------------------------------- Read an entry from a user's environment
1583:
1584: sub userenvironment {
1585: my ($udom,$unam,@what)=@_;
1586: my $items;
1587: foreach my $item (@what) {
1588: $items.=&escape($item).'&';
1589: }
1590: $items=~s/\&$//;
1591: my %returnhash=();
1592: my @answer=split(/\&/,
1593: &reply('get:'.$udom.':'.$unam.':environment:'.$items,
1594: &homeserver($unam,$udom)));
1595: my $i;
1596: for ($i=0;$i<=$#what;$i++) {
1597: $returnhash{$what[$i]}=&unescape($answer[$i]);
1598: }
1599: return %returnhash;
1600: }
1601:
1602: # ---------------------------------------------------------- Get a studentphoto
1603: sub studentphoto {
1604: my ($udom,$unam,$ext) = @_;
1605: my $home=&Apache::lonnet::homeserver($unam,$udom);
1606: if (defined($env{'request.course.id'})) {
1607: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1608: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
1609: return(&retrievestudentphoto($udom,$unam,$ext));
1610: } else {
1611: my ($result,$perm_reqd)=
1612: &Apache::lonnet::auto_photo_permission($unam,$udom);
1613: if ($result eq 'ok') {
1614: if (!($perm_reqd eq 'yes')) {
1615: return(&retrievestudentphoto($udom,$unam,$ext));
1616: }
1617: }
1618: }
1619: }
1620: } else {
1621: my ($result,$perm_reqd) =
1622: &Apache::lonnet::auto_photo_permission($unam,$udom);
1623: if ($result eq 'ok') {
1624: if (!($perm_reqd eq 'yes')) {
1625: return(&retrievestudentphoto($udom,$unam,$ext));
1626: }
1627: }
1628: }
1629: return '/adm/lonKaputt/lonlogo_broken.gif';
1630: }
1631:
1632: sub retrievestudentphoto {
1633: my ($udom,$unam,$ext,$type) = @_;
1634: my $home=&Apache::lonnet::homeserver($unam,$udom);
1635: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
1636: if ($ret eq 'ok') {
1637: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
1638: if ($type eq 'thumbnail') {
1639: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
1640: }
1641: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
1642: return $tokenurl;
1643: } else {
1644: if ($type eq 'thumbnail') {
1645: return '/adm/lonKaputt/genericstudent_tn.gif';
1646: } else {
1647: return '/adm/lonKaputt/lonlogo_broken.gif';
1648: }
1649: }
1650: }
1651:
1652: # -------------------------------------------------------------------- New chat
1653:
1654: sub chatsend {
1655: my ($newentry,$anon,$group)=@_;
1656: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
1657: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1658: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1659: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1660: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1661: &escape($newentry)).':'.$group,$chome);
1662: }
1663:
1664: # ------------------------------------------ Find current version of a resource
1665:
1666: sub getversion {
1667: my $fname=&clutter(shift);
1668: unless ($fname=~/^\/res\//) { return -1; }
1669: return ¤tversion(&filelocation('',$fname));
1670: }
1671:
1672: sub currentversion {
1673: my $fname=shift;
1674: my ($result,$cached)=&is_cached_new('resversion',$fname);
1675: if (defined($cached)) { return $result; }
1676: my $author=$fname;
1677: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1678: my ($udom,$uname)=split(/\//,$author);
1679: my $home=homeserver($uname,$udom);
1680: if ($home eq 'no_host') {
1681: return -1;
1682: }
1683: my $answer=reply("currentversion:$fname",$home);
1684: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1685: return -1;
1686: }
1687: return &do_cache_new('resversion',$fname,$answer,600);
1688: }
1689:
1690: # ----------------------------- Subscribe to a resource, return URL if possible
1691:
1692: sub subscribe {
1693: my $fname=shift;
1694: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1695: $fname=~s/[\n\r]//g;
1696: my $author=$fname;
1697: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1698: my ($udom,$uname)=split(/\//,$author);
1699: my $home=homeserver($uname,$udom);
1700: if ($home eq 'no_host') {
1701: return 'not_found';
1702: }
1703: my $answer=reply("sub:$fname",$home);
1704: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
1705: $answer.=' by '.$home;
1706: }
1707: return $answer;
1708: }
1709:
1710: # -------------------------------------------------------------- Replicate file
1711:
1712: sub repcopy {
1713: my $filename=shift;
1714: $filename=~s/\/+/\//g;
1715: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
1716: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1717: if ($filename=~m|^/home/httpd/html/userfiles/| or
1718: $filename=~m -^/*(uploaded|editupload)/-) {
1719: return &repcopy_userfile($filename);
1720: }
1721: $filename=~s/[\n\r]//g;
1722: my $transname="$filename.in.transfer";
1723: # FIXME: this should flock
1724: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1725: my $remoteurl=subscribe($filename);
1726: if ($remoteurl =~ /^con_lost by/) {
1727: &logthis("Subscribe returned $remoteurl: $filename");
1728: return 'unavailable';
1729: } elsif ($remoteurl eq 'not_found') {
1730: #&logthis("Subscribe returned not_found: $filename");
1731: return 'not_found';
1732: } elsif ($remoteurl =~ /^rejected by/) {
1733: &logthis("Subscribe returned $remoteurl: $filename");
1734: return 'forbidden';
1735: } elsif ($remoteurl eq 'directory') {
1736: return 'ok';
1737: } else {
1738: my $author=$filename;
1739: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
1740: my ($udom,$uname)=split(/\//,$author);
1741: my $home=homeserver($uname,$udom);
1742: unless ($home eq $perlvar{'lonHostID'}) {
1743: my @parts=split(/\//,$filename);
1744: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1745: if ($path ne "$perlvar{'lonDocRoot'}/res") {
1746: &logthis("Malconfiguration for replication: $filename");
1747: return 'bad_request';
1748: }
1749: my $count;
1750: for ($count=5;$count<$#parts;$count++) {
1751: $path.="/$parts[$count]";
1752: if ((-e $path)!=1) {
1753: mkdir($path,0777);
1754: }
1755: }
1756: my $ua=new LWP::UserAgent;
1757: my $request=new HTTP::Request('GET',"$remoteurl");
1758: my $response=$ua->request($request,$transname);
1759: if ($response->is_error()) {
1760: unlink($transname);
1761: my $message=$response->status_line;
1762: &logthis("<font color=\"blue\">WARNING:"
1763: ." LWP get: $message: $filename</font>");
1764: return 'unavailable';
1765: } else {
1766: if ($remoteurl!~/\.meta$/) {
1767: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
1768: my $mresponse=$ua->request($mrequest,$filename.'.meta');
1769: if ($mresponse->is_error()) {
1770: unlink($filename.'.meta');
1771: &logthis(
1772: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1773: }
1774: }
1775: rename($transname,$filename);
1776: return 'ok';
1777: }
1778: }
1779: }
1780: }
1781:
1782: # ------------------------------------------------ Get server side include body
1783: sub ssi_body {
1784: my ($filelink,%form)=@_;
1785: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
1786: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
1787: }
1788: my $output='';
1789: my $response;
1790: if ($filelink=~/^https?\:/) {
1791: ($output,$response)=&externalssi($filelink);
1792: } else {
1793: ($output,$response)=&ssi($filelink,%form);
1794: }
1795: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1796: $output=~s/^.*?\<body[^\>]*\>//si;
1797: $output=~s/\<\/body\s*\>.*?$//si;
1798: if (wantarray) {
1799: return ($output, $response);
1800: } else {
1801: return $output;
1802: }
1803: }
1804:
1805: # --------------------------------------------------------- Server Side Include
1806:
1807: sub absolute_url {
1808: my ($host_name) = @_;
1809: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
1810: if ($host_name eq '') {
1811: $host_name = $ENV{'SERVER_NAME'};
1812: }
1813: return $protocol.$host_name;
1814: }
1815:
1816: #
1817: # Server side include.
1818: # Parameters:
1819: # fn Possibly encrypted resource name/id.
1820: # form Hash that describes how the rendering should be done
1821: # and other things.
1822: # Returns:
1823: # Scalar context: The content of the response.
1824: # Array context: 2 element list of the content and the full response object.
1825: #
1826: sub ssi {
1827:
1828: my ($fn,%form)=@_;
1829: my $ua=new LWP::UserAgent;
1830: my $request;
1831:
1832: $form{'no_update_last_known'}=1;
1833: &Apache::lonenc::check_encrypt(\$fn);
1834: if (%form) {
1835: $request=new HTTP::Request('POST',&absolute_url().$fn);
1836: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys %form));
1837: } else {
1838: $request=new HTTP::Request('GET',&absolute_url().$fn);
1839: }
1840:
1841: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1842: my $response=$ua->request($request);
1843:
1844: if (wantarray) {
1845: return ($response->content, $response);
1846: } else {
1847: return $response->content;
1848: }
1849: }
1850:
1851: sub externalssi {
1852: my ($url)=@_;
1853: my $ua=new LWP::UserAgent;
1854: my $request=new HTTP::Request('GET',$url);
1855: my $response=$ua->request($request);
1856: if (wantarray) {
1857: return ($response->content, $response);
1858: } else {
1859: return $response->content;
1860: }
1861: }
1862:
1863: # -------------------------------- Allow a /uploaded/ URI to be vouched for
1864:
1865: sub allowuploaded {
1866: my ($srcurl,$url)=@_;
1867: $url=&clutter(&declutter($url));
1868: my $dir=$url;
1869: $dir=~s/\/[^\/]+$//;
1870: my %httpref=();
1871: my $httpurl=&hreflocation('',$url);
1872: $httpref{'httpref.'.$httpurl}=$srcurl;
1873: &Apache::lonnet::appenv(\%httpref);
1874: }
1875:
1876: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1877: # input: action, courseID, current domain, intended
1878: # path to file, source of file, instruction to parse file for objects,
1879: # ref to hash for embedded objects,
1880: # ref to hash for codebase of java objects.
1881: #
1882: # output: url to file (if action was uploaddoc),
1883: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1884: #
1885: # Allows directory structure to be used within lonUsers/../userfiles/ for a
1886: # course.
1887: #
1888: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1889: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
1890: # course's home server.
1891: #
1892: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
1893: # be copied from $source (current location) to
1894: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1895: # and will then be copied to
1896: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
1897: # course's home server.
1898: #
1899: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1900: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1901: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1902: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
1903: # in course's home server.
1904: #
1905:
1906: sub process_coursefile {
1907: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase)=@_;
1908: my $fetchresult;
1909: my $home=&homeserver($docuname,$docudom);
1910: if ($action eq 'propagate') {
1911: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1912: $home);
1913: } else {
1914: my $fpath = '';
1915: my $fname = $file;
1916: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1917: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1918: my $filepath = &build_filepath($fpath);
1919: if ($action eq 'copy') {
1920: if ($source eq '') {
1921: $fetchresult = 'no source file';
1922: return $fetchresult;
1923: } else {
1924: my $destination = $filepath.'/'.$fname;
1925: rename($source,$destination);
1926: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1927: $home);
1928: }
1929: } elsif ($action eq 'uploaddoc') {
1930: open(my $fh,'>'.$filepath.'/'.$fname);
1931: print $fh $env{'form.'.$source};
1932: close($fh);
1933: if ($parser eq 'parse') {
1934: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
1935: unless ($parse_result eq 'ok') {
1936: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
1937: }
1938: }
1939: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1940: $home);
1941: if ($fetchresult eq 'ok') {
1942: return '/uploaded/'.$fpath.'/'.$fname;
1943: } else {
1944: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1945: ' to host '.$home.': '.$fetchresult);
1946: return '/adm/notfound.html';
1947: }
1948: }
1949: }
1950: unless ( $fetchresult eq 'ok') {
1951: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1952: ' to host '.$home.': '.$fetchresult);
1953: }
1954: return $fetchresult;
1955: }
1956:
1957: sub build_filepath {
1958: my ($fpath) = @_;
1959: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
1960: unless ($fpath eq '') {
1961: my @parts=split('/',$fpath);
1962: foreach my $part (@parts) {
1963: $filepath.= '/'.$part;
1964: if ((-e $filepath)!=1) {
1965: mkdir($filepath,0777);
1966: }
1967: }
1968: }
1969: return $filepath;
1970: }
1971:
1972: sub store_edited_file {
1973: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1974: my $file = $primary_url;
1975: $file =~ s#^/uploaded/$docudom/$docuname/##;
1976: my $fpath = '';
1977: my $fname = $file;
1978: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1979: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1980: my $filepath = &build_filepath($fpath);
1981: open(my $fh,'>'.$filepath.'/'.$fname);
1982: print $fh $content;
1983: close($fh);
1984: my $home=&homeserver($docuname,$docudom);
1985: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1986: $home);
1987: if ($$fetchresult eq 'ok') {
1988: return '/uploaded/'.$fpath.'/'.$fname;
1989: } else {
1990: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1991: ' to host '.$home.': '.$$fetchresult);
1992: return '/adm/notfound.html';
1993: }
1994: }
1995:
1996: sub clean_filename {
1997: my ($fname,$args)=@_;
1998: # Replace Windows backslashes by forward slashes
1999: $fname=~s/\\/\//g;
2000: if (!$args->{'keep_path'}) {
2001: # Get rid of everything but the actual filename
2002: $fname=~s/^.*\/([^\/]+)$/$1/;
2003: }
2004: # Replace spaces by underscores
2005: $fname=~s/\s+/\_/g;
2006: # Replace all other weird characters by nothing
2007: $fname=~s{[^/\w\.\-]}{}g;
2008: # Replace all .\d. sequences with _\d. so they no longer look like version
2009: # numbers
2010: $fname=~s/\.(\d+)(?=\.)/_$1/g;
2011: return $fname;
2012: }
2013:
2014: # --------------- Take an uploaded file and put it into the userfiles directory
2015: # input: $formname - the contents of the file are in $env{"form.$formname"}
2016: # the desired filenam is in $env{"form.$formname.filename"}
2017: # $coursedoc - if true up to the current course
2018: # if false
2019: # $subdir - directory in userfile to store the file into
2020: # $parser - instruction to parse file for objects ($parser = parse)
2021: # $allfiles - reference to hash for embedded objects
2022: # $codebase - reference to hash for codebase of java objects
2023: # $desuname - username for permanent storage of uploaded file
2024: # $dsetudom - domain for permanaent storage of uploaded file
2025: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2026: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
2027: #
2028: # output: url of file in userspace, or error: <message>
2029: # or /adm/notfound.html if failure to upload occurse
2030:
2031:
2032: sub userfileupload {
2033: my ($formname,$coursedoc,$subdir,$parser,$allfiles,$codebase,$destuname,
2034: $destudom,$thumbwidth,$thumbheight)=@_;
2035: if (!defined($subdir)) { $subdir='unknown'; }
2036: my $fname=$env{'form.'.$formname.'.filename'};
2037: $fname=&clean_filename($fname);
2038: # See if there is anything left
2039: unless ($fname) { return 'error: no uploaded file'; }
2040: chop($env{'form.'.$formname});
2041: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) { #files uploaded to help request form are handled differently
2042: my $now = time;
2043: my $filepath = 'tmp/helprequests/'.$now;
2044: my @parts=split(/\//,$filepath);
2045: my $fullpath = $perlvar{'lonDaemons'};
2046: for (my $i=0;$i<@parts;$i++) {
2047: $fullpath .= '/'.$parts[$i];
2048: if ((-e $fullpath)!=1) {
2049: mkdir($fullpath,0777);
2050: }
2051: }
2052: open(my $fh,'>'.$fullpath.'/'.$fname);
2053: print $fh $env{'form.'.$formname};
2054: close($fh);
2055: return $fullpath.'/'.$fname;
2056: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) { #files uploaded to create course page are handled differently
2057: my $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2058: '_'.$env{'user.domain'}.'/pending';
2059: my @parts=split(/\//,$filepath);
2060: my $fullpath = $perlvar{'lonDaemons'};
2061: for (my $i=0;$i<@parts;$i++) {
2062: $fullpath .= '/'.$parts[$i];
2063: if ((-e $fullpath)!=1) {
2064: mkdir($fullpath,0777);
2065: }
2066: }
2067: open(my $fh,'>'.$fullpath.'/'.$fname);
2068: print $fh $env{'form.'.$formname};
2069: close($fh);
2070: return $fullpath.'/'.$fname;
2071: }
2072:
2073: # Create the directory if not present
2074: $fname="$subdir/$fname";
2075: if ($coursedoc) {
2076: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2077: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2078: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
2079: return &finishuserfileupload($docuname,$docudom,
2080: $formname,$fname,$parser,$allfiles,
2081: $codebase,$thumbwidth,$thumbheight);
2082: } else {
2083: $fname=$env{'form.folder'}.'/'.$fname;
2084: return &process_coursefile('uploaddoc',$docuname,$docudom,
2085: $fname,$formname,$parser,
2086: $allfiles,$codebase);
2087: }
2088: } elsif (defined($destuname)) {
2089: my $docuname=$destuname;
2090: my $docudom=$destudom;
2091: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2092: $parser,$allfiles,$codebase,
2093: $thumbwidth,$thumbheight);
2094:
2095: } else {
2096: my $docuname=$env{'user.name'};
2097: my $docudom=$env{'user.domain'};
2098: if (exists($env{'form.group'})) {
2099: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2100: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2101: }
2102: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2103: $parser,$allfiles,$codebase,
2104: $thumbwidth,$thumbheight);
2105: }
2106: }
2107:
2108: sub finishuserfileupload {
2109: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
2110: $thumbwidth,$thumbheight) = @_;
2111: my $path=$docudom.'/'.$docuname.'/';
2112: my $filepath=$perlvar{'lonDocRoot'};
2113: my ($fnamepath,$file,$fetchthumb);
2114: $file=$fname;
2115: if ($fname=~m|/|) {
2116: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2117: $path.=$fnamepath.'/';
2118: }
2119: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
2120: my $count;
2121: for ($count=4;$count<=$#parts;$count++) {
2122: $filepath.="/$parts[$count]";
2123: if ((-e $filepath)!=1) {
2124: mkdir($filepath,0777);
2125: }
2126: }
2127: # Save the file
2128: {
2129: if (!open(FH,'>'.$filepath.'/'.$file)) {
2130: &logthis('Failed to create '.$filepath.'/'.$file);
2131: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2132: return '/adm/notfound.html';
2133: }
2134: if (!print FH ($env{'form.'.$formname})) {
2135: &logthis('Failed to write to '.$filepath.'/'.$file);
2136: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2137: return '/adm/notfound.html';
2138: }
2139: close(FH);
2140: }
2141: if ($parser eq 'parse') {
2142: my $parse_result = &extract_embedded_items($filepath.'/'.$file,$allfiles,
2143: $codebase);
2144: unless ($parse_result eq 'ok') {
2145: &logthis('Failed to parse '.$filepath.$file.
2146: ' for embedded media: '.$parse_result);
2147: }
2148: }
2149: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2150: my $input = $filepath.'/'.$file;
2151: my $output = $filepath.'/'.'tn-'.$file;
2152: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2153: system("convert -sample $thumbsize $input $output");
2154: if (-e $filepath.'/'.'tn-'.$file) {
2155: $fetchthumb = 1;
2156: }
2157: }
2158:
2159: # Notify homeserver to grep it
2160: #
2161: my $docuhome=&homeserver($docuname,$docudom);
2162: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
2163: if ($fetchresult eq 'ok') {
2164: if ($fetchthumb) {
2165: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
2166: if ($thumbresult ne 'ok') {
2167: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
2168: $docuhome.': '.$thumbresult);
2169: }
2170: }
2171: #
2172: # Return the URL to it
2173: return '/uploaded/'.$path.$file;
2174: } else {
2175: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
2176: ': '.$fetchresult);
2177: return '/adm/notfound.html';
2178: }
2179: }
2180:
2181: sub extract_embedded_items {
2182: my ($fullpath,$allfiles,$codebase,$content) = @_;
2183: my @state = ();
2184: my %javafiles = (
2185: codebase => '',
2186: code => '',
2187: archive => ''
2188: );
2189: my %mediafiles = (
2190: src => '',
2191: movie => '',
2192: );
2193: my $p;
2194: if ($content) {
2195: $p = HTML::LCParser->new($content);
2196: } else {
2197: $p = HTML::LCParser->new($fullpath);
2198: }
2199: while (my $t=$p->get_token()) {
2200: if ($t->[0] eq 'S') {
2201: my ($tagname, $attr) = ($t->[1],$t->[2]);
2202: push(@state, $tagname);
2203: if (lc($tagname) eq 'allow') {
2204: &add_filetype($allfiles,$attr->{'src'},'src');
2205: }
2206: if (lc($tagname) eq 'img') {
2207: &add_filetype($allfiles,$attr->{'src'},'src');
2208: }
2209: if (lc($tagname) eq 'a') {
2210: &add_filetype($allfiles,$attr->{'href'},'href');
2211: }
2212: if (lc($tagname) eq 'script') {
2213: if ($attr->{'archive'} =~ /\.jar$/i) {
2214: &add_filetype($allfiles,$attr->{'archive'},'archive');
2215: } else {
2216: &add_filetype($allfiles,$attr->{'src'},'src');
2217: }
2218: }
2219: if (lc($tagname) eq 'link') {
2220: if (lc($attr->{'rel'}) eq 'stylesheet') {
2221: &add_filetype($allfiles,$attr->{'href'},'href');
2222: }
2223: }
2224: if (lc($tagname) eq 'object' ||
2225: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
2226: foreach my $item (keys(%javafiles)) {
2227: $javafiles{$item} = '';
2228: }
2229: }
2230: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
2231: my $name = lc($attr->{'name'});
2232: foreach my $item (keys(%javafiles)) {
2233: if ($name eq $item) {
2234: $javafiles{$item} = $attr->{'value'};
2235: last;
2236: }
2237: }
2238: foreach my $item (keys(%mediafiles)) {
2239: if ($name eq $item) {
2240: &add_filetype($allfiles, $attr->{'value'}, 'value');
2241: last;
2242: }
2243: }
2244: }
2245: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
2246: foreach my $item (keys(%javafiles)) {
2247: if ($attr->{$item}) {
2248: $javafiles{$item} = $attr->{$item};
2249: last;
2250: }
2251: }
2252: foreach my $item (keys(%mediafiles)) {
2253: if ($attr->{$item}) {
2254: &add_filetype($allfiles,$attr->{$item},$item);
2255: last;
2256: }
2257: }
2258: }
2259: } elsif ($t->[0] eq 'E') {
2260: my ($tagname) = ($t->[1]);
2261: if ($javafiles{'codebase'} ne '') {
2262: $javafiles{'codebase'} .= '/';
2263: }
2264: if (lc($tagname) eq 'applet' ||
2265: lc($tagname) eq 'object' ||
2266: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
2267: ) {
2268: foreach my $item (keys(%javafiles)) {
2269: if ($item ne 'codebase' && $javafiles{$item} ne '') {
2270: my $file=$javafiles{'codebase'}.$javafiles{$item};
2271: &add_filetype($allfiles,$file,$item);
2272: }
2273: }
2274: }
2275: pop @state;
2276: }
2277: }
2278: return 'ok';
2279: }
2280:
2281: sub add_filetype {
2282: my ($allfiles,$file,$type)=@_;
2283: if (exists($allfiles->{$file})) {
2284: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
2285: push(@{$allfiles->{$file}}, &escape($type));
2286: }
2287: } else {
2288: @{$allfiles->{$file}} = (&escape($type));
2289: }
2290: }
2291:
2292: sub removeuploadedurl {
2293: my ($url)=@_;
2294: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
2295: return &removeuserfile($uname,$udom,$fname);
2296: }
2297:
2298: sub removeuserfile {
2299: my ($docuname,$docudom,$fname)=@_;
2300: my $home=&homeserver($docuname,$docudom);
2301: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
2302: if ($result eq 'ok') {
2303: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
2304: my $metafile = $fname.'.meta';
2305: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
2306: my $url = "/uploaded/$docudom/$docuname/$fname";
2307: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2308: my $sqlresult =
2309: &update_portfolio_table($docuname,$docudom,$file,
2310: 'portfolio_metadata',$group,
2311: 'delete');
2312: }
2313: }
2314: return $result;
2315: }
2316:
2317: sub mkdiruserfile {
2318: my ($docuname,$docudom,$dir)=@_;
2319: my $home=&homeserver($docuname,$docudom);
2320: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
2321: }
2322:
2323: sub renameuserfile {
2324: my ($docuname,$docudom,$old,$new)=@_;
2325: my $home=&homeserver($docuname,$docudom);
2326: my $result = &reply("renameuserfile:$docudom:$docuname:".
2327: &escape("$old").':'.&escape("$new"),$home);
2328: if ($result eq 'ok') {
2329: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
2330: my $oldmeta = $old.'.meta';
2331: my $newmeta = $new.'.meta';
2332: my $metaresult =
2333: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
2334: my $url = "/uploaded/$docudom/$docuname/$old";
2335: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
2336: my $sqlresult =
2337: &update_portfolio_table($docuname,$docudom,$file,
2338: 'portfolio_metadata',$group,
2339: 'delete');
2340: }
2341: }
2342: return $result;
2343: }
2344:
2345: # ------------------------------------------------------------------------- Log
2346:
2347: sub log {
2348: my ($dom,$nam,$hom,$what)=@_;
2349: return critical("log:$dom:$nam:$what",$hom);
2350: }
2351:
2352: # ------------------------------------------------------------------ Course Log
2353: #
2354: # This routine flushes several buffers of non-mission-critical nature
2355: #
2356:
2357: sub flushcourselogs {
2358: &logthis('Flushing log buffers');
2359: #
2360: # course logs
2361: # This is a log of all transactions in a course, which can be used
2362: # for data mining purposes
2363: #
2364: # It also collects the courseid database, which lists last transaction
2365: # times and course titles for all courseids
2366: #
2367: my %courseidbuffer=();
2368: foreach my $crsid (keys(%courselogs)) {
2369: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
2370: &escape($courselogs{$crsid}),
2371: $coursehombuf{$crsid}) eq 'ok') {
2372: delete $courselogs{$crsid};
2373: } else {
2374: &logthis('Failed to flush log buffer for '.$crsid);
2375: if (length($courselogs{$crsid})>40000) {
2376: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
2377: " exceeded maximum size, deleting.</font>");
2378: delete $courselogs{$crsid};
2379: }
2380: }
2381: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
2382: 'description' => $coursedescrbuf{$crsid},
2383: 'inst_code' => $courseinstcodebuf{$crsid},
2384: 'type' => $coursetypebuf{$crsid},
2385: 'owner' => $courseownerbuf{$crsid},
2386: };
2387: }
2388: #
2389: # Write course id database (reverse lookup) to homeserver of courses
2390: # Is used in pickcourse
2391: #
2392: foreach my $crs_home (keys(%courseidbuffer)) {
2393: my $response = &courseidput(&host_domain($crs_home),
2394: $courseidbuffer{$crs_home},
2395: $crs_home,'timeonly');
2396: }
2397: #
2398: # File accesses
2399: # Writes to the dynamic metadata of resources to get hit counts, etc.
2400: #
2401: foreach my $entry (keys(%accesshash)) {
2402: if ($entry =~ /___count$/) {
2403: my ($dom,$name);
2404: ($dom,$name,undef)=
2405: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
2406: if (! defined($dom) || $dom eq '' ||
2407: ! defined($name) || $name eq '') {
2408: my $cid = $env{'request.course.id'};
2409: $dom = $env{'request.'.$cid.'.domain'};
2410: $name = $env{'request.'.$cid.'.num'};
2411: }
2412: my $value = $accesshash{$entry};
2413: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
2414: my %temphash=($url => $value);
2415: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
2416: if ($result eq 'ok') {
2417: delete $accesshash{$entry};
2418: } elsif ($result eq 'unknown_cmd') {
2419: # Target server has old code running on it.
2420: my %temphash=($entry => $value);
2421: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2422: delete $accesshash{$entry};
2423: }
2424: }
2425: } else {
2426: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
2427: my %temphash=($entry => $accesshash{$entry});
2428: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
2429: delete $accesshash{$entry};
2430: }
2431: }
2432: }
2433: #
2434: # Roles
2435: # Reverse lookup of user roles for course faculty/staff and co-authorship
2436: #
2437: foreach my $entry (keys(%userrolehash)) {
2438: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
2439: split(/\:/,$entry);
2440: if (&Apache::lonnet::put('nohist_userroles',
2441: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
2442: $rudom,$runame) eq 'ok') {
2443: delete $userrolehash{$entry};
2444: }
2445: }
2446: #
2447: # Reverse lookup of domain roles (dc, ad, li, sc, au)
2448: #
2449: my %domrolebuffer = ();
2450: foreach my $entry (keys %domainrolehash) {
2451: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
2452: if ($domrolebuffer{$rudom}) {
2453: $domrolebuffer{$rudom}.='&'.&escape($entry).
2454: '='.&escape($domainrolehash{$entry});
2455: } else {
2456: $domrolebuffer{$rudom}.=&escape($entry).
2457: '='.&escape($domainrolehash{$entry});
2458: }
2459: delete $domainrolehash{$entry};
2460: }
2461: foreach my $dom (keys(%domrolebuffer)) {
2462: my %servers = &get_servers($dom,'library');
2463: foreach my $tryserver (keys(%servers)) {
2464: unless (&reply('domroleput:'.$dom.':'.
2465: $domrolebuffer{$dom},$tryserver) eq 'ok') {
2466: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
2467: }
2468: }
2469: }
2470: $dumpcount++;
2471: }
2472:
2473: sub courselog {
2474: my $what=shift;
2475: $what=time.':'.$what;
2476: unless ($env{'request.course.id'}) { return ''; }
2477: $coursedombuf{$env{'request.course.id'}}=
2478: $env{'course.'.$env{'request.course.id'}.'.domain'};
2479: $coursenumbuf{$env{'request.course.id'}}=
2480: $env{'course.'.$env{'request.course.id'}.'.num'};
2481: $coursehombuf{$env{'request.course.id'}}=
2482: $env{'course.'.$env{'request.course.id'}.'.home'};
2483: $coursedescrbuf{$env{'request.course.id'}}=
2484: $env{'course.'.$env{'request.course.id'}.'.description'};
2485: $courseinstcodebuf{$env{'request.course.id'}}=
2486: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
2487: $courseownerbuf{$env{'request.course.id'}}=
2488: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
2489: $coursetypebuf{$env{'request.course.id'}}=
2490: $env{'course.'.$env{'request.course.id'}.'.type'};
2491: if (defined $courselogs{$env{'request.course.id'}}) {
2492: $courselogs{$env{'request.course.id'}}.='&'.$what;
2493: } else {
2494: $courselogs{$env{'request.course.id'}}.=$what;
2495: }
2496: if (length($courselogs{$env{'request.course.id'}})>4048) {
2497: &flushcourselogs();
2498: }
2499: }
2500:
2501: sub courseacclog {
2502: my $fnsymb=shift;
2503: unless ($env{'request.course.id'}) { return ''; }
2504: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
2505: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
2506: $what.=':POST';
2507: # FIXME: Probably ought to escape things....
2508: foreach my $key (keys(%env)) {
2509: if ($key=~/^form\.(.*)/) {
2510: my $formitem = $1;
2511: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
2512: $what.=':'.$formitem.'='.$env{$key};
2513: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
2514: $what.=':'.$formitem.'='.$env{$key};
2515: }
2516: }
2517: }
2518: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
2519: # FIXME: We should not be depending on a form parameter that someone
2520: # editing lonsearchcat.pm might change in the future.
2521: if ($env{'form.phase'} eq 'course_search') {
2522: $what.= ':POST';
2523: # FIXME: Probably ought to escape things....
2524: foreach my $element ('courseexp','crsfulltext','crsrelated',
2525: 'crsdiscuss') {
2526: $what.=':'.$element.'='.$env{'form.'.$element};
2527: }
2528: }
2529: }
2530: &courselog($what);
2531: }
2532:
2533: sub countacc {
2534: my $url=&declutter(shift);
2535: return if (! defined($url) || $url eq '');
2536: unless ($env{'request.course.id'}) { return ''; }
2537: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
2538: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
2539: $accesshash{$key}++;
2540: }
2541:
2542: sub linklog {
2543: my ($from,$to)=@_;
2544: $from=&declutter($from);
2545: $to=&declutter($to);
2546: $accesshash{$from.'___'.$to.'___comefrom'}=1;
2547: $accesshash{$to.'___'.$from.'___goto'}=1;
2548: }
2549:
2550: sub userrolelog {
2551: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
2552: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
2553: ($trole=~/^in/) || ($trole=~/^cc/) ||
2554: ($trole=~/^ep/) || ($trole=~/^cr/) ||
2555: ($trole=~/^ta/)) {
2556: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2557: $userrolehash
2558: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2559: =$tend.':'.$tstart;
2560: }
2561: if (($env{'request.role'} =~ /dc\./) &&
2562: (($trole=~/^au/) || ($trole=~/^in/) ||
2563: ($trole=~/^cc/) || ($trole=~/^ep/) ||
2564: ($trole=~/^cr/) || ($trole=~/^ta/))) {
2565: $userrolehash
2566: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
2567: =$tend.':'.$tstart;
2568: }
2569: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
2570: ($trole=~/^li/) || ($trole=~/^li/) ||
2571: ($trole=~/^au/) || ($trole=~/^dg/) ||
2572: ($trole=~/^sc/)) {
2573: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
2574: $domainrolehash
2575: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
2576: = $tend.':'.$tstart;
2577: }
2578: }
2579:
2580: sub courserolelog {
2581: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
2582: if (($trole eq 'cc') || ($trole eq 'in') ||
2583: ($trole eq 'ep') || ($trole eq 'ad') ||
2584: ($trole eq 'ta') || ($trole eq 'st') ||
2585: ($trole=~/^cr/) || ($trole eq 'gr')) {
2586: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
2587: my $cdom = $1;
2588: my $cnum = $2;
2589: my $sec = $3;
2590: my $namespace = 'rolelog';
2591: my %storehash = (
2592: role => $trole,
2593: start => $tstart,
2594: end => $tend,
2595: selfenroll => $selfenroll,
2596: context => $context,
2597: );
2598: if ($trole eq 'gr') {
2599: $namespace = 'groupslog';
2600: $storehash{'group'} = $sec;
2601: } else {
2602: $storehash{'section'} = $sec;
2603: }
2604: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
2605: }
2606: }
2607: return;
2608: }
2609:
2610: sub get_course_adv_roles {
2611: my ($cid,$codes) = @_;
2612: $cid=$env{'request.course.id'} unless (defined($cid));
2613: my %coursehash=&coursedescription($cid);
2614: my %nothide=();
2615: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2616: if ($user !~ /:/) {
2617: $nothide{join(':',split(/[\@]/,$user))}=1;
2618: } else {
2619: $nothide{$user}=1;
2620: }
2621: }
2622: my %returnhash=();
2623: my %dumphash=
2624: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
2625: my $now=time;
2626: foreach my $entry (keys %dumphash) {
2627: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2628: if (($tstart) && ($tstart<0)) { next; }
2629: if (($tend) && ($tend<$now)) { next; }
2630: if (($tstart) && ($now<$tstart)) { next; }
2631: my ($role,$username,$domain,$section)=split(/\:/,$entry);
2632: if ($username eq '' || $domain eq '') { next; }
2633: if ((&privileged($username,$domain)) &&
2634: (!$nothide{$username.':'.$domain})) { next; }
2635: if ($role eq 'cr') { next; }
2636: if ($codes) {
2637: if ($section) { $role .= ':'.$section; }
2638: if ($returnhash{$role}) {
2639: $returnhash{$role}.=','.$username.':'.$domain;
2640: } else {
2641: $returnhash{$role}=$username.':'.$domain;
2642: }
2643: } else {
2644: my $key=&plaintext($role);
2645: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
2646: if ($returnhash{$key}) {
2647: $returnhash{$key}.=','.$username.':'.$domain;
2648: } else {
2649: $returnhash{$key}=$username.':'.$domain;
2650: }
2651: }
2652: }
2653: return %returnhash;
2654: }
2655:
2656: sub get_my_roles {
2657: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
2658: unless (defined($uname)) { $uname=$env{'user.name'}; }
2659: unless (defined($udom)) { $udom=$env{'user.domain'}; }
2660: my (%dumphash,%nothide);
2661: if ($context eq 'userroles') {
2662: %dumphash = &dump('roles',$udom,$uname);
2663: } else {
2664: %dumphash=
2665: &dump('nohist_userroles',$udom,$uname);
2666: if ($hidepriv) {
2667: my %coursehash=&coursedescription($udom.'_'.$uname);
2668: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
2669: if ($user !~ /:/) {
2670: $nothide{join(':',split(/[\@]/,$user))} = 1;
2671: } else {
2672: $nothide{$user} = 1;
2673: }
2674: }
2675: }
2676: }
2677: my %returnhash=();
2678: my $now=time;
2679: foreach my $entry (keys(%dumphash)) {
2680: my ($role,$tend,$tstart);
2681: if ($context eq 'userroles') {
2682: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
2683: } else {
2684: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
2685: }
2686: if (($tstart) && ($tstart<0)) { next; }
2687: my $status = 'active';
2688: if (($tend) && ($tend<=$now)) {
2689: $status = 'previous';
2690: }
2691: if (($tstart) && ($now<$tstart)) {
2692: $status = 'future';
2693: }
2694: if (ref($types) eq 'ARRAY') {
2695: if (!grep(/^\Q$status\E$/,@{$types})) {
2696: next;
2697: }
2698: } else {
2699: if ($status ne 'active') {
2700: next;
2701: }
2702: }
2703: my ($rolecode,$username,$domain,$section,$area);
2704: if ($context eq 'userroles') {
2705: ($area,$rolecode) = split(/_/,$entry);
2706: (undef,$domain,$username,$section) = split(/\//,$area);
2707: } else {
2708: ($role,$username,$domain,$section) = split(/\:/,$entry);
2709: }
2710: if (ref($roledoms) eq 'ARRAY') {
2711: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
2712: next;
2713: }
2714: }
2715: if (ref($roles) eq 'ARRAY') {
2716: if (!grep(/^\Q$role\E$/,@{$roles})) {
2717: if ($role =~ /^cr\//) {
2718: if (!grep(/^cr$/,@{$roles})) {
2719: next;
2720: }
2721: } else {
2722: next;
2723: }
2724: }
2725: }
2726: if ($hidepriv) {
2727: if ((&privileged($username,$domain)) &&
2728: (!$nothide{$username.':'.$domain})) {
2729: next;
2730: }
2731: }
2732: if ($withsec) {
2733: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
2734: $tstart.':'.$tend;
2735: } else {
2736: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
2737: }
2738: }
2739: return %returnhash;
2740: }
2741:
2742: # ----------------------------------------------------- Frontpage Announcements
2743: #
2744: #
2745:
2746: sub postannounce {
2747: my ($server,$text)=@_;
2748: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
2749: unless ($text=~/\w/) { $text=''; }
2750: return &reply('setannounce:'.&escape($text),$server);
2751: }
2752:
2753: sub getannounce {
2754:
2755: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
2756: my $announcement='';
2757: while (my $line = <$fh>) { $announcement .= $line; }
2758: close($fh);
2759: if ($announcement=~/\w/) {
2760: return
2761: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
2762: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
2763: } else {
2764: return '';
2765: }
2766: } else {
2767: return '';
2768: }
2769: }
2770:
2771: # ---------------------------------------------------------- Course ID routines
2772: # Deal with domain's nohist_courseid.db files
2773: #
2774:
2775: sub courseidput {
2776: my ($domain,$storehash,$coursehome,$caller) = @_;
2777: my $outcome;
2778: if ($caller eq 'timeonly') {
2779: my $cids = '';
2780: foreach my $item (keys(%$storehash)) {
2781: $cids.=&escape($item).'&';
2782: }
2783: $cids=~s/\&$//;
2784: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
2785: $coursehome);
2786: } else {
2787: my $items = '';
2788: foreach my $item (keys(%$storehash)) {
2789: $items.= &escape($item).'='.
2790: &freeze_escape($$storehash{$item}).'&';
2791: }
2792: $items=~s/\&$//;
2793: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
2794: $coursehome);
2795: }
2796: if ($outcome eq 'unknown_cmd') {
2797: my $what;
2798: foreach my $cid (keys(%$storehash)) {
2799: $what .= &escape($cid).'=';
2800: foreach my $item ('description','inst_code','owner','type') {
2801: $what .= &escape($storehash->{$cid}{$item}).':';
2802: }
2803: $what =~ s/\:$/&/;
2804: }
2805: $what =~ s/\&$//;
2806: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
2807: } else {
2808: return $outcome;
2809: }
2810: }
2811:
2812: sub courseiddump {
2813: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
2814: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
2815: $selfenrollonly,$catfilter,$showhidden,$caller)=@_;
2816: my $as_hash = 1;
2817: my %returnhash;
2818: if (!$domfilter) { $domfilter=''; }
2819: my %libserv = &all_library();
2820: foreach my $tryserver (keys(%libserv)) {
2821: if ( ( $hostidflag == 1
2822: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
2823: || (!defined($hostidflag)) ) {
2824:
2825: if (($domfilter eq '') ||
2826: (&host_domain($tryserver) eq $domfilter)) {
2827: my $rep =
2828: &reply('courseiddump:'.&host_domain($tryserver).':'.
2829: $sincefilter.':'.&escape($descfilter).':'.
2830: &escape($instcodefilter).':'.&escape($ownerfilter).
2831: ':'.&escape($coursefilter).':'.&escape($typefilter).
2832: ':'.&escape($regexp_ok).':'.$as_hash.':'.
2833: &escape($selfenrollonly).':'.&escape($catfilter).':'.
2834: $showhidden.':'.$caller,$tryserver);
2835: my @pairs=split(/\&/,$rep);
2836: foreach my $item (@pairs) {
2837: my ($key,$value)=split(/\=/,$item,2);
2838: $key = &unescape($key);
2839: next if ($key =~ /^error: 2 /);
2840: my $result = &thaw_unescape($value);
2841: if (ref($result) eq 'HASH') {
2842: $returnhash{$key}=$result;
2843: } else {
2844: my @responses = split(/:/,$value);
2845: my @items = ('description','inst_code','owner','type');
2846: for (my $i=0; $i<@responses; $i++) {
2847: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
2848: }
2849: }
2850: }
2851: }
2852: }
2853: }
2854: return %returnhash;
2855: }
2856:
2857: # ---------------------------------------------------------- DC e-mail
2858:
2859: sub dcmailput {
2860: my ($domain,$msgid,$message,$server)=@_;
2861: my $status = &Apache::lonnet::critical(
2862: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
2863: &escape($message),$server);
2864: return $status;
2865: }
2866:
2867: sub dcmaildump {
2868: my ($dom,$startdate,$enddate,$senders) = @_;
2869: my %returnhash=();
2870:
2871: if (defined(&domain($dom,'primary'))) {
2872: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
2873: &escape($enddate).':';
2874: my @esc_senders=map { &escape($_)} @$senders;
2875: $cmd.=&escape(join('&',@esc_senders));
2876: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
2877: my ($key,$value) = split(/\=/,$line,2);
2878: if (($key) && ($value)) {
2879: $returnhash{&unescape($key)} = &unescape($value);
2880: }
2881: }
2882: }
2883: return %returnhash;
2884: }
2885: # ---------------------------------------------------------- Domain roles
2886:
2887: sub get_domain_roles {
2888: my ($dom,$roles,$startdate,$enddate)=@_;
2889: if (undef($startdate) || $startdate eq '') {
2890: $startdate = '.';
2891: }
2892: if (undef($enddate) || $enddate eq '') {
2893: $enddate = '.';
2894: }
2895: my $rolelist;
2896: if (ref($roles) eq 'ARRAY') {
2897: $rolelist = join(':',@{$roles});
2898: }
2899: my %personnel = ();
2900:
2901: my %servers = &get_servers($dom,'library');
2902: foreach my $tryserver (keys(%servers)) {
2903: %{$personnel{$tryserver}}=();
2904: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
2905: &escape($startdate).':'.
2906: &escape($enddate).':'.
2907: &escape($rolelist), $tryserver))) {
2908: my ($key,$value) = split(/\=/,$line,2);
2909: if (($key) && ($value)) {
2910: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
2911: }
2912: }
2913: }
2914: return %personnel;
2915: }
2916:
2917: # ----------------------------------------------------------- Check out an item
2918:
2919: sub get_first_access {
2920: my ($type,$argsymb)=@_;
2921: my ($symb,$courseid,$udom,$uname)=&whichuser();
2922: if ($argsymb) { $symb=$argsymb; }
2923: my ($map,$id,$res)=&decode_symb($symb);
2924: if ($type eq 'course') {
2925: $res='course';
2926: } elsif ($type eq 'map') {
2927: $res=&symbread($map);
2928: } else {
2929: $res=$symb;
2930: }
2931: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
2932: return $times{"$courseid\0$res"};
2933: }
2934:
2935: sub set_first_access {
2936: my ($type)=@_;
2937: my ($symb,$courseid,$udom,$uname)=&whichuser();
2938: my ($map,$id,$res)=&decode_symb($symb);
2939: if ($type eq 'course') {
2940: $res='course';
2941: } elsif ($type eq 'map') {
2942: $res=&symbread($map);
2943: } else {
2944: $res=$symb;
2945: }
2946: my $firstaccess=&get_first_access($type,$symb);
2947: if (!$firstaccess) {
2948: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
2949: }
2950: return 'already_set';
2951: }
2952:
2953: sub checkout {
2954: my ($symb,$tuname,$tudom,$tcrsid)=@_;
2955: my $now=time;
2956: my $lonhost=$perlvar{'lonHostID'};
2957: my $infostr=&escape(
2958: 'CHECKOUTTOKEN&'.
2959: $tuname.'&'.
2960: $tudom.'&'.
2961: $tcrsid.'&'.
2962: $symb.'&'.
2963: $now.'&'.$ENV{'REMOTE_ADDR'});
2964: my $token=&reply('tmpput:'.$infostr,$lonhost);
2965: if ($token=~/^error\:/) {
2966: &logthis("<font color=\"blue\">WARNING: ".
2967: "Checkout tmpput failed ".$tudom.' - '.$tuname.' - '.$symb.
2968: "</font>");
2969: return '';
2970: }
2971:
2972: $token=~s/^(\d+)\_.*\_(\d+)$/$1\*$2\*$lonhost/;
2973: $token=~tr/a-z/A-Z/;
2974:
2975: my %infohash=('resource.0.outtoken' => $token,
2976: 'resource.0.checkouttime' => $now,
2977: 'resource.0.outremote' => $ENV{'REMOTE_ADDR'});
2978:
2979: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
2980: return '';
2981: } else {
2982: &logthis("<font color=\"blue\">WARNING: ".
2983: "Checkout cstore failed ".$tudom.' - '.$tuname.' - '.$symb.
2984: "</font>");
2985: }
2986:
2987: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
2988: &escape('Checkout '.$infostr.' - '.
2989: $token)) ne 'ok') {
2990: return '';
2991: } else {
2992: &logthis("<font color=\"blue\">WARNING: ".
2993: "Checkout log failed ".$tudom.' - '.$tuname.' - '.$symb.
2994: "</font>");
2995: }
2996: return $token;
2997: }
2998:
2999: # ------------------------------------------------------------ Check in an item
3000:
3001: sub checkin {
3002: my $token=shift;
3003: my $now=time;
3004: my ($ta,$tb,$lonhost)=split(/\*/,$token);
3005: $lonhost=~tr/A-Z/a-z/;
3006: my $dtoken=$ta.'_'.&hostname($lonhost).'_'.$tb;
3007: $dtoken=~s/\W/\_/g;
3008: my ($dummy,$tuname,$tudom,$tcrsid,$symb,$chtim,$rmaddr)=
3009: split(/\&/,&unescape(&reply('tmpget:'.$dtoken,$lonhost)));
3010:
3011: unless (($tuname) && ($tudom)) {
3012: &logthis('Check in '.$token.' ('.$dtoken.') failed');
3013: return '';
3014: }
3015:
3016: unless (&allowed('mgr',$tcrsid)) {
3017: &logthis('Check in '.$token.' ('.$dtoken.') unauthorized: '.
3018: $env{'user.name'}.' - '.$env{'user.domain'});
3019: return '';
3020: }
3021:
3022: my %infohash=('resource.0.intoken' => $token,
3023: 'resource.0.checkintime' => $now,
3024: 'resource.0.inremote' => $ENV{'REMOTE_ADDR'});
3025:
3026: unless (&cstore(\%infohash,$symb,$tcrsid,$tudom,$tuname) eq 'ok') {
3027: return '';
3028: }
3029:
3030: if (&log($tudom,$tuname,&homeserver($tuname,$tudom),
3031: &escape('Checkin - '.$token)) ne 'ok') {
3032: return '';
3033: }
3034:
3035: return ($symb,$tuname,$tudom,$tcrsid);
3036: }
3037:
3038: # --------------------------------------------- Set Expire Date for Spreadsheet
3039:
3040: sub expirespread {
3041: my ($uname,$udom,$stype,$usymb)=@_;
3042: my $cid=$env{'request.course.id'};
3043: if ($cid) {
3044: my $now=time;
3045: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
3046: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3047: $env{'course.'.$cid.'.num'}.
3048: ':nohist_expirationdates:'.
3049: &escape($key).'='.$now,
3050: $env{'course.'.$cid.'.home'})
3051: }
3052: return 'ok';
3053: }
3054:
3055: # ----------------------------------------------------- Devalidate Spreadsheets
3056:
3057: sub devalidate {
3058: my ($symb,$uname,$udom)=@_;
3059: my $cid=$env{'request.course.id'};
3060: if ($cid) {
3061: # delete the stored spreadsheets for
3062: # - the student level sheet of this user in course's homespace
3063: # - the assessment level sheet for this resource
3064: # for this user in user's homespace
3065: # - current conditional state info
3066: my $key=$uname.':'.$udom.':';
3067: my $status=
3068: &del('nohist_calculatedsheets',
3069: [$key.'studentcalc:'],
3070: $env{'course.'.$cid.'.domain'},
3071: $env{'course.'.$cid.'.num'})
3072: .' '.
3073: &del('nohist_calculatedsheets_'.$cid,
3074: [$key.'assesscalc:'.$symb],$udom,$uname);
3075: unless ($status eq 'ok ok') {
3076: &logthis('Could not devalidate spreadsheet '.
3077: $uname.' at '.$udom.' for '.
3078: $symb.': '.$status);
3079: }
3080: &delenv('user.state.'.$cid);
3081: }
3082: }
3083:
3084: sub get_scalar {
3085: my ($string,$end) = @_;
3086: my $value;
3087: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3088: $value = $1;
3089: } elsif ($$string =~ s/^([^&]*?)&//) {
3090: $value = $1;
3091: }
3092: return &unescape($value);
3093: }
3094:
3095: sub array2str {
3096: my (@array) = @_;
3097: my $result=&arrayref2str(\@array);
3098: $result=~s/^__ARRAY_REF__//;
3099: $result=~s/__END_ARRAY_REF__$//;
3100: return $result;
3101: }
3102:
3103: sub arrayref2str {
3104: my ($arrayref) = @_;
3105: my $result='__ARRAY_REF__';
3106: foreach my $elem (@$arrayref) {
3107: if(ref($elem) eq 'ARRAY') {
3108: $result.=&arrayref2str($elem).'&';
3109: } elsif(ref($elem) eq 'HASH') {
3110: $result.=&hashref2str($elem).'&';
3111: } elsif(ref($elem)) {
3112: #print("Got a ref of ".(ref($elem))." skipping.");
3113: } else {
3114: $result.=&escape($elem).'&';
3115: }
3116: }
3117: $result=~s/\&$//;
3118: $result .= '__END_ARRAY_REF__';
3119: return $result;
3120: }
3121:
3122: sub hash2str {
3123: my (%hash) = @_;
3124: my $result=&hashref2str(\%hash);
3125: $result=~s/^__HASH_REF__//;
3126: $result=~s/__END_HASH_REF__$//;
3127: return $result;
3128: }
3129:
3130: sub hashref2str {
3131: my ($hashref)=@_;
3132: my $result='__HASH_REF__';
3133: foreach my $key (sort(keys(%$hashref))) {
3134: if (ref($key) eq 'ARRAY') {
3135: $result.=&arrayref2str($key).'=';
3136: } elsif (ref($key) eq 'HASH') {
3137: $result.=&hashref2str($key).'=';
3138: } elsif (ref($key)) {
3139: $result.='=';
3140: #print("Got a ref of ".(ref($key))." skipping.");
3141: } else {
3142: if ($key) {$result.=&escape($key).'=';} else { last; }
3143: }
3144:
3145: if(ref($hashref->{$key}) eq 'ARRAY') {
3146: $result.=&arrayref2str($hashref->{$key}).'&';
3147: } elsif(ref($hashref->{$key}) eq 'HASH') {
3148: $result.=&hashref2str($hashref->{$key}).'&';
3149: } elsif(ref($hashref->{$key})) {
3150: $result.='&';
3151: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
3152: } else {
3153: $result.=&escape($hashref->{$key}).'&';
3154: }
3155: }
3156: $result=~s/\&$//;
3157: $result .= '__END_HASH_REF__';
3158: return $result;
3159: }
3160:
3161: sub str2hash {
3162: my ($string)=@_;
3163: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
3164: return %$hash;
3165: }
3166:
3167: sub str2hashref {
3168: my ($string) = @_;
3169:
3170: my %hash;
3171:
3172: if($string !~ /^__HASH_REF__/) {
3173: if (! ($string eq '' || !defined($string))) {
3174: $hash{'error'}='Not hash reference';
3175: }
3176: return (\%hash, $string);
3177: }
3178:
3179: $string =~ s/^__HASH_REF__//;
3180:
3181: while($string !~ /^__END_HASH_REF__/) {
3182: #key
3183: my $key='';
3184: if($string =~ /^__HASH_REF__/) {
3185: ($key, $string)=&str2hashref($string);
3186: if(defined($key->{'error'})) {
3187: $hash{'error'}='Bad data';
3188: return (\%hash, $string);
3189: }
3190: } elsif($string =~ /^__ARRAY_REF__/) {
3191: ($key, $string)=&str2arrayref($string);
3192: if($key->[0] eq 'Array reference error') {
3193: $hash{'error'}='Bad data';
3194: return (\%hash, $string);
3195: }
3196: } else {
3197: $string =~ s/^(.*?)=//;
3198: $key=&unescape($1);
3199: }
3200: $string =~ s/^=//;
3201:
3202: #value
3203: my $value='';
3204: if($string =~ /^__HASH_REF__/) {
3205: ($value, $string)=&str2hashref($string);
3206: if(defined($value->{'error'})) {
3207: $hash{'error'}='Bad data';
3208: return (\%hash, $string);
3209: }
3210: } elsif($string =~ /^__ARRAY_REF__/) {
3211: ($value, $string)=&str2arrayref($string);
3212: if($value->[0] eq 'Array reference error') {
3213: $hash{'error'}='Bad data';
3214: return (\%hash, $string);
3215: }
3216: } else {
3217: $value=&get_scalar(\$string,'__END_HASH_REF__');
3218: }
3219: $string =~ s/^&//;
3220:
3221: $hash{$key}=$value;
3222: }
3223:
3224: $string =~ s/^__END_HASH_REF__//;
3225:
3226: return (\%hash, $string);
3227: }
3228:
3229: sub str2array {
3230: my ($string)=@_;
3231: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
3232: return @$array;
3233: }
3234:
3235: sub str2arrayref {
3236: my ($string) = @_;
3237: my @array;
3238:
3239: if($string !~ /^__ARRAY_REF__/) {
3240: if (! ($string eq '' || !defined($string))) {
3241: $array[0]='Array reference error';
3242: }
3243: return (\@array, $string);
3244: }
3245:
3246: $string =~ s/^__ARRAY_REF__//;
3247:
3248: while($string !~ /^__END_ARRAY_REF__/) {
3249: my $value='';
3250: if($string =~ /^__HASH_REF__/) {
3251: ($value, $string)=&str2hashref($string);
3252: if(defined($value->{'error'})) {
3253: $array[0] ='Array reference error';
3254: return (\@array, $string);
3255: }
3256: } elsif($string =~ /^__ARRAY_REF__/) {
3257: ($value, $string)=&str2arrayref($string);
3258: if($value->[0] eq 'Array reference error') {
3259: $array[0] ='Array reference error';
3260: return (\@array, $string);
3261: }
3262: } else {
3263: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
3264: }
3265: $string =~ s/^&//;
3266:
3267: push(@array, $value);
3268: }
3269:
3270: $string =~ s/^__END_ARRAY_REF__//;
3271:
3272: return (\@array, $string);
3273: }
3274:
3275: # -------------------------------------------------------------------Temp Store
3276:
3277: sub tmpreset {
3278: my ($symb,$namespace,$domain,$stuname) = @_;
3279: if (!$symb) {
3280: $symb=&symbread();
3281: if (!$symb) { $symb= $env{'request.url'}; }
3282: }
3283: $symb=escape($symb);
3284:
3285: if (!$namespace) { $namespace=$env{'request.state'}; }
3286: $namespace=~s/\//\_/g;
3287: $namespace=~s/\W//g;
3288:
3289: if (!$domain) { $domain=$env{'user.domain'}; }
3290: if (!$stuname) { $stuname=$env{'user.name'}; }
3291: if ($domain eq 'public' && $stuname eq 'public') {
3292: $stuname=$ENV{'REMOTE_ADDR'};
3293: }
3294: my $path=$perlvar{'lonDaemons'}.'/tmp';
3295: my %hash;
3296: if (tie(%hash,'GDBM_File',
3297: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3298: &GDBM_WRCREAT(),0640)) {
3299: foreach my $key (keys %hash) {
3300: if ($key=~ /:$symb/) {
3301: delete($hash{$key});
3302: }
3303: }
3304: }
3305: }
3306:
3307: sub tmpstore {
3308: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3309:
3310: if (!$symb) {
3311: $symb=&symbread();
3312: if (!$symb) { $symb= $env{'request.url'}; }
3313: }
3314: $symb=escape($symb);
3315:
3316: if (!$namespace) {
3317: # I don't think we would ever want to store this for a course.
3318: # it seems this will only be used if we don't have a course.
3319: #$namespace=$env{'request.course.id'};
3320: #if (!$namespace) {
3321: $namespace=$env{'request.state'};
3322: #}
3323: }
3324: $namespace=~s/\//\_/g;
3325: $namespace=~s/\W//g;
3326: if (!$domain) { $domain=$env{'user.domain'}; }
3327: if (!$stuname) { $stuname=$env{'user.name'}; }
3328: if ($domain eq 'public' && $stuname eq 'public') {
3329: $stuname=$ENV{'REMOTE_ADDR'};
3330: }
3331: my $now=time;
3332: my %hash;
3333: my $path=$perlvar{'lonDaemons'}.'/tmp';
3334: if (tie(%hash,'GDBM_File',
3335: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3336: &GDBM_WRCREAT(),0640)) {
3337: $hash{"version:$symb"}++;
3338: my $version=$hash{"version:$symb"};
3339: my $allkeys='';
3340: foreach my $key (keys(%$storehash)) {
3341: $allkeys.=$key.':';
3342: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
3343: }
3344: $hash{"$version:$symb:timestamp"}=$now;
3345: $allkeys.='timestamp';
3346: $hash{"$version:keys:$symb"}=$allkeys;
3347: if (untie(%hash)) {
3348: return 'ok';
3349: } else {
3350: return "error:$!";
3351: }
3352: } else {
3353: return "error:$!";
3354: }
3355: }
3356:
3357: # -----------------------------------------------------------------Temp Restore
3358:
3359: sub tmprestore {
3360: my ($symb,$namespace,$domain,$stuname) = @_;
3361:
3362: if (!$symb) {
3363: $symb=&symbread();
3364: if (!$symb) { $symb= $env{'request.url'}; }
3365: }
3366: $symb=escape($symb);
3367:
3368: if (!$namespace) { $namespace=$env{'request.state'}; }
3369:
3370: if (!$domain) { $domain=$env{'user.domain'}; }
3371: if (!$stuname) { $stuname=$env{'user.name'}; }
3372: if ($domain eq 'public' && $stuname eq 'public') {
3373: $stuname=$ENV{'REMOTE_ADDR'};
3374: }
3375: my %returnhash;
3376: $namespace=~s/\//\_/g;
3377: $namespace=~s/\W//g;
3378: my %hash;
3379: my $path=$perlvar{'lonDaemons'}.'/tmp';
3380: if (tie(%hash,'GDBM_File',
3381: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
3382: &GDBM_READER(),0640)) {
3383: my $version=$hash{"version:$symb"};
3384: $returnhash{'version'}=$version;
3385: my $scope;
3386: for ($scope=1;$scope<=$version;$scope++) {
3387: my $vkeys=$hash{"$scope:keys:$symb"};
3388: my @keys=split(/:/,$vkeys);
3389: my $key;
3390: $returnhash{"$scope:keys"}=$vkeys;
3391: foreach $key (@keys) {
3392: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3393: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
3394: }
3395: }
3396: if (!(untie(%hash))) {
3397: return "error:$!";
3398: }
3399: } else {
3400: return "error:$!";
3401: }
3402: return %returnhash;
3403: }
3404:
3405: # ----------------------------------------------------------------------- Store
3406:
3407: sub store {
3408: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3409: my $home='';
3410:
3411: if ($stuname) { $home=&homeserver($stuname,$domain); }
3412:
3413: $symb=&symbclean($symb);
3414: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3415:
3416: if (!$domain) { $domain=$env{'user.domain'}; }
3417: if (!$stuname) { $stuname=$env{'user.name'}; }
3418:
3419: &devalidate($symb,$stuname,$domain);
3420:
3421: $symb=escape($symb);
3422: if (!$namespace) {
3423: unless ($namespace=$env{'request.course.id'}) {
3424: return '';
3425: }
3426: }
3427: if (!$home) { $home=$env{'user.home'}; }
3428:
3429: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3430: $$storehash{'host'}=$perlvar{'lonHostID'};
3431:
3432: my $namevalue='';
3433: foreach my $key (keys(%$storehash)) {
3434: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3435: }
3436: $namevalue=~s/\&$//;
3437: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
3438: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3439: }
3440:
3441: # -------------------------------------------------------------- Critical Store
3442:
3443: sub cstore {
3444: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
3445: my $home='';
3446:
3447: if ($stuname) { $home=&homeserver($stuname,$domain); }
3448:
3449: $symb=&symbclean($symb);
3450: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
3451:
3452: if (!$domain) { $domain=$env{'user.domain'}; }
3453: if (!$stuname) { $stuname=$env{'user.name'}; }
3454:
3455: &devalidate($symb,$stuname,$domain);
3456:
3457: $symb=escape($symb);
3458: if (!$namespace) {
3459: unless ($namespace=$env{'request.course.id'}) {
3460: return '';
3461: }
3462: }
3463: if (!$home) { $home=$env{'user.home'}; }
3464:
3465: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
3466: $$storehash{'host'}=$perlvar{'lonHostID'};
3467:
3468: my $namevalue='';
3469: foreach my $key (keys(%$storehash)) {
3470: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
3471: }
3472: $namevalue=~s/\&$//;
3473: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
3474: return critical
3475: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
3476: }
3477:
3478: # --------------------------------------------------------------------- Restore
3479:
3480: sub restore {
3481: my ($symb,$namespace,$domain,$stuname) = @_;
3482: my $home='';
3483:
3484: if ($stuname) { $home=&homeserver($stuname,$domain); }
3485:
3486: if (!$symb) {
3487: unless ($symb=escape(&symbread())) { return ''; }
3488: } else {
3489: $symb=&escape(&symbclean($symb));
3490: }
3491: if (!$namespace) {
3492: unless ($namespace=$env{'request.course.id'}) {
3493: return '';
3494: }
3495: }
3496: if (!$domain) { $domain=$env{'user.domain'}; }
3497: if (!$stuname) { $stuname=$env{'user.name'}; }
3498: if (!$home) { $home=$env{'user.home'}; }
3499: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
3500:
3501: my %returnhash=();
3502: foreach my $line (split(/\&/,$answer)) {
3503: my ($name,$value)=split(/\=/,$line);
3504: $returnhash{&unescape($name)}=&thaw_unescape($value);
3505: }
3506: my $version;
3507: for ($version=1;$version<=$returnhash{'version'};$version++) {
3508: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
3509: $returnhash{$item}=$returnhash{$version.':'.$item};
3510: }
3511: }
3512: return %returnhash;
3513: }
3514:
3515: # ---------------------------------------------------------- Course Description
3516:
3517: sub coursedescription {
3518: my ($courseid,$args)=@_;
3519: $courseid=~s/^\///;
3520: $courseid=~s/\_/\//g;
3521: my ($cdomain,$cnum)=split(/\//,$courseid);
3522: my $chome=&homeserver($cnum,$cdomain);
3523: my $normalid=$cdomain.'_'.$cnum;
3524: # need to always cache even if we get errors otherwise we keep
3525: # trying and trying and trying to get the course description.
3526: my %envhash=();
3527: my %returnhash=();
3528:
3529: my $expiretime=600;
3530: if ($env{'request.course.id'} eq $normalid) {
3531: $expiretime=120;
3532: }
3533:
3534: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
3535: if (!$args->{'freshen_cache'}
3536: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
3537: foreach my $key (keys(%env)) {
3538: next if ($key !~ /^\Q$prefix\E(.*)/);
3539: my ($setting) = $1;
3540: $returnhash{$setting} = $env{$key};
3541: }
3542: return %returnhash;
3543: }
3544:
3545: # get the data agin
3546: if (!$args->{'one_time'}) {
3547: $envhash{'course.'.$normalid.'.last_cache'}=time;
3548: }
3549:
3550: if ($chome ne 'no_host') {
3551: %returnhash=&dump('environment',$cdomain,$cnum);
3552: if (!exists($returnhash{'con_lost'})) {
3553: $returnhash{'home'}= $chome;
3554: $returnhash{'domain'} = $cdomain;
3555: $returnhash{'num'} = $cnum;
3556: if (!defined($returnhash{'type'})) {
3557: $returnhash{'type'} = 'Course';
3558: }
3559: while (my ($name,$value) = each %returnhash) {
3560: $envhash{'course.'.$normalid.'.'.$name}=$value;
3561: }
3562: $returnhash{'url'}=&clutter($returnhash{'url'});
3563: $returnhash{'fn'}=$perlvar{'lonDaemons'}.'/tmp/'.
3564: $env{'user.name'}.'_'.$cdomain.'_'.$cnum;
3565: $envhash{'course.'.$normalid.'.home'}=$chome;
3566: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
3567: $envhash{'course.'.$normalid.'.num'}=$cnum;
3568: }
3569: }
3570: if (!$args->{'one_time'}) {
3571: &appenv(\%envhash);
3572: }
3573: return %returnhash;
3574: }
3575:
3576: # -------------------------------------------------See if a user is privileged
3577:
3578: sub privileged {
3579: my ($username,$domain)=@_;
3580: my $rolesdump=&reply("dump:$domain:$username:roles",
3581: &homeserver($username,$domain));
3582: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return 0; }
3583: my $now=time;
3584: if ($rolesdump ne '') {
3585: foreach my $entry (split(/&/,$rolesdump)) {
3586: if ($entry!~/^rolesdef_/) {
3587: my ($area,$role)=split(/=/,$entry);
3588: $area=~s/\_\w\w$//;
3589: my ($trole,$tend,$tstart)=split(/_/,$role);
3590: if (($trole eq 'dc') || ($trole eq 'su')) {
3591: my $active=1;
3592: if ($tend) {
3593: if ($tend<$now) { $active=0; }
3594: }
3595: if ($tstart) {
3596: if ($tstart>$now) { $active=0; }
3597: }
3598: if ($active) { return 1; }
3599: }
3600: }
3601: }
3602: }
3603: return 0;
3604: }
3605:
3606: # -------------------------------------------------------- Get user privileges
3607:
3608: sub rolesinit {
3609: my ($domain,$username,$authhost)=@_;
3610: my %userroles;
3611: my $rolesdump=reply("dump:$domain:$username:roles",$authhost);
3612: if (($rolesdump eq 'con_lost') || ($rolesdump eq '')) { return \%userroles; }
3613: my %allroles=();
3614: my %allgroups=();
3615: my $now=time;
3616: %userroles = ('user.login.time' => $now);
3617: my $group_privs;
3618:
3619: if ($rolesdump ne '') {
3620: foreach my $entry (split(/&/,$rolesdump)) {
3621: if ($entry!~/^rolesdef_/) {
3622: my ($area,$role)=split(/=/,$entry);
3623: $area=~s/\_\w\w$//;
3624: my ($trole,$tend,$tstart,$group_privs);
3625: if ($role=~/^cr/) {
3626: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
3627: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
3628: ($tend,$tstart)=split('_',$trest);
3629: } else {
3630: $trole=$role;
3631: }
3632: } elsif ($role =~ m|^gr/|) {
3633: ($trole,$tend,$tstart) = split(/_/,$role);
3634: ($trole,$group_privs) = split(/\//,$trole);
3635: $group_privs = &unescape($group_privs);
3636: } else {
3637: ($trole,$tend,$tstart)=split(/_/,$role);
3638: }
3639: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
3640: $username);
3641: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
3642: if (($tend!=0) && ($tend<$now)) { $trole=''; }
3643: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
3644: if (($area ne '') && ($trole ne '')) {
3645: my $spec=$trole.'.'.$area;
3646: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
3647: if ($trole =~ /^cr\//) {
3648: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
3649: } elsif ($trole eq 'gr') {
3650: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
3651: } else {
3652: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
3653: }
3654: }
3655: }
3656: }
3657: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
3658: $userroles{'user.adv'} = $adv;
3659: $userroles{'user.author'} = $author;
3660: $env{'user.adv'}=$adv;
3661: }
3662: return \%userroles;
3663: }
3664:
3665: sub set_arearole {
3666: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
3667: # log the associated role with the area
3668: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
3669: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
3670: }
3671:
3672: sub custom_roleprivs {
3673: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
3674: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
3675: my $homsvr=homeserver($rauthor,$rdomain);
3676: if (&hostname($homsvr) ne '') {
3677: my ($rdummy,$roledef)=
3678: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
3679: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
3680: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
3681: if (defined($syspriv)) {
3682: $$allroles{'cm./'}.=':'.$syspriv;
3683: $$allroles{$spec.'./'}.=':'.$syspriv;
3684: }
3685: if ($tdomain ne '') {
3686: if (defined($dompriv)) {
3687: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
3688: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
3689: }
3690: if (($trest ne '') && (defined($coursepriv))) {
3691: $$allroles{'cm.'.$area}.=':'.$coursepriv;
3692: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
3693: }
3694: }
3695: }
3696: }
3697: }
3698:
3699: sub group_roleprivs {
3700: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
3701: my $access = 1;
3702: my $now = time;
3703: if (($tend!=0) && ($tend<$now)) { $access = 0; }
3704: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
3705: if ($access) {
3706: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
3707: $$allgroups{$course}{$group} .=':'.$group_privs;
3708: }
3709: }
3710:
3711: sub standard_roleprivs {
3712: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
3713: if (defined($pr{$trole.':s'})) {
3714: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
3715: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
3716: }
3717: if ($tdomain ne '') {
3718: if (defined($pr{$trole.':d'})) {
3719: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3720: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
3721: }
3722: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
3723: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
3724: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
3725: }
3726: }
3727: }
3728:
3729: sub set_userprivs {
3730: my ($userroles,$allroles,$allgroups) = @_;
3731: my $author=0;
3732: my $adv=0;
3733: my %grouproles = ();
3734: if (keys(%{$allgroups}) > 0) {
3735: foreach my $role (keys %{$allroles}) {
3736: my ($trole,$area,$sec,$extendedarea);
3737: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
3738: $trole = $1;
3739: $area = $2;
3740: $sec = $3;
3741: $extendedarea = $area.$sec;
3742: if (exists($$allgroups{$area})) {
3743: foreach my $group (keys(%{$$allgroups{$area}})) {
3744: my $spec = $trole.'.'.$extendedarea;
3745: $grouproles{$spec.'.'.$area.'/'.$group} =
3746: $$allgroups{$area}{$group};
3747: }
3748: }
3749: }
3750: }
3751: }
3752: foreach my $group (keys(%grouproles)) {
3753: $$allroles{$group} = $grouproles{$group};
3754: }
3755: foreach my $role (keys(%{$allroles})) {
3756: my %thesepriv;
3757: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
3758: foreach my $item (split(/:/,$$allroles{$role})) {
3759: if ($item ne '') {
3760: my ($privilege,$restrictions)=split(/&/,$item);
3761: if ($restrictions eq '') {
3762: $thesepriv{$privilege}='F';
3763: } elsif ($thesepriv{$privilege} ne 'F') {
3764: $thesepriv{$privilege}.=$restrictions;
3765: }
3766: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
3767: }
3768: }
3769: my $thesestr='';
3770: foreach my $priv (keys(%thesepriv)) {
3771: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
3772: }
3773: $userroles->{'user.priv.'.$role} = $thesestr;
3774: }
3775: return ($author,$adv);
3776: }
3777:
3778: # --------------------------------------------------------------- get interface
3779:
3780: sub get {
3781: my ($namespace,$storearr,$udomain,$uname)=@_;
3782: my $items='';
3783: foreach my $item (@$storearr) {
3784: $items.=&escape($item).'&';
3785: }
3786: $items=~s/\&$//;
3787: if (!$udomain) { $udomain=$env{'user.domain'}; }
3788: if (!$uname) { $uname=$env{'user.name'}; }
3789: my $uhome=&homeserver($uname,$udomain);
3790:
3791: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
3792: my @pairs=split(/\&/,$rep);
3793: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
3794: return @pairs;
3795: }
3796: my %returnhash=();
3797: my $i=0;
3798: foreach my $item (@$storearr) {
3799: $returnhash{$item}=&thaw_unescape($pairs[$i]);
3800: $i++;
3801: }
3802: return %returnhash;
3803: }
3804:
3805: # --------------------------------------------------------------- del interface
3806:
3807: sub del {
3808: my ($namespace,$storearr,$udomain,$uname)=@_;
3809: my $items='';
3810: foreach my $item (@$storearr) {
3811: $items.=&escape($item).'&';
3812: }
3813: $items=~s/\&$//;
3814: if (!$udomain) { $udomain=$env{'user.domain'}; }
3815: if (!$uname) { $uname=$env{'user.name'}; }
3816: my $uhome=&homeserver($uname,$udomain);
3817:
3818: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
3819: }
3820:
3821: # -------------------------------------------------------------- dump interface
3822:
3823: sub dump {
3824: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3825: if (!$udomain) { $udomain=$env{'user.domain'}; }
3826: if (!$uname) { $uname=$env{'user.name'}; }
3827: my $uhome=&homeserver($uname,$udomain);
3828: if ($regexp) {
3829: $regexp=&escape($regexp);
3830: } else {
3831: $regexp='.';
3832: }
3833: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3834: my @pairs=split(/\&/,$rep);
3835: my %returnhash=();
3836: foreach my $item (@pairs) {
3837: my ($key,$value)=split(/=/,$item,2);
3838: $key = &unescape($key);
3839: next if ($key =~ /^error: 2 /);
3840: $returnhash{$key}=&thaw_unescape($value);
3841: }
3842: return %returnhash;
3843: }
3844:
3845: # --------------------------------------------------------- dumpstore interface
3846:
3847: sub dumpstore {
3848: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
3849: if (!$udomain) { $udomain=$env{'user.domain'}; }
3850: if (!$uname) { $uname=$env{'user.name'}; }
3851: my $uhome=&homeserver($uname,$udomain);
3852: if ($regexp) {
3853: $regexp=&escape($regexp);
3854: } else {
3855: $regexp='.';
3856: }
3857: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
3858: my @pairs=split(/\&/,$rep);
3859: my %returnhash=();
3860: foreach my $item (@pairs) {
3861: my ($key,$value)=split(/=/,$item,2);
3862: next if ($key =~ /^error: 2 /);
3863: $returnhash{$key}=&thaw_unescape($value);
3864: }
3865: return %returnhash;
3866: }
3867:
3868: # -------------------------------------------------------------- keys interface
3869:
3870: sub getkeys {
3871: my ($namespace,$udomain,$uname)=@_;
3872: if (!$udomain) { $udomain=$env{'user.domain'}; }
3873: if (!$uname) { $uname=$env{'user.name'}; }
3874: my $uhome=&homeserver($uname,$udomain);
3875: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
3876: my @keyarray=();
3877: foreach my $key (split(/\&/,$rep)) {
3878: next if ($key =~ /^error: 2 /);
3879: push(@keyarray,&unescape($key));
3880: }
3881: return @keyarray;
3882: }
3883:
3884: # --------------------------------------------------------------- currentdump
3885: sub currentdump {
3886: my ($courseid,$sdom,$sname)=@_;
3887: $courseid = $env{'request.course.id'} if (! defined($courseid));
3888: $sdom = $env{'user.domain'} if (! defined($sdom));
3889: $sname = $env{'user.name'} if (! defined($sname));
3890: my $uhome = &homeserver($sname,$sdom);
3891: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
3892: return if ($rep =~ /^(error:|no_such_host)/);
3893: #
3894: my %returnhash=();
3895: #
3896: if ($rep eq "unknown_cmd") {
3897: # an old lond will not know currentdump
3898: # Do a dump and make it look like a currentdump
3899: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
3900: return if ($tmp[0] =~ /^(error:|no_such_host)/);
3901: my %hash = @tmp;
3902: @tmp=();
3903: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
3904: } else {
3905: my @pairs=split(/\&/,$rep);
3906: foreach my $pair (@pairs) {
3907: my ($key,$value)=split(/=/,$pair,2);
3908: my ($symb,$param) = split(/:/,$key);
3909: $returnhash{&unescape($symb)}->{&unescape($param)} =
3910: &thaw_unescape($value);
3911: }
3912: }
3913: return %returnhash;
3914: }
3915:
3916: sub convert_dump_to_currentdump{
3917: my %hash = %{shift()};
3918: my %returnhash;
3919: # Code ripped from lond, essentially. The only difference
3920: # here is the unescaping done by lonnet::dump(). Conceivably
3921: # we might run in to problems with parameter names =~ /^v\./
3922: while (my ($key,$value) = each(%hash)) {
3923: my ($v,$symb,$param) = split(/:/,$key);
3924: $symb = &unescape($symb);
3925: $param = &unescape($param);
3926: next if ($v eq 'version' || $symb eq 'keys');
3927: next if (exists($returnhash{$symb}) &&
3928: exists($returnhash{$symb}->{$param}) &&
3929: $returnhash{$symb}->{'v.'.$param} > $v);
3930: $returnhash{$symb}->{$param}=$value;
3931: $returnhash{$symb}->{'v.'.$param}=$v;
3932: }
3933: #
3934: # Remove all of the keys in the hashes which keep track of
3935: # the version of the parameter.
3936: while (my ($symb,$param_hash) = each(%returnhash)) {
3937: # use a foreach because we are going to delete from the hash.
3938: foreach my $key (keys(%$param_hash)) {
3939: delete($param_hash->{$key}) if ($key =~ /^v\./);
3940: }
3941: }
3942: return \%returnhash;
3943: }
3944:
3945: # ------------------------------------------------------ critical inc interface
3946:
3947: sub cinc {
3948: return &inc(@_,'critical');
3949: }
3950:
3951: # --------------------------------------------------------------- inc interface
3952:
3953: sub inc {
3954: my ($namespace,$store,$udomain,$uname,$critical) = @_;
3955: if (!$udomain) { $udomain=$env{'user.domain'}; }
3956: if (!$uname) { $uname=$env{'user.name'}; }
3957: my $uhome=&homeserver($uname,$udomain);
3958: my $items='';
3959: if (! ref($store)) {
3960: # got a single value, so use that instead
3961: $items = &escape($store).'=&';
3962: } elsif (ref($store) eq 'SCALAR') {
3963: $items = &escape($$store).'=&';
3964: } elsif (ref($store) eq 'ARRAY') {
3965: $items = join('=&',map {&escape($_);} @{$store});
3966: } elsif (ref($store) eq 'HASH') {
3967: while (my($key,$value) = each(%{$store})) {
3968: $items.= &escape($key).'='.&escape($value).'&';
3969: }
3970: }
3971: $items=~s/\&$//;
3972: if ($critical) {
3973: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
3974: } else {
3975: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
3976: }
3977: }
3978:
3979: # --------------------------------------------------------------- put interface
3980:
3981: sub put {
3982: my ($namespace,$storehash,$udomain,$uname)=@_;
3983: if (!$udomain) { $udomain=$env{'user.domain'}; }
3984: if (!$uname) { $uname=$env{'user.name'}; }
3985: my $uhome=&homeserver($uname,$udomain);
3986: my $items='';
3987: foreach my $item (keys(%$storehash)) {
3988: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
3989: }
3990: $items=~s/\&$//;
3991: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
3992: }
3993:
3994: # ------------------------------------------------------------ newput interface
3995:
3996: sub newput {
3997: my ($namespace,$storehash,$udomain,$uname)=@_;
3998: if (!$udomain) { $udomain=$env{'user.domain'}; }
3999: if (!$uname) { $uname=$env{'user.name'}; }
4000: my $uhome=&homeserver($uname,$udomain);
4001: my $items='';
4002: foreach my $key (keys(%$storehash)) {
4003: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
4004: }
4005: $items=~s/\&$//;
4006: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
4007: }
4008:
4009: # --------------------------------------------------------- putstore interface
4010:
4011: sub putstore {
4012: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4013: if (!$udomain) { $udomain=$env{'user.domain'}; }
4014: if (!$uname) { $uname=$env{'user.name'}; }
4015: my $uhome=&homeserver($uname,$udomain);
4016: my $items='';
4017: foreach my $key (keys(%$storehash)) {
4018: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
4019: }
4020: $items=~s/\&$//;
4021: my $esc_symb=&escape($symb);
4022: my $esc_v=&escape($version);
4023: my $reply =
4024: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
4025: $uhome);
4026: if ($reply eq 'unknown_cmd') {
4027: # gfall back to way things use to be done
4028: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
4029: $uname);
4030: }
4031: return $reply;
4032: }
4033:
4034: sub old_putstore {
4035: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
4036: if (!$udomain) { $udomain=$env{'user.domain'}; }
4037: if (!$uname) { $uname=$env{'user.name'}; }
4038: my $uhome=&homeserver($uname,$udomain);
4039: my %newstorehash;
4040: foreach my $item (keys(%$storehash)) {
4041: my $key = $version.':'.&escape($symb).':'.$item;
4042: $newstorehash{$key} = $storehash->{$item};
4043: }
4044: my $items='';
4045: my %allitems = ();
4046: foreach my $item (keys(%newstorehash)) {
4047: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
4048: my $key = $1.':keys:'.$2;
4049: $allitems{$key} .= $3.':';
4050: }
4051: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
4052: }
4053: foreach my $item (keys(%allitems)) {
4054: $allitems{$item} =~ s/\:$//;
4055: $items.= $item.'='.$allitems{$item}.'&';
4056: }
4057: $items=~s/\&$//;
4058: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
4059: }
4060:
4061: # ------------------------------------------------------ critical put interface
4062:
4063: sub cput {
4064: my ($namespace,$storehash,$udomain,$uname)=@_;
4065: if (!$udomain) { $udomain=$env{'user.domain'}; }
4066: if (!$uname) { $uname=$env{'user.name'}; }
4067: my $uhome=&homeserver($uname,$udomain);
4068: my $items='';
4069: foreach my $item (keys(%$storehash)) {
4070: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4071: }
4072: $items=~s/\&$//;
4073: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
4074: }
4075:
4076: # -------------------------------------------------------------- eget interface
4077:
4078: sub eget {
4079: my ($namespace,$storearr,$udomain,$uname)=@_;
4080: my $items='';
4081: foreach my $item (@$storearr) {
4082: $items.=&escape($item).'&';
4083: }
4084: $items=~s/\&$//;
4085: if (!$udomain) { $udomain=$env{'user.domain'}; }
4086: if (!$uname) { $uname=$env{'user.name'}; }
4087: my $uhome=&homeserver($uname,$udomain);
4088: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
4089: my @pairs=split(/\&/,$rep);
4090: my %returnhash=();
4091: my $i=0;
4092: foreach my $item (@$storearr) {
4093: $returnhash{$item}=&thaw_unescape($pairs[$i]);
4094: $i++;
4095: }
4096: return %returnhash;
4097: }
4098:
4099: # ------------------------------------------------------------ tmpput interface
4100: sub tmpput {
4101: my ($storehash,$server,$context)=@_;
4102: my $items='';
4103: foreach my $item (keys(%$storehash)) {
4104: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
4105: }
4106: $items=~s/\&$//;
4107: if (defined($context)) {
4108: $items .= ':'.&escape($context);
4109: }
4110: return &reply("tmpput:$items",$server);
4111: }
4112:
4113: # ------------------------------------------------------------ tmpget interface
4114: sub tmpget {
4115: my ($token,$server)=@_;
4116: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4117: my $rep=&reply("tmpget:$token",$server);
4118: my %returnhash;
4119: foreach my $item (split(/\&/,$rep)) {
4120: my ($key,$value)=split(/=/,$item);
4121: next if ($key =~ /^error: 2 /);
4122: $returnhash{&unescape($key)}=&thaw_unescape($value);
4123: }
4124: return %returnhash;
4125: }
4126:
4127: # ------------------------------------------------------------ tmpget interface
4128: sub tmpdel {
4129: my ($token,$server)=@_;
4130: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
4131: return &reply("tmpdel:$token",$server);
4132: }
4133:
4134: # -------------------------------------------------- portfolio access checking
4135:
4136: sub portfolio_access {
4137: my ($requrl) = @_;
4138: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
4139: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
4140: if ($result) {
4141: my %setters;
4142: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4143: my ($startblock,$endblock) =
4144: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
4145: if ($startblock && $endblock) {
4146: return 'B';
4147: }
4148: } else {
4149: my ($startblock,$endblock) =
4150: &Apache::loncommon::blockcheck(\%setters,'port');
4151: if ($startblock && $endblock) {
4152: return 'B';
4153: }
4154: }
4155: }
4156: if ($result eq 'ok') {
4157: return 'F';
4158: } elsif ($result =~ /^[^:]+:guest_/) {
4159: return 'A';
4160: }
4161: return '';
4162: }
4163:
4164: sub get_portfolio_access {
4165: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
4166:
4167: if (!ref($access_hash)) {
4168: my $current_perms = &get_portfile_permissions($udom,$unum);
4169: my %access_controls = &get_access_controls($current_perms,$group,
4170: $file_name);
4171: $access_hash = $access_controls{$file_name};
4172: }
4173:
4174: my ($public,$guest,@domains,@users,@courses,@groups);
4175: my $now = time;
4176: if (ref($access_hash) eq 'HASH') {
4177: foreach my $key (keys(%{$access_hash})) {
4178: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
4179: if ($start > $now) {
4180: next;
4181: }
4182: if ($end && $end<$now) {
4183: next;
4184: }
4185: if ($scope eq 'public') {
4186: $public = $key;
4187: last;
4188: } elsif ($scope eq 'guest') {
4189: $guest = $key;
4190: } elsif ($scope eq 'domains') {
4191: push(@domains,$key);
4192: } elsif ($scope eq 'users') {
4193: push(@users,$key);
4194: } elsif ($scope eq 'course') {
4195: push(@courses,$key);
4196: } elsif ($scope eq 'group') {
4197: push(@groups,$key);
4198: }
4199: }
4200: if ($public) {
4201: return 'ok';
4202: }
4203: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
4204: if ($guest) {
4205: return $guest;
4206: }
4207: } else {
4208: if (@domains > 0) {
4209: foreach my $domkey (@domains) {
4210: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
4211: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
4212: return 'ok';
4213: }
4214: }
4215: }
4216: }
4217: if (@users > 0) {
4218: foreach my $userkey (@users) {
4219: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
4220: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
4221: if (ref($item) eq 'HASH') {
4222: if (($item->{'uname'} eq $env{'user.name'}) &&
4223: ($item->{'udom'} eq $env{'user.domain'})) {
4224: return 'ok';
4225: }
4226: }
4227: }
4228: }
4229: }
4230: }
4231: my %roleshash;
4232: my @courses_and_groups = @courses;
4233: push(@courses_and_groups,@groups);
4234: if (@courses_and_groups > 0) {
4235: my (%allgroups,%allroles);
4236: my ($start,$end,$role,$sec,$group);
4237: foreach my $envkey (%env) {
4238: if ($envkey =~ m-^user\.role\.(gr|cc|in|ta|ep|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
4239: my $cid = $2.'_'.$3;
4240: if ($1 eq 'gr') {
4241: $group = $4;
4242: $allgroups{$cid}{$group} = $env{$envkey};
4243: } else {
4244: if ($4 eq '') {
4245: $sec = 'none';
4246: } else {
4247: $sec = $4;
4248: }
4249: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4250: }
4251: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
4252: my $cid = $2.'_'.$3;
4253: if ($4 eq '') {
4254: $sec = 'none';
4255: } else {
4256: $sec = $4;
4257: }
4258: $allroles{$cid}{$1}{$sec} = $env{$envkey};
4259: }
4260: }
4261: if (keys(%allroles) == 0) {
4262: return;
4263: }
4264: foreach my $key (@courses_and_groups) {
4265: my %content = %{$$access_hash{$key}};
4266: my $cnum = $content{'number'};
4267: my $cdom = $content{'domain'};
4268: my $cid = $cdom.'_'.$cnum;
4269: if (!exists($allroles{$cid})) {
4270: next;
4271: }
4272: foreach my $role_id (keys(%{$content{'roles'}})) {
4273: my @sections = @{$content{'roles'}{$role_id}{'section'}};
4274: my @groups = @{$content{'roles'}{$role_id}{'group'}};
4275: my @status = @{$content{'roles'}{$role_id}{'access'}};
4276: my @roles = @{$content{'roles'}{$role_id}{'role'}};
4277: foreach my $role (keys(%{$allroles{$cid}})) {
4278: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
4279: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
4280: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
4281: if (grep/^all$/,@sections) {
4282: return 'ok';
4283: } else {
4284: if (grep/^$sec$/,@sections) {
4285: return 'ok';
4286: }
4287: }
4288: }
4289: }
4290: if (keys(%{$allgroups{$cid}}) == 0) {
4291: if (grep/^none$/,@groups) {
4292: return 'ok';
4293: }
4294: } else {
4295: if (grep/^all$/,@groups) {
4296: return 'ok';
4297: }
4298: foreach my $group (keys(%{$allgroups{$cid}})) {
4299: if (grep/^$group$/,@groups) {
4300: return 'ok';
4301: }
4302: }
4303: }
4304: }
4305: }
4306: }
4307: }
4308: }
4309: if ($guest) {
4310: return $guest;
4311: }
4312: }
4313: }
4314: return;
4315: }
4316:
4317: sub course_group_datechecker {
4318: my ($dates,$now,$status) = @_;
4319: my ($start,$end) = split(/\./,$dates);
4320: if (!$start && !$end) {
4321: return 'ok';
4322: }
4323: if (grep/^active$/,@{$status}) {
4324: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
4325: return 'ok';
4326: }
4327: }
4328: if (grep/^previous$/,@{$status}) {
4329: if ($end > $now ) {
4330: return 'ok';
4331: }
4332: }
4333: if (grep/^future$/,@{$status}) {
4334: if ($start > $now) {
4335: return 'ok';
4336: }
4337: }
4338: return;
4339: }
4340:
4341: sub parse_portfolio_url {
4342: my ($url) = @_;
4343:
4344: my ($type,$udom,$unum,$group,$file_name);
4345:
4346: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
4347: $type = 1;
4348: $udom = $1;
4349: $unum = $2;
4350: $file_name = $3;
4351: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
4352: $type = 2;
4353: $udom = $1;
4354: $unum = $2;
4355: $group = $3;
4356: $file_name = $3.'/'.$4;
4357: }
4358: if (wantarray) {
4359: return ($type,$udom,$unum,$file_name,$group);
4360: }
4361: return $type;
4362: }
4363:
4364: sub is_portfolio_url {
4365: my ($url) = @_;
4366: return scalar(&parse_portfolio_url($url));
4367: }
4368:
4369: sub is_portfolio_file {
4370: my ($file) = @_;
4371: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
4372: return 1;
4373: }
4374: return;
4375: }
4376:
4377: sub usertools_access {
4378: my ($uname,$udom,$tool,$action) = @_;
4379: my $access;
4380: my %tools = (
4381: aboutme => 1,
4382: blog => 1,
4383: portfolio => 1,
4384: );
4385: return if (!defined($tools{$tool}));
4386:
4387: if ((!defined($udom)) || (!defined($uname))) {
4388: $udom = $env{'user.domain'};
4389: $uname = $env{'user.name'};
4390: }
4391:
4392: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4393: if ($action ne 'reload') {
4394: return $env{'environment.availabletools.'.$tool};
4395: }
4396: }
4397:
4398: my ($toolstatus,$inststatus);
4399:
4400: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
4401: $toolstatus = $env{'environment.tools.'.$tool};
4402: $inststatus = $env{'environment.inststatus'};
4403: } else {
4404: my %userenv = &userenvironment($udom,$uname,'tools.'.$tool);
4405: $toolstatus = $userenv{'tools.'.$tool};
4406: $inststatus = $userenv{'inststatus'};
4407: }
4408:
4409: if ($toolstatus ne '') {
4410: if ($toolstatus) {
4411: $access = 1;
4412: } else {
4413: $access = 0;
4414: }
4415: return $access;
4416: }
4417:
4418: my $is_adv = &is_advanced_user($udom,$uname);
4419: my %domdef = &get_domain_defaults($udom);
4420: if (ref($domdef{$tool}) eq 'HASH') {
4421: if ($is_adv) {
4422: if ($domdef{$tool}{'_LC_adv'} ne '') {
4423: if ($domdef{$tool}{'_LC_adv'}) {
4424: $access = 1;
4425: } else {
4426: $access = 0;
4427: }
4428: return $access;
4429: }
4430: }
4431: if ($inststatus ne '') {
4432: my ($hasaccess,$hasnoaccess);
4433: foreach my $affiliation (split(/:/,$inststatus)) {
4434: if ($domdef{$tool}{$affiliation} ne '') {
4435: if ($domdef{$tool}{$affiliation}) {
4436: $hasaccess = 1;
4437: } else {
4438: $hasnoaccess = 1;
4439: }
4440: }
4441: }
4442: if ($hasaccess || $hasnoaccess) {
4443: if ($hasaccess) {
4444: $access = 1;
4445: } elsif ($hasnoaccess) {
4446: $access = 0;
4447: }
4448: return $access;
4449: }
4450: } else {
4451: if ($domdef{$tool}{'default'} ne '') {
4452: if ($domdef{$tool}{'default'}) {
4453: $access = 1;
4454: } elsif ($domdef{$tool}{'default'} == 0) {
4455: $access = 0;
4456: }
4457: return $access;
4458: }
4459: }
4460: } else {
4461: $access = 1;
4462: return $access;
4463: }
4464: }
4465:
4466: sub is_advanced_user {
4467: my ($udom,$uname) = @_;
4468: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
4469: my %allroles;
4470: my $is_adv;
4471: foreach my $role (keys(%roleshash)) {
4472: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
4473: my $area = '/'.$tdomain.'/'.$trest;
4474: if ($sec ne '') {
4475: $area .= '/'.$sec;
4476: }
4477: if (($area ne '') && ($trole ne '')) {
4478: my $spec=$trole.'.'.$area;
4479: if ($trole =~ /^cr\//) {
4480: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4481: } elsif ($trole ne 'gr') {
4482: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4483: }
4484: }
4485: }
4486: foreach my $role (keys(%allroles)) {
4487: last if ($is_adv);
4488: foreach my $item (split(/:/,$allroles{$role})) {
4489: if ($item ne '') {
4490: my ($privilege,$restrictions)=split(/&/,$item);
4491: if ($privilege eq 'adv') {
4492: $is_adv = 1;
4493: last;
4494: }
4495: }
4496: }
4497: }
4498: return $is_adv;
4499: }
4500:
4501: # ---------------------------------------------- Custom access rule evaluation
4502:
4503: sub customaccess {
4504: my ($priv,$uri)=@_;
4505: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
4506: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
4507: $udom = &LONCAPA::clean_domain($udom);
4508: $ucrs = &LONCAPA::clean_username($ucrs);
4509: my $access=0;
4510: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
4511: my ($effect,$realm,$role,$type)=split(/\:/,$right);
4512: if ($type eq 'user') {
4513: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4514: my ($tdom,$tuname)=split(m{/},$scope);
4515: if ($tdom) {
4516: if ($tdom ne $env{'user.domain'}) { next; }
4517: }
4518: if ($tuname) {
4519: if ($tuname ne $env{'user.name'}) { next; }
4520: }
4521: $access=($effect eq 'allow');
4522: last;
4523: }
4524: } else {
4525: if ($role) {
4526: if ($role ne $urole) { next; }
4527: }
4528: foreach my $scope (split(/\s*\,\s*/,$realm)) {
4529: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
4530: if ($tdom) {
4531: if ($tdom ne $udom) { next; }
4532: }
4533: if ($tcrs) {
4534: if ($tcrs ne $ucrs) { next; }
4535: }
4536: if ($tsec) {
4537: if ($tsec ne $usec) { next; }
4538: }
4539: $access=($effect eq 'allow');
4540: last;
4541: }
4542: if ($realm eq '' && $role eq '') {
4543: $access=($effect eq 'allow');
4544: }
4545: }
4546: }
4547: return $access;
4548: }
4549:
4550: # ------------------------------------------------- Check for a user privilege
4551:
4552: sub allowed {
4553: my ($priv,$uri,$symb,$role)=@_;
4554: my $ver_orguri=$uri;
4555: $uri=&deversion($uri);
4556: my $orguri=$uri;
4557: $uri=&declutter($uri);
4558:
4559: if ($priv eq 'evb') {
4560: # Evade communication block restrictions for specified role in a course
4561: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
4562: return $1;
4563: } else {
4564: return;
4565: }
4566: }
4567:
4568: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
4569: # Free bre access to adm and meta resources
4570: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
4571: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
4572: && ($priv eq 'bre')) {
4573: return 'F';
4574: }
4575:
4576: # Free bre access to user's own portfolio contents
4577: my ($space,$domain,$name,@dir)=split('/',$uri);
4578: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
4579: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
4580: my %setters;
4581: my ($startblock,$endblock) =
4582: &Apache::loncommon::blockcheck(\%setters,'port');
4583: if ($startblock && $endblock) {
4584: return 'B';
4585: } else {
4586: return 'F';
4587: }
4588: }
4589:
4590: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
4591: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
4592: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
4593: if (exists($env{'request.course.id'})) {
4594: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
4595: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
4596: if (($domain eq $cdom) && ($name eq $cnum)) {
4597: my $courseprivid=$env{'request.course.id'};
4598: $courseprivid=~s/\_/\//;
4599: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
4600: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
4601: return $1;
4602: } else {
4603: if ($env{'request.course.sec'}) {
4604: $courseprivid.='/'.$env{'request.course.sec'};
4605: }
4606: if ($env{'user.priv.'.$env{'request.role'}.'./'.
4607: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
4608: return $2;
4609: }
4610: }
4611: }
4612: }
4613: }
4614:
4615: # Free bre to public access
4616:
4617: if ($priv eq 'bre') {
4618: my $copyright=&metadata($uri,'copyright');
4619: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
4620: return 'F';
4621: }
4622: if ($copyright eq 'priv') {
4623: $uri=~/([^\/]+)\/([^\/]+)\//;
4624: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
4625: return '';
4626: }
4627: }
4628: if ($copyright eq 'domain') {
4629: $uri=~/([^\/]+)\/([^\/]+)\//;
4630: unless (($env{'user.domain'} eq $1) ||
4631: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
4632: return '';
4633: }
4634: }
4635: if ($env{'request.role'}=~ /li\.\//) {
4636: # Library role, so allow browsing of resources in this domain.
4637: return 'F';
4638: }
4639: if ($copyright eq 'custom') {
4640: unless (&customaccess($priv,$uri)) { return ''; }
4641: }
4642: }
4643: # Domain coordinator is trying to create a course
4644: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
4645: # uri is the requested domain in this case.
4646: # comparison to 'request.role.domain' shows if the user has selected
4647: # a role of dc for the domain in question.
4648: return 'F' if ($uri eq $env{'request.role.domain'});
4649: }
4650:
4651: my $thisallowed='';
4652: my $statecond=0;
4653: my $courseprivid='';
4654:
4655: # Course
4656:
4657: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
4658: $thisallowed.=$1;
4659: }
4660:
4661: # Domain
4662:
4663: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
4664: =~/\Q$priv\E\&([^\:]*)/) {
4665: $thisallowed.=$1;
4666: }
4667:
4668: # Course: uri itself is a course
4669: my $courseuri=$uri;
4670: $courseuri=~s/\_(\d)/\/$1/;
4671: $courseuri=~s/^([^\/])/\/$1/;
4672:
4673: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
4674: =~/\Q$priv\E\&([^\:]*)/) {
4675: $thisallowed.=$1;
4676: }
4677:
4678: # URI is an uploaded document for this course, default permissions don't matter
4679: # not allowing 'edit' access (editupload) to uploaded course docs
4680: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
4681: $thisallowed='';
4682: my ($match)=&is_on_map($uri);
4683: if ($match) {
4684: if ($env{'user.priv.'.$env{'request.role'}.'./'}
4685: =~/\Q$priv\E\&([^\:]*)/) {
4686: $thisallowed.=$1;
4687: }
4688: } else {
4689: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
4690: if ($refuri) {
4691: if ($refuri =~ m|^/adm/|) {
4692: $thisallowed='F';
4693: } else {
4694: $refuri=&declutter($refuri);
4695: my ($match) = &is_on_map($refuri);
4696: if ($match) {
4697: $thisallowed='F';
4698: }
4699: }
4700: }
4701: }
4702: }
4703:
4704: if ($priv eq 'bre'
4705: && $thisallowed ne 'F'
4706: && $thisallowed ne '2'
4707: && &is_portfolio_url($uri)) {
4708: $thisallowed = &portfolio_access($uri);
4709: }
4710:
4711: # Full access at system, domain or course-wide level? Exit.
4712: if ($thisallowed=~/F/) {
4713: return 'F';
4714: }
4715:
4716: # If this is generating or modifying users, exit with special codes
4717:
4718: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
4719: if (($priv eq 'cca') || ($priv eq 'caa')) {
4720: my ($audom,$auname)=split('/',$uri);
4721: # no author name given, so this just checks on the general right to make a co-author in this domain
4722: unless ($auname) { return $thisallowed; }
4723: # an author name is given, so we are about to actually make a co-author for a certain account
4724: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
4725: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
4726: ($audom ne $env{'request.role.domain'}))) { return ''; }
4727: }
4728: return $thisallowed;
4729: }
4730: #
4731: # Gathered so far: system, domain and course wide privileges
4732: #
4733: # Course: See if uri or referer is an individual resource that is part of
4734: # the course
4735:
4736: if ($env{'request.course.id'}) {
4737:
4738: $courseprivid=$env{'request.course.id'};
4739: if ($env{'request.course.sec'}) {
4740: $courseprivid.='/'.$env{'request.course.sec'};
4741: }
4742: $courseprivid=~s/\_/\//;
4743: my $checkreferer=1;
4744: my ($match,$cond)=&is_on_map($uri);
4745: if ($match) {
4746: $statecond=$cond;
4747: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
4748: =~/\Q$priv\E\&([^\:]*)/) {
4749: $thisallowed.=$1;
4750: $checkreferer=0;
4751: }
4752: }
4753:
4754: if ($checkreferer) {
4755: my $refuri=$env{'httpref.'.$orguri};
4756: unless ($refuri) {
4757: foreach my $key (keys(%env)) {
4758: if ($key=~/^httpref\..*\*/) {
4759: my $pattern=$key;
4760: $pattern=~s/^httpref\.\/res\///;
4761: $pattern=~s/\*/\[\^\/\]\+/g;
4762: $pattern=~s/\//\\\//g;
4763: if ($orguri=~/$pattern/) {
4764: $refuri=$env{$key};
4765: }
4766: }
4767: }
4768: }
4769:
4770: if ($refuri) {
4771: $refuri=&declutter($refuri);
4772: my ($match,$cond)=&is_on_map($refuri);
4773: if ($match) {
4774: my $refstatecond=$cond;
4775: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
4776: =~/\Q$priv\E\&([^\:]*)/) {
4777: $thisallowed.=$1;
4778: $uri=$refuri;
4779: $statecond=$refstatecond;
4780: }
4781: }
4782: }
4783: }
4784: }
4785:
4786: #
4787: # Gathered now: all privileges that could apply, and condition number
4788: #
4789: #
4790: # Full or no access?
4791: #
4792:
4793: if ($thisallowed=~/F/) {
4794: return 'F';
4795: }
4796:
4797: unless ($thisallowed) {
4798: return '';
4799: }
4800:
4801: # Restrictions exist, deal with them
4802: #
4803: # C:according to course preferences
4804: # R:according to resource settings
4805: # L:unless locked
4806: # X:according to user session state
4807: #
4808:
4809: # Possibly locked functionality, check all courses
4810: # Locks might take effect only after 10 minutes cache expiration for other
4811: # courses, and 2 minutes for current course
4812:
4813: my $envkey;
4814: if ($thisallowed=~/L/) {
4815: foreach $envkey (keys %env) {
4816: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
4817: my $courseid=$2;
4818: my $roleid=$1.'.'.$2;
4819: $courseid=~s/^\///;
4820: my $expiretime=600;
4821: if ($env{'request.role'} eq $roleid) {
4822: $expiretime=120;
4823: }
4824: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
4825: my $prefix='course.'.$cdom.'_'.$cnum.'.';
4826: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
4827: &coursedescription($courseid,{'freshen_cache' => 1});
4828: }
4829: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
4830: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
4831: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
4832: &log($env{'user.domain'},$env{'user.name'},
4833: $env{'user.home'},
4834: 'Locked by res: '.$priv.' for '.$uri.' due to '.
4835: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4836: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4837: return '';
4838: }
4839: }
4840: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
4841: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
4842: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
4843: &log($env{'user.domain'},$env{'user.name'},
4844: $env{'user.home'},
4845: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
4846: $cdom.'/'.$cnum.'/'.$csec.' expire '.
4847: $env{$prefix.'priv.'.$priv.'.lock.expire'});
4848: return '';
4849: }
4850: }
4851: }
4852: }
4853: }
4854:
4855: #
4856: # Rest of the restrictions depend on selected course
4857: #
4858:
4859: unless ($env{'request.course.id'}) {
4860: if ($thisallowed eq 'A') {
4861: return 'A';
4862: } elsif ($thisallowed eq 'B') {
4863: return 'B';
4864: } else {
4865: return '1';
4866: }
4867: }
4868:
4869: #
4870: # Now user is definitely in a course
4871: #
4872:
4873:
4874: # Course preferences
4875:
4876: if ($thisallowed=~/C/) {
4877: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4878: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
4879: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
4880: =~/\Q$rolecode\E/) {
4881: if ($priv ne 'pch') {
4882: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4883: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
4884: $env{'request.course.id'});
4885: }
4886: return '';
4887: }
4888:
4889: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
4890: =~/\Q$unamedom\E/) {
4891: if ($priv ne 'pch') {
4892: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
4893: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
4894: $env{'request.course.id'});
4895: }
4896: return '';
4897: }
4898: }
4899:
4900: # Resource preferences
4901:
4902: if ($thisallowed=~/R/) {
4903: my $rolecode=(split(/\./,$env{'request.role'}))[0];
4904: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
4905: if ($priv ne 'pch') {
4906: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
4907: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
4908: }
4909: return '';
4910: }
4911: }
4912:
4913: # Restricted by state or randomout?
4914:
4915: if ($thisallowed=~/X/) {
4916: if ($env{'acc.randomout'}) {
4917: if (!$symb) { $symb=&symbread($uri,1); }
4918: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
4919: return '';
4920: }
4921: }
4922: if (&condval($statecond)) {
4923: return '2';
4924: } else {
4925: return '';
4926: }
4927: }
4928:
4929: if ($thisallowed eq 'A') {
4930: return 'A';
4931: } elsif ($thisallowed eq 'B') {
4932: return 'B';
4933: }
4934: return 'F';
4935: }
4936:
4937: sub split_uri_for_cond {
4938: my $uri=&deversion(&declutter(shift));
4939: my @uriparts=split(/\//,$uri);
4940: my $filename=pop(@uriparts);
4941: my $pathname=join('/',@uriparts);
4942: return ($pathname,$filename);
4943: }
4944: # --------------------------------------------------- Is a resource on the map?
4945:
4946: sub is_on_map {
4947: my ($pathname,$filename) = &split_uri_for_cond(shift);
4948: #Trying to find the conditional for the file
4949: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
4950: /\&\Q$filename\E\:([\d\|]+)\&/);
4951: if ($match) {
4952: return (1,$1);
4953: } else {
4954: return (0,0);
4955: }
4956: }
4957:
4958: # --------------------------------------------------------- Get symb from alias
4959:
4960: sub get_symb_from_alias {
4961: my $symb=shift;
4962: my ($map,$resid,$url)=&decode_symb($symb);
4963: # Already is a symb
4964: if ($url) { return $symb; }
4965: # Must be an alias
4966: my $aliassymb='';
4967: my %bighash;
4968: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
4969: &GDBM_READER(),0640)) {
4970: my $rid=$bighash{'mapalias_'.$symb};
4971: if ($rid) {
4972: my ($mapid,$resid)=split(/\./,$rid);
4973: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
4974: $resid,$bighash{'src_'.$rid});
4975: }
4976: untie %bighash;
4977: }
4978: return $aliassymb;
4979: }
4980:
4981: # ----------------------------------------------------------------- Define Role
4982:
4983: sub definerole {
4984: if (allowed('mcr','/')) {
4985: my ($rolename,$sysrole,$domrole,$courole)=@_;
4986: foreach my $role (split(':',$sysrole)) {
4987: my ($crole,$cqual)=split(/\&/,$role);
4988: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
4989: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
4990: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
4991: return "refused:s:$crole&$cqual";
4992: }
4993: }
4994: }
4995: foreach my $role (split(':',$domrole)) {
4996: my ($crole,$cqual)=split(/\&/,$role);
4997: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
4998: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
4999: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
5000: return "refused:d:$crole&$cqual";
5001: }
5002: }
5003: }
5004: foreach my $role (split(':',$courole)) {
5005: my ($crole,$cqual)=split(/\&/,$role);
5006: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
5007: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
5008: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
5009: return "refused:c:$crole&$cqual";
5010: }
5011: }
5012: }
5013: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5014: "$env{'user.domain'}:$env{'user.name'}:".
5015: "rolesdef_$rolename=".
5016: escape($sysrole.'_'.$domrole.'_'.$courole);
5017: return reply($command,$env{'user.home'});
5018: } else {
5019: return 'refused';
5020: }
5021: }
5022:
5023: # ---------------- Make a metadata query against the network of library servers
5024:
5025: sub metadata_query {
5026: my ($query,$custom,$customshow,$server_array)=@_;
5027: my %rhash;
5028: my %libserv = &all_library();
5029: my @server_list = (defined($server_array) ? @$server_array
5030: : keys(%libserv) );
5031: for my $server (@server_list) {
5032: unless ($custom or $customshow) {
5033: my $reply=&reply("querysend:".&escape($query),$server);
5034: $rhash{$server}=$reply;
5035: }
5036: else {
5037: my $reply=&reply("querysend:".&escape($query).':'.
5038: &escape($custom).':'.&escape($customshow),
5039: $server);
5040: $rhash{$server}=$reply;
5041: }
5042: }
5043: return \%rhash;
5044: }
5045:
5046: # ----------------------------------------- Send log queries and wait for reply
5047:
5048: sub log_query {
5049: my ($uname,$udom,$query,%filters)=@_;
5050: my $uhome=&homeserver($uname,$udom);
5051: if ($uhome eq 'no_host') { return 'error: no_host'; }
5052: my $uhost=&hostname($uhome);
5053: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
5054: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
5055: $uhome);
5056: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
5057: return get_query_reply($queryid);
5058: }
5059:
5060: # -------------------------- Update MySQL table for portfolio file
5061:
5062: sub update_portfolio_table {
5063: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
5064: if ($group ne '') {
5065: $file_name =~s /^\Q$group\E//;
5066: }
5067: my $homeserver = &homeserver($uname,$udom);
5068: my $queryid=
5069: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
5070: ':'.&escape($file_name).':'.$action,$homeserver);
5071: my $reply = &get_query_reply($queryid);
5072: return $reply;
5073: }
5074:
5075: # -------------------------- Update MySQL allusers table
5076:
5077: sub update_allusers_table {
5078: my ($uname,$udom,$names) = @_;
5079: my $homeserver = &homeserver($uname,$udom);
5080: my $queryid=
5081: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
5082: 'lastname='.&escape($names->{'lastname'}).'%%'.
5083: 'firstname='.&escape($names->{'firstname'}).'%%'.
5084: 'middlename='.&escape($names->{'middlename'}).'%%'.
5085: 'generation='.&escape($names->{'generation'}).'%%'.
5086: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
5087: 'id='.&escape($names->{'id'}),$homeserver);
5088: my $reply = &get_query_reply($queryid);
5089: return $reply;
5090: }
5091:
5092: # ------- Request retrieval of institutional classlists for course(s)
5093:
5094: sub fetch_enrollment_query {
5095: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
5096: my $homeserver;
5097: my $maxtries = 1;
5098: if ($context eq 'automated') {
5099: $homeserver = $perlvar{'lonHostID'};
5100: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
5101: } else {
5102: $homeserver = &homeserver($cnum,$dom);
5103: }
5104: my $host=&hostname($homeserver);
5105: my $cmd = '';
5106: foreach my $affiliate (keys %{$affiliatesref}) {
5107: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5108: }
5109: $cmd =~ s/%%$//;
5110: $cmd = &escape($cmd);
5111: my $query = 'fetchenrollment';
5112: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
5113: unless ($queryid=~/^\Q$host\E\_/) {
5114: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
5115: return 'error: '.$queryid;
5116: }
5117: my $reply = &get_query_reply($queryid);
5118: my $tries = 1;
5119: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5120: $reply = &get_query_reply($queryid);
5121: $tries ++;
5122: }
5123: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5124: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5125: } else {
5126: my @responses = split(/:/,$reply);
5127: if ($homeserver eq $perlvar{'lonHostID'}) {
5128: foreach my $line (@responses) {
5129: my ($key,$value) = split(/=/,$line,2);
5130: $$replyref{$key} = $value;
5131: }
5132: } else {
5133: my $pathname = $perlvar{'lonDaemons'}.'/tmp';
5134: foreach my $line (@responses) {
5135: my ($key,$value) = split(/=/,$line);
5136: $$replyref{$key} = $value;
5137: if ($value > 0) {
5138: foreach my $item (@{$$affiliatesref{$key}}) {
5139: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
5140: my $destname = $pathname.'/'.$filename;
5141: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
5142: if ($xml_classlist =~ /^error/) {
5143: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
5144: } else {
5145: if ( open(FILE,">$destname") ) {
5146: print FILE &unescape($xml_classlist);
5147: close(FILE);
5148: } else {
5149: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
5150: }
5151: }
5152: }
5153: }
5154: }
5155: }
5156: return 'ok';
5157: }
5158: return 'error';
5159: }
5160:
5161: sub get_query_reply {
5162: my $queryid=shift;
5163: my $replyfile=$perlvar{'lonDaemons'}.'/tmp/'.$queryid;
5164: my $reply='';
5165: for (1..100) {
5166: sleep 2;
5167: if (-e $replyfile.'.end') {
5168: if (open(my $fh,$replyfile)) {
5169: $reply = join('',<$fh>);
5170: close($fh);
5171: } else { return 'error: reply_file_error'; }
5172: return &unescape($reply);
5173: }
5174: }
5175: return 'timeout:'.$queryid;
5176: }
5177:
5178: sub courselog_query {
5179: #
5180: # possible filters:
5181: # url: url or symb
5182: # username
5183: # domain
5184: # action: view, submit, grade
5185: # start: timestamp
5186: # end: timestamp
5187: #
5188: my (%filters)=@_;
5189: unless ($env{'request.course.id'}) { return 'no_course'; }
5190: if ($filters{'url'}) {
5191: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
5192: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
5193: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
5194: }
5195: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
5196: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
5197: return &log_query($cname,$cdom,'courselog',%filters);
5198: }
5199:
5200: sub userlog_query {
5201: #
5202: # possible filters:
5203: # action: log check role
5204: # start: timestamp
5205: # end: timestamp
5206: #
5207: my ($uname,$udom,%filters)=@_;
5208: return &log_query($uname,$udom,'userlog',%filters);
5209: }
5210:
5211: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
5212:
5213: sub auto_run {
5214: my ($cnum,$cdom) = @_;
5215: my $response = 0;
5216: my $settings;
5217: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
5218: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
5219: $settings = $domconfig{'autoenroll'};
5220: if ($settings->{'run'} eq '1') {
5221: $response = 1;
5222: }
5223: } else {
5224: my $homeserver;
5225: if (&is_course($cdom,$cnum)) {
5226: $homeserver = &homeserver($cnum,$cdom);
5227: } else {
5228: $homeserver = &domain($cdom,'primary');
5229: }
5230: if ($homeserver ne 'no_host') {
5231: $response = &reply('autorun:'.$cdom,$homeserver);
5232: }
5233: }
5234: return $response;
5235: }
5236:
5237: sub auto_get_sections {
5238: my ($cnum,$cdom,$inst_coursecode) = @_;
5239: my $homeserver = &homeserver($cnum,$cdom);
5240: my @secs = ();
5241: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
5242: unless ($response eq 'refused') {
5243: @secs = split(/:/,$response);
5244: }
5245: return @secs;
5246: }
5247:
5248: sub auto_new_course {
5249: my ($cnum,$cdom,$inst_course_id,$owner) = @_;
5250: my $homeserver = &homeserver($cnum,$cdom);
5251: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.$owner.':'.$cdom,$homeserver));
5252: return $response;
5253: }
5254:
5255: sub auto_validate_courseID {
5256: my ($cnum,$cdom,$inst_course_id) = @_;
5257: my $homeserver = &homeserver($cnum,$cdom);
5258: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
5259: return $response;
5260: }
5261:
5262: sub auto_create_password {
5263: my ($cnum,$cdom,$authparam,$udom) = @_;
5264: my ($homeserver,$response);
5265: my $create_passwd = 0;
5266: my $authchk = '';
5267: if ($udom =~ /^$match_domain$/) {
5268: $homeserver = &domain($udom,'primary');
5269: }
5270: if ($homeserver eq '') {
5271: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
5272: $homeserver = &homeserver($cnum,$cdom);
5273: }
5274: }
5275: if ($homeserver eq '') {
5276: $authchk = 'nodomain';
5277: } else {
5278: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
5279: if ($response eq 'refused') {
5280: $authchk = 'refused';
5281: } else {
5282: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
5283: }
5284: }
5285: return ($authparam,$create_passwd,$authchk);
5286: }
5287:
5288: sub auto_photo_permission {
5289: my ($cnum,$cdom,$students) = @_;
5290: my $homeserver = &homeserver($cnum,$cdom);
5291: my ($outcome,$perm_reqd,$conditions) =
5292: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
5293: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5294: return (undef,undef);
5295: }
5296: return ($outcome,$perm_reqd,$conditions);
5297: }
5298:
5299: sub auto_checkphotos {
5300: my ($uname,$udom,$pid) = @_;
5301: my $homeserver = &homeserver($uname,$udom);
5302: my ($result,$resulttype);
5303: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
5304: &escape($uname).':'.&escape($pid),
5305: $homeserver));
5306: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5307: return (undef,undef);
5308: }
5309: if ($outcome) {
5310: ($result,$resulttype) = split(/:/,$outcome);
5311: }
5312: return ($result,$resulttype);
5313: }
5314:
5315: sub auto_photochoice {
5316: my ($cnum,$cdom) = @_;
5317: my $homeserver = &homeserver($cnum,$cdom);
5318: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
5319: &escape($cdom),
5320: $homeserver)));
5321: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
5322: return (undef,undef);
5323: }
5324: return ($update,$comment);
5325: }
5326:
5327: sub auto_photoupdate {
5328: my ($affiliatesref,$dom,$cnum,$photo) = @_;
5329: my $homeserver = &homeserver($cnum,$dom);
5330: my $host=&hostname($homeserver);
5331: my $cmd = '';
5332: my $maxtries = 1;
5333: foreach my $affiliate (keys(%{$affiliatesref})) {
5334: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
5335: }
5336: $cmd =~ s/%%$//;
5337: $cmd = &escape($cmd);
5338: my $query = 'institutionalphotos';
5339: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
5340: unless ($queryid=~/^\Q$host\E\_/) {
5341: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
5342: return 'error: '.$queryid;
5343: }
5344: my $reply = &get_query_reply($queryid);
5345: my $tries = 1;
5346: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
5347: $reply = &get_query_reply($queryid);
5348: $tries ++;
5349: }
5350: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
5351: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
5352: } else {
5353: my @responses = split(/:/,$reply);
5354: my $outcome = shift(@responses);
5355: foreach my $item (@responses) {
5356: my ($key,$value) = split(/=/,$item);
5357: $$photo{$key} = $value;
5358: }
5359: return $outcome;
5360: }
5361: return 'error';
5362: }
5363:
5364: sub auto_instcode_format {
5365: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
5366: $cat_order) = @_;
5367: my $courses = '';
5368: my @homeservers;
5369: if ($caller eq 'global') {
5370: my %servers = &get_servers($codedom,'library');
5371: foreach my $tryserver (keys(%servers)) {
5372: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5373: push(@homeservers,$tryserver);
5374: }
5375: }
5376: } else {
5377: push(@homeservers,&homeserver($caller,$codedom));
5378: }
5379: foreach my $code (keys(%{$instcodes})) {
5380: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
5381: }
5382: chop($courses);
5383: my $ok_response = 0;
5384: my $response;
5385: while (@homeservers > 0 && $ok_response == 0) {
5386: my $server = shift(@homeservers);
5387: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
5388: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
5389: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
5390: split(/:/,$response);
5391: %{$codes} = (%{$codes},&str2hash($codes_str));
5392: push(@{$codetitles},&str2array($codetitles_str));
5393: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
5394: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
5395: $ok_response = 1;
5396: }
5397: }
5398: if ($ok_response) {
5399: return 'ok';
5400: } else {
5401: return $response;
5402: }
5403: }
5404:
5405: sub auto_instcode_defaults {
5406: my ($domain,$returnhash,$code_order) = @_;
5407: my @homeservers;
5408:
5409: my %servers = &get_servers($domain,'library');
5410: foreach my $tryserver (keys(%servers)) {
5411: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
5412: push(@homeservers,$tryserver);
5413: }
5414: }
5415:
5416: my $response;
5417: foreach my $server (@homeservers) {
5418: $response=&reply('autoinstcodedefaults:'.$domain,$server);
5419: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
5420:
5421: foreach my $pair (split(/\&/,$response)) {
5422: my ($name,$value)=split(/\=/,$pair);
5423: if ($name eq 'code_order') {
5424: @{$code_order} = split(/\&/,&unescape($value));
5425: } else {
5426: $returnhash->{&unescape($name)}=&unescape($value);
5427: }
5428: }
5429: return 'ok';
5430: }
5431:
5432: return $response;
5433: }
5434:
5435: sub auto_validate_class_sec {
5436: my ($cdom,$cnum,$owners,$inst_class) = @_;
5437: my $homeserver = &homeserver($cnum,$cdom);
5438: my $ownerlist;
5439: if (ref($owners) eq 'ARRAY') {
5440: $ownerlist = join(',',@{$owners});
5441: } else {
5442: $ownerlist = $owners;
5443: }
5444: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
5445: &escape($ownerlist).':'.$cdom,$homeserver);
5446: return $response;
5447: }
5448:
5449: # ------------------------------------------------------- Course Group routines
5450:
5451: sub get_coursegroups {
5452: my ($cdom,$cnum,$group,$namespace) = @_;
5453: return(&dump($namespace,$cdom,$cnum,$group));
5454: }
5455:
5456: sub modify_coursegroup {
5457: my ($cdom,$cnum,$groupsettings) = @_;
5458: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
5459: }
5460:
5461: sub toggle_coursegroup_status {
5462: my ($cdom,$cnum,$group,$action) = @_;
5463: my ($from_namespace,$to_namespace);
5464: if ($action eq 'delete') {
5465: $from_namespace = 'coursegroups';
5466: $to_namespace = 'deleted_groups';
5467: } else {
5468: $from_namespace = 'deleted_groups';
5469: $to_namespace = 'coursegroups';
5470: }
5471: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
5472: if (my $tmp = &error(%curr_group)) {
5473: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
5474: return ('read error',$tmp);
5475: } else {
5476: my %savedsettings = %curr_group;
5477: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
5478: my $deloutcome;
5479: if ($result eq 'ok') {
5480: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
5481: } else {
5482: return ('write error',$result);
5483: }
5484: if ($deloutcome eq 'ok') {
5485: return 'ok';
5486: } else {
5487: return ('delete error',$deloutcome);
5488: }
5489: }
5490: }
5491:
5492: sub modify_group_roles {
5493: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
5494: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
5495: my $role = 'gr/'.&escape($userprivs);
5496: my ($uname,$udom) = split(/:/,$user);
5497: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
5498: if ($result eq 'ok') {
5499: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
5500: }
5501: return $result;
5502: }
5503:
5504: sub modify_coursegroup_membership {
5505: my ($cdom,$cnum,$membership) = @_;
5506: my $result = &put('groupmembership',$membership,$cdom,$cnum);
5507: return $result;
5508: }
5509:
5510: sub get_active_groups {
5511: my ($udom,$uname,$cdom,$cnum) = @_;
5512: my $now = time;
5513: my %groups = ();
5514: foreach my $key (keys(%env)) {
5515: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
5516: my ($start,$end) = split(/\./,$env{$key});
5517: if (($end!=0) && ($end<$now)) { next; }
5518: if (($start!=0) && ($start>$now)) { next; }
5519: if ($1 eq $cdom && $2 eq $cnum) {
5520: $groups{$3} = $env{$key} ;
5521: }
5522: }
5523: }
5524: return %groups;
5525: }
5526:
5527: sub get_group_membership {
5528: my ($cdom,$cnum,$group) = @_;
5529: return(&dump('groupmembership',$cdom,$cnum,$group));
5530: }
5531:
5532: sub get_users_groups {
5533: my ($udom,$uname,$courseid) = @_;
5534: my @usersgroups;
5535: my $cachetime=1800;
5536:
5537: my $hashid="$udom:$uname:$courseid";
5538: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
5539: if (defined($cached)) {
5540: @usersgroups = split(/:/,$grouplist);
5541: } else {
5542: $grouplist = '';
5543: my $courseurl = &courseid_to_courseurl($courseid);
5544: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
5545: my $access_end = $env{'course.'.$courseid.
5546: '.default_enrollment_end_date'};
5547: my $now = time;
5548: foreach my $key (keys(%roleshash)) {
5549: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
5550: my $group = $1;
5551: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
5552: my $start = $2;
5553: my $end = $1;
5554: if ($start == -1) { next; } # deleted from group
5555: if (($start!=0) && ($start>$now)) { next; }
5556: if (($end!=0) && ($end<$now)) {
5557: if ($access_end && $access_end < $now) {
5558: if ($access_end - $end < 86400) {
5559: push(@usersgroups,$group);
5560: }
5561: }
5562: next;
5563: }
5564: push(@usersgroups,$group);
5565: }
5566: }
5567: }
5568: @usersgroups = &sort_course_groups($courseid,@usersgroups);
5569: $grouplist = join(':',@usersgroups);
5570: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
5571: }
5572: return @usersgroups;
5573: }
5574:
5575: sub devalidate_getgroups_cache {
5576: my ($udom,$uname,$cdom,$cnum)=@_;
5577: my $courseid = $cdom.'_'.$cnum;
5578:
5579: my $hashid="$udom:$uname:$courseid";
5580: &devalidate_cache_new('getgroups',$hashid);
5581: }
5582:
5583: # ------------------------------------------------------------------ Plain Text
5584:
5585: sub plaintext {
5586: my ($short,$type,$cid) = @_;
5587: if ($short =~ /^cr/) {
5588: return (split('/',$short))[-1];
5589: }
5590: if (!defined($cid)) {
5591: $cid = $env{'request.course.id'};
5592: }
5593: if (defined($cid) && defined($env{'course.'.$cid.'.'.$short.'.plaintext'})) {
5594: return &Apache::lonlocal::mt($env{'course.'.$cid.'.'.$short.
5595: '.plaintext'});
5596: }
5597: my %rolenames = (
5598: Course => 'std',
5599: Group => 'alt1',
5600: );
5601: if (defined($type) &&
5602: defined($rolenames{$type}) &&
5603: defined($prp{$short}{$rolenames{$type}})) {
5604: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
5605: } else {
5606: return &Apache::lonlocal::mt($prp{$short}{'std'});
5607: }
5608: }
5609:
5610: # ----------------------------------------------------------------- Assign Role
5611:
5612: sub assignrole {
5613: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
5614: $context)=@_;
5615: my $mrole;
5616: if ($role =~ /^cr\//) {
5617: my $cwosec=$url;
5618: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
5619: unless (&allowed('ccr',$cwosec)) {
5620: &logthis('Refused custom assignrole: '.
5621: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5622: $env{'user.name'}.' at '.$env{'user.domain'});
5623: return 'refused';
5624: }
5625: $mrole='cr';
5626: } elsif ($role =~ /^gr\//) {
5627: my $cwogrp=$url;
5628: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
5629: unless (&allowed('mdg',$cwogrp)) {
5630: &logthis('Refused group assignrole: '.
5631: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
5632: $env{'user.name'}.' at '.$env{'user.domain'});
5633: return 'refused';
5634: }
5635: $mrole='gr';
5636: } else {
5637: my $cwosec=$url;
5638: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
5639: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
5640: my $refused;
5641: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
5642: if (!(&allowed('c'.$role,$url))) {
5643: $refused = 1;
5644: }
5645: } else {
5646: $refused = 1;
5647: }
5648: if ($refused) {
5649: if (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5650: $refused = '';
5651: } else {
5652: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
5653: ' '.$role.' '.$end.' '.$start.' by '.
5654: $env{'user.name'}.' at '.$env{'user.domain'});
5655: return 'refused';
5656: }
5657: }
5658: }
5659: $mrole=$role;
5660: }
5661: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
5662: "$udom:$uname:$url".'_'."$mrole=$role";
5663: if ($end) { $command.='_'.$end; }
5664: if ($start) {
5665: if ($end) {
5666: $command.='_'.$start;
5667: } else {
5668: $command.='_0_'.$start;
5669: }
5670: }
5671: my $origstart = $start;
5672: my $origend = $end;
5673: my $delflag;
5674: # actually delete
5675: if ($deleteflag) {
5676: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
5677: # modify command to delete the role
5678: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
5679: "$udom:$uname:$url".'_'."$mrole";
5680: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
5681: # set start and finish to negative values for userrolelog
5682: $start=-1;
5683: $end=-1;
5684: $delflag = 1;
5685: }
5686: }
5687: # send command
5688: my $answer=&reply($command,&homeserver($uname,$udom));
5689: # log new user role if status is ok
5690: if ($answer eq 'ok') {
5691: &userrolelog($role,$uname,$udom,$url,$start,$end);
5692: # for course roles, perform group memberships changes triggered by role change.
5693: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
5694: unless ($role =~ /^gr/) {
5695: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
5696: $origstart,$selfenroll,$context);
5697: }
5698: }
5699: return $answer;
5700: }
5701:
5702: # -------------------------------------------------- Modify user authentication
5703: # Overrides without validation
5704:
5705: sub modifyuserauth {
5706: my ($udom,$uname,$umode,$upass)=@_;
5707: my $uhome=&homeserver($uname,$udom);
5708: unless (&allowed('mau',$udom)) { return 'refused'; }
5709: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
5710: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5711: ' in domain '.$env{'request.role.domain'});
5712: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
5713: &escape($upass),$uhome);
5714: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
5715: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
5716: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5717: &log($udom,,$uname,$uhome,
5718: 'Authentication changed by '.$env{'user.domain'}.', '.
5719: $env{'user.name'}.', '.$umode.
5720: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
5721: unless ($reply eq 'ok') {
5722: &logthis('Authentication mode error: '.$reply);
5723: return 'error: '.$reply;
5724: }
5725: return 'ok';
5726: }
5727:
5728: # --------------------------------------------------------------- Modify a user
5729:
5730: sub modifyuser {
5731: my ($udom, $uname, $uid,
5732: $umode, $upass, $first,
5733: $middle, $last, $gene,
5734: $forceid, $desiredhome, $email, $inststatus)=@_;
5735: $udom= &LONCAPA::clean_domain($udom);
5736: $uname=&LONCAPA::clean_username($uname);
5737: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
5738: $umode.', '.$first.', '.$middle.', '.
5739: $last.', '.$gene.'(forceid: '.$forceid.')'.
5740: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
5741: ' desiredhome not specified').
5742: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
5743: ' in domain '.$env{'request.role.domain'});
5744: my $uhome=&homeserver($uname,$udom,'true');
5745: # ----------------------------------------------------------------- Create User
5746: if (($uhome eq 'no_host') &&
5747: (($umode && $upass) || ($umode eq 'localauth'))) {
5748: my $unhome='';
5749: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
5750: $unhome = $desiredhome;
5751: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
5752: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
5753: } else { # load balancing routine for determining $unhome
5754: my $loadm=10000000;
5755: my %servers = &get_servers($udom,'library');
5756: foreach my $tryserver (keys(%servers)) {
5757: my $answer=reply('load',$tryserver);
5758: if (($answer=~/\d+/) && ($answer<$loadm)) {
5759: $loadm=$answer;
5760: $unhome=$tryserver;
5761: }
5762: }
5763: }
5764: if (($unhome eq '') || ($unhome eq 'no_host')) {
5765: return 'error: unable to find a home server for '.$uname.
5766: ' in domain '.$udom;
5767: }
5768: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
5769: &escape($upass),$unhome);
5770: unless ($reply eq 'ok') {
5771: return 'error: '.$reply;
5772: }
5773: $uhome=&homeserver($uname,$udom,'true');
5774: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
5775: return 'error: unable verify users home machine.';
5776: }
5777: } # End of creation of new user
5778: # ---------------------------------------------------------------------- Add ID
5779: if ($uid) {
5780: $uid=~tr/A-Z/a-z/;
5781: my %uidhash=&idrget($udom,$uname);
5782: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
5783: && (!$forceid)) {
5784: unless ($uid eq $uidhash{$uname}) {
5785: return 'error: user id "'.$uid.'" does not match '.
5786: 'current user id "'.$uidhash{$uname}.'".';
5787: }
5788: } else {
5789: &idput($udom,($uname => $uid));
5790: }
5791: }
5792: # -------------------------------------------------------------- Add names, etc
5793: my @tmp=&get('environment',
5794: ['firstname','middlename','lastname','generation','id',
5795: 'permanentemail','inststatus'],
5796: $udom,$uname);
5797: my %names;
5798: if ($tmp[0] =~ m/^error:.*/) {
5799: %names=();
5800: } else {
5801: %names = @tmp;
5802: }
5803: #
5804: # Make sure to not trash student environment if instructor does not bother
5805: # to supply name and email information
5806: #
5807: if ($first) { $names{'firstname'} = $first; }
5808: if (defined($middle)) { $names{'middlename'} = $middle; }
5809: if ($last) { $names{'lastname'} = $last; }
5810: if (defined($gene)) { $names{'generation'} = $gene; }
5811: if ($email) {
5812: $email=~s/[^\w\@\.\-\,]//gs;
5813: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
5814: }
5815: if ($uid) { $names{'id'} = $uid; }
5816: if (defined($inststatus)) { $names{'inststatus'} = $inststatus; }
5817: my $reply = &put('environment', \%names, $udom,$uname);
5818: if ($reply ne 'ok') { return 'error: '.$reply; }
5819: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
5820: &devalidate_cache_new('namescache',$uname.':'.$udom);
5821: my $logmsg = 'Success modifying user '.$udom.', '.$uname.', '.$uid.', '.
5822: $umode.', '.$first.', '.$middle.', '.
5823: $last.', '.$gene.', '.$email.', '.$inststatus;
5824: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
5825: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
5826: } else {
5827: $logmsg .= ' during self creation';
5828: }
5829: &logthis($logmsg);
5830: return 'ok';
5831: }
5832:
5833: # -------------------------------------------------------------- Modify student
5834:
5835: sub modifystudent {
5836: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
5837: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
5838: $selfenroll,$context)=@_;
5839: if (!$cid) {
5840: unless ($cid=$env{'request.course.id'}) {
5841: return 'not_in_class';
5842: }
5843: }
5844: # --------------------------------------------------------------- Make the user
5845: my $reply=&modifyuser
5846: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
5847: $desiredhome,$email);
5848: unless ($reply eq 'ok') { return $reply; }
5849: # This will cause &modify_student_enrollment to get the uid from the
5850: # students environment
5851: $uid = undef if (!$forceid);
5852: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
5853: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
5854: return $reply;
5855: }
5856:
5857: sub modify_student_enrollment {
5858: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
5859: my ($cdom,$cnum,$chome);
5860: if (!$cid) {
5861: unless ($cid=$env{'request.course.id'}) {
5862: return 'not_in_class';
5863: }
5864: $cdom=$env{'course.'.$cid.'.domain'};
5865: $cnum=$env{'course.'.$cid.'.num'};
5866: } else {
5867: ($cdom,$cnum)=split(/_/,$cid);
5868: }
5869: $chome=$env{'course.'.$cid.'.home'};
5870: if (!$chome) {
5871: $chome=&homeserver($cnum,$cdom);
5872: }
5873: if (!$chome) { return 'unknown_course'; }
5874: # Make sure the user exists
5875: my $uhome=&homeserver($uname,$udom);
5876: if (($uhome eq '') || ($uhome eq 'no_host')) {
5877: return 'error: no such user';
5878: }
5879: # Get student data if we were not given enough information
5880: if (!defined($first) || $first eq '' ||
5881: !defined($last) || $last eq '' ||
5882: !defined($uid) || $uid eq '' ||
5883: !defined($middle) || $middle eq '' ||
5884: !defined($gene) || $gene eq '') {
5885: # They did not supply us with enough data to enroll the student, so
5886: # we need to pick up more information.
5887: my %tmp = &get('environment',
5888: ['firstname','middlename','lastname', 'generation','id']
5889: ,$udom,$uname);
5890:
5891: #foreach my $key (keys(%tmp)) {
5892: # &logthis("key $key = ".$tmp{$key});
5893: #}
5894: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
5895: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
5896: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
5897: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
5898: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
5899: }
5900: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
5901: my $reply=cput('classlist',
5902: {"$uname:$udom" =>
5903: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
5904: $cdom,$cnum);
5905: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
5906: return 'error: '.$reply;
5907: } else {
5908: &devalidate_getsection_cache($udom,$uname,$cid);
5909: }
5910: # Add student role to user
5911: my $uurl='/'.$cid;
5912: $uurl=~s/\_/\//g;
5913: if ($usec) {
5914: $uurl.='/'.$usec;
5915: }
5916: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
5917: }
5918:
5919: sub format_name {
5920: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
5921: my $name;
5922: if ($first ne 'lastname') {
5923: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
5924: } else {
5925: if ($lastname=~/\S/) {
5926: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
5927: $name=~s/\s+,/,/;
5928: } else {
5929: $name.= $firstname.' '.$middlename.' '.$generation;
5930: }
5931: }
5932: $name=~s/^\s+//;
5933: $name=~s/\s+$//;
5934: $name=~s/\s+/ /g;
5935: return $name;
5936: }
5937:
5938: # ------------------------------------------------- Write to course preferences
5939:
5940: sub writecoursepref {
5941: my ($courseid,%prefs)=@_;
5942: $courseid=~s/^\///;
5943: $courseid=~s/\_/\//g;
5944: my ($cdomain,$cnum)=split(/\//,$courseid);
5945: my $chome=homeserver($cnum,$cdomain);
5946: if (($chome eq '') || ($chome eq 'no_host')) {
5947: return 'error: no such course';
5948: }
5949: my $cstring='';
5950: foreach my $pref (keys(%prefs)) {
5951: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
5952: }
5953: $cstring=~s/\&$//;
5954: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
5955: }
5956:
5957: # ---------------------------------------------------------- Make/modify course
5958:
5959: sub createcourse {
5960: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
5961: $course_owner,$crstype)=@_;
5962: $url=&declutter($url);
5963: my $cid='';
5964: unless (&allowed('ccc',$udom)) {
5965: return 'refused';
5966: }
5967: # ------------------------------------------------------------------- Create ID
5968: my $uname=int(1+rand(9)).
5969: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
5970: substr($$.time,0,5).unpack("H8",pack("I32",time)).
5971: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5972: # ----------------------------------------------- Make sure that does not exist
5973: my $uhome=&homeserver($uname,$udom,'true');
5974: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5975: $uname=substr($$.time,0,5).unpack("H8",pack("I32",time)).
5976: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
5977: $uhome=&homeserver($uname,$udom,'true');
5978: unless (($uhome eq '') || ($uhome eq 'no_host')) {
5979: return 'error: unable to generate unique course-ID';
5980: }
5981: }
5982: # ------------------------------------------------ Check supplied server name
5983: $course_server = $env{'user.homeserver'} if (! defined($course_server));
5984: if (! &is_library($course_server)) {
5985: return 'error:bad server name '.$course_server;
5986: }
5987: # ------------------------------------------------------------- Make the course
5988: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
5989: $course_server);
5990: unless ($reply eq 'ok') { return 'error: '.$reply; }
5991: $uhome=&homeserver($uname,$udom,'true');
5992: if (($uhome eq '') || ($uhome eq 'no_host')) {
5993: return 'error: no such course';
5994: }
5995: # ----------------------------------------------------------------- Course made
5996: # log existence
5997: my $newcourse = {
5998: $udom.'_'.$uname => {
5999: description => $description,
6000: inst_code => $inst_code,
6001: owner => $course_owner,
6002: type => $crstype,
6003: },
6004: };
6005: &courseidput($udom,$newcourse,$uhome,'notime');
6006: # set toplevel url
6007: my $topurl=$url;
6008: unless ($nonstandard) {
6009: # ------------------------------------------ For standard courses, make top url
6010: my $mapurl=&clutter($url);
6011: if ($mapurl eq '/res/') { $mapurl=''; }
6012: $env{'form.initmap'}=(<<ENDINITMAP);
6013: <map>
6014: <resource id="1" type="start"></resource>
6015: <resource id="2" src="$mapurl"></resource>
6016: <resource id="3" type="finish"></resource>
6017: <link index="1" from="1" to="2"></link>
6018: <link index="2" from="2" to="3"></link>
6019: </map>
6020: ENDINITMAP
6021: $topurl=&declutter(
6022: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
6023: );
6024: }
6025: # ----------------------------------------------------------- Write preferences
6026: &writecoursepref($udom.'_'.$uname,
6027: ('description' => $description,
6028: 'url' => $topurl));
6029: return '/'.$udom.'/'.$uname;
6030: }
6031:
6032: sub is_course {
6033: my ($cdom,$cnum) = @_;
6034: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
6035: undef,'.');
6036: if (exists($courses{$cdom.'_'.$cnum})) {
6037: return 1;
6038: }
6039: return 0;
6040: }
6041:
6042: # ---------------------------------------------------------- Assign Custom Role
6043:
6044: sub assigncustomrole {
6045: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
6046: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
6047: $end,$start,$deleteflag,$selfenroll,$context);
6048: }
6049:
6050: # ----------------------------------------------------------------- Revoke Role
6051:
6052: sub revokerole {
6053: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
6054: my $now=time;
6055: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
6056: }
6057:
6058: # ---------------------------------------------------------- Revoke Custom Role
6059:
6060: sub revokecustomrole {
6061: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
6062: my $now=time;
6063: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
6064: $deleteflag,$selfenroll,$context);
6065: }
6066:
6067: # ------------------------------------------------------------ Disk usage
6068: sub diskusage {
6069: my ($udom,$uname,$directorypath,$getpropath)=@_;
6070: $directorypath =~ s/\/$//;
6071: my $listing=&reply('du2:'.&escape($directorypath).':'
6072: .&escape($getpropath).':'.&escape($uname).':'
6073: .&escape($udom),homeserver($uname,$udom));
6074: if ($listing eq 'unknown_cmd') {
6075: if ($getpropath) {
6076: $directorypath = &propath($udom,$uname).'/'.$directorypath;
6077: }
6078: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
6079: }
6080: return $listing;
6081: }
6082:
6083: sub is_locked {
6084: my ($file_name, $domain, $user) = @_;
6085: my @check;
6086: my $is_locked;
6087: push @check, $file_name;
6088: my %locked = &get('file_permissions',\@check,
6089: $env{'user.domain'},$env{'user.name'});
6090: my ($tmp)=keys(%locked);
6091: if ($tmp=~/^error:/) { undef(%locked); }
6092:
6093: if (ref($locked{$file_name}) eq 'ARRAY') {
6094: $is_locked = 'false';
6095: foreach my $entry (@{$locked{$file_name}}) {
6096: if (ref($entry) eq 'ARRAY') {
6097: $is_locked = 'true';
6098: last;
6099: }
6100: }
6101: } else {
6102: $is_locked = 'false';
6103: }
6104: }
6105:
6106: sub declutter_portfile {
6107: my ($file) = @_;
6108: $file =~ s{^(/portfolio/|portfolio/)}{/};
6109: return $file;
6110: }
6111:
6112: # ------------------------------------------------------------- Mark as Read Only
6113:
6114: sub mark_as_readonly {
6115: my ($domain,$user,$files,$what) = @_;
6116: my %current_permissions = &dump('file_permissions',$domain,$user);
6117: my ($tmp)=keys(%current_permissions);
6118: if ($tmp=~/^error:/) { undef(%current_permissions); }
6119: foreach my $file (@{$files}) {
6120: $file = &declutter_portfile($file);
6121: push(@{$current_permissions{$file}},$what);
6122: }
6123: &put('file_permissions',\%current_permissions,$domain,$user);
6124: return;
6125: }
6126:
6127: # ------------------------------------------------------------Save Selected Files
6128:
6129: sub save_selected_files {
6130: my ($user, $path, @files) = @_;
6131: my $filename = $user."savedfiles";
6132: my @other_files = &files_not_in_path($user, $path);
6133: open (OUT, '>'.$tmpdir.$filename);
6134: foreach my $file (@files) {
6135: print (OUT $env{'form.currentpath'}.$file."\n");
6136: }
6137: foreach my $file (@other_files) {
6138: print (OUT $file."\n");
6139: }
6140: close (OUT);
6141: return 'ok';
6142: }
6143:
6144: sub clear_selected_files {
6145: my ($user) = @_;
6146: my $filename = $user."savedfiles";
6147: open (OUT, '>'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6148: print (OUT undef);
6149: close (OUT);
6150: return ("ok");
6151: }
6152:
6153: sub files_in_path {
6154: my ($user, $path) = @_;
6155: my $filename = $user."savedfiles";
6156: my %return_files;
6157: open (IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6158: while (my $line_in = <IN>) {
6159: chomp ($line_in);
6160: my @paths_and_file = split (m!/!, $line_in);
6161: my $file_part = pop (@paths_and_file);
6162: my $path_part = join ('/', @paths_and_file);
6163: $path_part.='/';
6164: my $path_and_file = $path_part.$file_part;
6165: if ($path_part eq $path) {
6166: $return_files{$file_part}= 'selected';
6167: }
6168: }
6169: close (IN);
6170: return (\%return_files);
6171: }
6172:
6173: # called in portfolio select mode, to show files selected NOT in current directory
6174: sub files_not_in_path {
6175: my ($user, $path) = @_;
6176: my $filename = $user."savedfiles";
6177: my @return_files;
6178: my $path_part;
6179: open(IN, '<'.$Apache::lonnet::perlvar{'lonDaemons'}.'/tmp/'.$filename);
6180: while (my $line = <IN>) {
6181: #ok, I know it's clunky, but I want it to work
6182: my @paths_and_file = split(m|/|, $line);
6183: my $file_part = pop(@paths_and_file);
6184: chomp($file_part);
6185: my $path_part = join('/', @paths_and_file);
6186: $path_part .= '/';
6187: my $path_and_file = $path_part.$file_part;
6188: if ($path_part ne $path) {
6189: push(@return_files, ($path_and_file));
6190: }
6191: }
6192: close(OUT);
6193: return (@return_files);
6194: }
6195:
6196: #----------------------------------------------Get portfolio file permissions
6197:
6198: sub get_portfile_permissions {
6199: my ($domain,$user) = @_;
6200: my %current_permissions = &dump('file_permissions',$domain,$user);
6201: my ($tmp)=keys(%current_permissions);
6202: if ($tmp=~/^error:/) { undef(%current_permissions); }
6203: return \%current_permissions;
6204: }
6205:
6206: #---------------------------------------------Get portfolio file access controls
6207:
6208: sub get_access_controls {
6209: my ($current_permissions,$group,$file) = @_;
6210: my %access;
6211: my $real_file = $file;
6212: $file =~ s/\.meta$//;
6213: if (defined($file)) {
6214: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
6215: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
6216: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
6217: }
6218: }
6219: } else {
6220: foreach my $key (keys(%{$current_permissions})) {
6221: if ($key =~ /\0accesscontrol$/) {
6222: if (defined($group)) {
6223: if ($key !~ m-^\Q$group\E/-) {
6224: next;
6225: }
6226: }
6227: my ($fullpath) = split(/\0/,$key);
6228: if (ref($$current_permissions{$key}) eq 'HASH') {
6229: foreach my $control (keys(%{$$current_permissions{$key}})) {
6230: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
6231: }
6232: }
6233: }
6234: }
6235: }
6236: return %access;
6237: }
6238:
6239: sub modify_access_controls {
6240: my ($file_name,$changes,$domain,$user)=@_;
6241: my ($outcome,$deloutcome);
6242: my %store_permissions;
6243: my %new_values;
6244: my %new_control;
6245: my %translation;
6246: my @deletions = ();
6247: my $now = time;
6248: if (exists($$changes{'activate'})) {
6249: if (ref($$changes{'activate'}) eq 'HASH') {
6250: my @newitems = sort(keys(%{$$changes{'activate'}}));
6251: my $numnew = scalar(@newitems);
6252: for (my $i=0; $i<$numnew; $i++) {
6253: my $newkey = $newitems[$i];
6254: my $newid = &Apache::loncommon::get_cgi_id();
6255: if ($newkey =~ /^\d+:/) {
6256: $newkey =~ s/^(\d+)/$newid/;
6257: $translation{$1} = $newid;
6258: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
6259: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
6260: $translation{$1} = $newid;
6261: }
6262: $new_values{$file_name."\0".$newkey} =
6263: $$changes{'activate'}{$newitems[$i]};
6264: $new_control{$newkey} = $now;
6265: }
6266: }
6267: }
6268: my %todelete;
6269: my %changed_items;
6270: foreach my $action ('delete','update') {
6271: if (exists($$changes{$action})) {
6272: if (ref($$changes{$action}) eq 'HASH') {
6273: foreach my $key (keys(%{$$changes{$action}})) {
6274: my ($itemnum) = ($key =~ /^([^:]+):/);
6275: if ($action eq 'delete') {
6276: $todelete{$itemnum} = 1;
6277: } else {
6278: $changed_items{$itemnum} = $key;
6279: }
6280: }
6281: }
6282: }
6283: }
6284: # get lock on access controls for file.
6285: my $lockhash = {
6286: $file_name."\0".'locked_access_records' => $env{'user.name'}.
6287: ':'.$env{'user.domain'},
6288: };
6289: my $tries = 0;
6290: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6291:
6292: while (($gotlock ne 'ok') && $tries <3) {
6293: $tries ++;
6294: sleep 1;
6295: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
6296: }
6297: if ($gotlock eq 'ok') {
6298: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
6299: my ($tmp)=keys(%curr_permissions);
6300: if ($tmp=~/^error:/) { undef(%curr_permissions); }
6301: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
6302: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
6303: if (ref($curr_controls) eq 'HASH') {
6304: foreach my $control_item (keys(%{$curr_controls})) {
6305: my ($itemnum) = ($control_item =~ /^([^:]+):/);
6306: if (defined($todelete{$itemnum})) {
6307: push(@deletions,$file_name."\0".$control_item);
6308: } else {
6309: if (defined($changed_items{$itemnum})) {
6310: $new_control{$changed_items{$itemnum}} = $now;
6311: push(@deletions,$file_name."\0".$control_item);
6312: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
6313: } else {
6314: $new_control{$control_item} = $$curr_controls{$control_item};
6315: }
6316: }
6317: }
6318: }
6319: }
6320: my ($group);
6321: if (&is_course($domain,$user)) {
6322: ($group,my $file) = split(/\//,$file_name,2);
6323: }
6324: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
6325: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
6326: $outcome = &put('file_permissions',\%new_values,$domain,$user);
6327: # remove lock
6328: my @del_lock = ($file_name."\0".'locked_access_records');
6329: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
6330: my $sqlresult =
6331: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
6332: $group);
6333: } else {
6334: $outcome = "error: could not obtain lockfile\n";
6335: }
6336: return ($outcome,$deloutcome,\%new_values,\%translation);
6337: }
6338:
6339: sub make_public_indefinitely {
6340: my ($requrl) = @_;
6341: my $now = time;
6342: my $action = 'activate';
6343: my $aclnum = 0;
6344: if (&is_portfolio_url($requrl)) {
6345: my (undef,$udom,$unum,$file_name,$group) =
6346: &parse_portfolio_url($requrl);
6347: my $current_perms = &get_portfile_permissions($udom,$unum);
6348: my %access_controls = &get_access_controls($current_perms,
6349: $group,$file_name);
6350: foreach my $key (keys(%{$access_controls{$file_name}})) {
6351: my ($num,$scope,$end,$start) =
6352: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
6353: if ($scope eq 'public') {
6354: if ($start <= $now && $end == 0) {
6355: $action = 'none';
6356: } else {
6357: $action = 'update';
6358: $aclnum = $num;
6359: }
6360: last;
6361: }
6362: }
6363: if ($action eq 'none') {
6364: return 'ok';
6365: } else {
6366: my %changes;
6367: my $newend = 0;
6368: my $newstart = $now;
6369: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
6370: $changes{$action}{$newkey} = {
6371: type => 'public',
6372: time => {
6373: start => $newstart,
6374: end => $newend,
6375: },
6376: };
6377: my ($outcome,$deloutcome,$new_values,$translation) =
6378: &modify_access_controls($file_name,\%changes,$udom,$unum);
6379: return $outcome;
6380: }
6381: } else {
6382: return 'invalid';
6383: }
6384: }
6385:
6386: #------------------------------------------------------Get Marked as Read Only
6387:
6388: sub get_marked_as_readonly {
6389: my ($domain,$user,$what,$group) = @_;
6390: my $current_permissions = &get_portfile_permissions($domain,$user);
6391: my @readonly_files;
6392: my $cmp1=$what;
6393: if (ref($what)) { $cmp1=join('',@{$what}) };
6394: while (my ($file_name,$value) = each(%{$current_permissions})) {
6395: if (defined($group)) {
6396: if ($file_name !~ m-^\Q$group\E/-) {
6397: next;
6398: }
6399: }
6400: if (ref($value) eq "ARRAY"){
6401: foreach my $stored_what (@{$value}) {
6402: my $cmp2=$stored_what;
6403: if (ref($stored_what) eq 'ARRAY') {
6404: $cmp2=join('',@{$stored_what});
6405: }
6406: if ($cmp1 eq $cmp2) {
6407: push(@readonly_files, $file_name);
6408: last;
6409: } elsif (!defined($what)) {
6410: push(@readonly_files, $file_name);
6411: last;
6412: }
6413: }
6414: }
6415: }
6416: return @readonly_files;
6417: }
6418: #-----------------------------------------------------------Get Marked as Read Only Hash
6419:
6420: sub get_marked_as_readonly_hash {
6421: my ($current_permissions,$group,$what) = @_;
6422: my %readonly_files;
6423: while (my ($file_name,$value) = each(%{$current_permissions})) {
6424: if (defined($group)) {
6425: if ($file_name !~ m-^\Q$group\E/-) {
6426: next;
6427: }
6428: }
6429: if (ref($value) eq "ARRAY"){
6430: foreach my $stored_what (@{$value}) {
6431: if (ref($stored_what) eq 'ARRAY') {
6432: foreach my $lock_descriptor(@{$stored_what}) {
6433: if ($lock_descriptor eq 'graded') {
6434: $readonly_files{$file_name} = 'graded';
6435: } elsif ($lock_descriptor eq 'handback') {
6436: $readonly_files{$file_name} = 'handback';
6437: } else {
6438: if (!exists($readonly_files{$file_name})) {
6439: $readonly_files{$file_name} = 'locked';
6440: }
6441: }
6442: }
6443: }
6444: }
6445: }
6446: }
6447: return %readonly_files;
6448: }
6449: # ------------------------------------------------------------ Unmark as Read Only
6450:
6451: sub unmark_as_readonly {
6452: # unmarks $file_name (if $file_name is defined), or all files locked by $what
6453: # for portfolio submissions, $what contains [$symb,$crsid]
6454: my ($domain,$user,$what,$file_name,$group) = @_;
6455: $file_name = &declutter_portfile($file_name);
6456: my $symb_crs = $what;
6457: if (ref($what)) { $symb_crs=join('',@$what); }
6458: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
6459: my ($tmp)=keys(%current_permissions);
6460: if ($tmp=~/^error:/) { undef(%current_permissions); }
6461: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
6462: foreach my $file (@readonly_files) {
6463: my $clean_file = &declutter_portfile($file);
6464: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
6465: my $current_locks = $current_permissions{$file};
6466: my @new_locks;
6467: my @del_keys;
6468: if (ref($current_locks) eq "ARRAY"){
6469: foreach my $locker (@{$current_locks}) {
6470: my $compare=$locker;
6471: if (ref($locker) eq 'ARRAY') {
6472: $compare=join('',@{$locker});
6473: if ($compare ne $symb_crs) {
6474: push(@new_locks, $locker);
6475: }
6476: }
6477: }
6478: if (scalar(@new_locks) > 0) {
6479: $current_permissions{$file} = \@new_locks;
6480: } else {
6481: push(@del_keys, $file);
6482: &del('file_permissions',\@del_keys, $domain, $user);
6483: delete($current_permissions{$file});
6484: }
6485: }
6486: }
6487: &put('file_permissions',\%current_permissions,$domain,$user);
6488: return;
6489: }
6490:
6491: # ------------------------------------------------------------ Directory lister
6492:
6493: sub dirlist {
6494: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
6495: $uri=~s/^\///;
6496: $uri=~s/\/$//;
6497: my ($udom, $uname);
6498: if ($getuserdir) {
6499: $udom = $userdomain;
6500: $uname = $username;
6501: } else {
6502: (undef,$udom,$uname)=split(/\//,$uri);
6503: if(defined($userdomain)) {
6504: $udom = $userdomain;
6505: }
6506: if(defined($username)) {
6507: $uname = $username;
6508: }
6509: }
6510: my ($dirRoot,$listing,@listing_results);
6511:
6512: $dirRoot = $perlvar{'lonDocRoot'};
6513: if (defined($getpropath)) {
6514: $dirRoot = &propath($udom,$uname);
6515: $dirRoot =~ s/\/$//;
6516: } elsif (defined($getuserdir)) {
6517: my $subdir=$uname.'__';
6518: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
6519: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
6520: ."/$udom/$subdir/$uname";
6521: } elsif (defined($alternateRoot)) {
6522: $dirRoot = $alternateRoot;
6523: }
6524:
6525: if($udom) {
6526: if($uname) {
6527: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
6528: .$getuserdir.':'.&escape($dirRoot)
6529: .':'.&escape($uname).':'.&escape($udom),
6530: &homeserver($uname,$udom));
6531: if ($listing eq 'unknown_cmd') {
6532: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
6533: &homeserver($uname,$udom));
6534: } else {
6535: @listing_results = map { &unescape($_); } split(/:/,$listing);
6536: }
6537: if ($listing eq 'unknown_cmd') {
6538: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
6539: &homeserver($uname,$udom));
6540: @listing_results = split(/:/,$listing);
6541: } else {
6542: @listing_results = map { &unescape($_); } split(/:/,$listing);
6543: }
6544: return @listing_results;
6545: } elsif(!$alternateRoot) {
6546: my %allusers;
6547: my %servers = &get_servers($udom,'library');
6548: foreach my $tryserver (keys(%servers)) {
6549: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
6550: &escape($udom),$tryserver);
6551: if ($listing eq 'unknown_cmd') {
6552: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
6553: $udom, $tryserver);
6554: } else {
6555: @listing_results = map { &unescape($_); } split(/:/,$listing);
6556: }
6557: if ($listing eq 'unknown_cmd') {
6558: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
6559: $udom, $tryserver);
6560: @listing_results = split(/:/,$listing);
6561: } else {
6562: @listing_results =
6563: map { &unescape($_); } split(/:/,$listing);
6564: }
6565: if ($listing_results[0] ne 'no_such_dir' &&
6566: $listing_results[0] ne 'empty' &&
6567: $listing_results[0] ne 'con_lost') {
6568: foreach my $line (@listing_results) {
6569: my ($entry) = split(/&/,$line,2);
6570: $allusers{$entry} = 1;
6571: }
6572: }
6573: }
6574: my $alluserstr='';
6575: foreach my $user (sort(keys(%allusers))) {
6576: $alluserstr.=$user.'&user:';
6577: }
6578: $alluserstr=~s/:$//;
6579: return split(/:/,$alluserstr);
6580: } else {
6581: return ('missing user name');
6582: }
6583: } elsif(!defined($getpropath)) {
6584: my @all_domains = sort(&all_domains());
6585: foreach my $domain (@all_domains) {
6586: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
6587: }
6588: return @all_domains;
6589: } else {
6590: return ('missing domain');
6591: }
6592: }
6593:
6594: # --------------------------------------------- GetFileTimestamp
6595: # This function utilizes dirlist and returns the date stamp for
6596: # when it was last modified. It will also return an error of -1
6597: # if an error occurs
6598:
6599: sub GetFileTimestamp {
6600: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
6601: $studentDomain = &LONCAPA::clean_domain($studentDomain);
6602: $studentName = &LONCAPA::clean_username($studentName);
6603: my ($fileStat) =
6604: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
6605: undef,$getuserdir);
6606: my @stats = split('&', $fileStat);
6607: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6608: # @stats contains first the filename, then the stat output
6609: return $stats[10]; # so this is 10 instead of 9.
6610: } else {
6611: return -1;
6612: }
6613: }
6614:
6615: sub stat_file {
6616: my ($uri) = @_;
6617: $uri = &clutter_with_no_wrapper($uri);
6618:
6619: my ($udom,$uname,$file);
6620: if ($uri =~ m-^/(uploaded|editupload)/-) {
6621: ($udom,$uname,$file) =
6622: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
6623: $file = 'userfiles/'.$file;
6624: }
6625: if ($uri =~ m-^/res/-) {
6626: ($udom,$uname) =
6627: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
6628: $file = $uri;
6629: }
6630:
6631: if (!$udom || !$uname || !$file) {
6632: # unable to handle the uri
6633: return ();
6634: }
6635: my $getpropath;
6636: if ($file =~ /^userfiles\//) {
6637: $getpropath = 1;
6638: }
6639: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
6640: my @stats = split('&', $result);
6641:
6642: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
6643: shift(@stats); #filename is first
6644: return @stats;
6645: }
6646: return ();
6647: }
6648:
6649: # -------------------------------------------------------- Value of a Condition
6650:
6651: # gets the value of a specific preevaluated condition
6652: # stored in the string $env{user.state.<cid>}
6653: # or looks up a condition reference in the bighash and if if hasn't
6654: # already been evaluated recurses into docondval to get the value of
6655: # the condition, then memoizing it to
6656: # $env{user.state.<cid>.<condition>}
6657: sub directcondval {
6658: my $number=shift;
6659: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
6660: &Apache::lonuserstate::evalstate();
6661: }
6662: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
6663: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
6664: } elsif ($number =~ /^_/) {
6665: my $sub_condition;
6666: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
6667: &GDBM_READER(),0640)) {
6668: $sub_condition=$bighash{'conditions'.$number};
6669: untie(%bighash);
6670: }
6671: my $value = &docondval($sub_condition);
6672: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
6673: return $value;
6674: }
6675: if ($env{'user.state.'.$env{'request.course.id'}}) {
6676: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
6677: } else {
6678: return 2;
6679: }
6680: }
6681:
6682: # get the collection of conditions for this resource
6683: sub condval {
6684: my $condidx=shift;
6685: my $allpathcond='';
6686: foreach my $cond (split(/\|/,$condidx)) {
6687: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
6688: $allpathcond.=
6689: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
6690: }
6691: }
6692: $allpathcond=~s/\|$//;
6693: return &docondval($allpathcond);
6694: }
6695:
6696: #evaluates an expression of conditions
6697: sub docondval {
6698: my ($allpathcond) = @_;
6699: my $result=0;
6700: if ($env{'request.course.id'}
6701: && defined($allpathcond)) {
6702: my $operand='|';
6703: my @stack;
6704: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
6705: if ($chunk eq '(') {
6706: push @stack,($operand,$result);
6707: } elsif ($chunk eq ')') {
6708: my $before=pop @stack;
6709: if (pop @stack eq '&') {
6710: $result=$result>$before?$before:$result;
6711: } else {
6712: $result=$result>$before?$result:$before;
6713: }
6714: } elsif (($chunk eq '&') || ($chunk eq '|')) {
6715: $operand=$chunk;
6716: } else {
6717: my $new=directcondval($chunk);
6718: if ($operand eq '&') {
6719: $result=$result>$new?$new:$result;
6720: } else {
6721: $result=$result>$new?$result:$new;
6722: }
6723: }
6724: }
6725: }
6726: return $result;
6727: }
6728:
6729: # ---------------------------------------------------- Devalidate courseresdata
6730:
6731: sub devalidatecourseresdata {
6732: my ($coursenum,$coursedomain)=@_;
6733: my $hashid=$coursenum.':'.$coursedomain;
6734: &devalidate_cache_new('courseres',$hashid);
6735: }
6736:
6737:
6738: # --------------------------------------------------- Course Resourcedata Query
6739: #
6740: # Parameters:
6741: # $coursenum - Number of the course.
6742: # $coursedomain - Domain at which the course was created.
6743: # Returns:
6744: # A hash of the course parameters along (I think) with timestamps
6745: # and version info.
6746:
6747: sub get_courseresdata {
6748: my ($coursenum,$coursedomain)=@_;
6749: my $coursehom=&homeserver($coursenum,$coursedomain);
6750: my $hashid=$coursenum.':'.$coursedomain;
6751: my ($result,$cached)=&is_cached_new('courseres',$hashid);
6752: my %dumpreply;
6753: unless (defined($cached)) {
6754: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
6755: $result=\%dumpreply;
6756: my ($tmp) = keys(%dumpreply);
6757: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
6758: &do_cache_new('courseres',$hashid,$result,600);
6759: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
6760: return $tmp;
6761: } elsif ($tmp =~ /^(error)/) {
6762: $result=undef;
6763: &do_cache_new('courseres',$hashid,$result,600);
6764: }
6765: }
6766: return $result;
6767: }
6768:
6769: sub devalidateuserresdata {
6770: my ($uname,$udom)=@_;
6771: my $hashid="$udom:$uname";
6772: &devalidate_cache_new('userres',$hashid);
6773: }
6774:
6775: sub get_userresdata {
6776: my ($uname,$udom)=@_;
6777: #most student don\'t have any data set, check if there is some data
6778: if (&EXT_cache_status($udom,$uname)) { return undef; }
6779:
6780: my $hashid="$udom:$uname";
6781: my ($result,$cached)=&is_cached_new('userres',$hashid);
6782: if (!defined($cached)) {
6783: my %resourcedata=&dump('resourcedata',$udom,$uname);
6784: $result=\%resourcedata;
6785: &do_cache_new('userres',$hashid,$result,600);
6786: }
6787: my ($tmp)=keys(%$result);
6788: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
6789: return $result;
6790: }
6791: #error 2 occurs when the .db doesn't exist
6792: if ($tmp!~/error: 2 /) {
6793: &logthis("<font color=\"blue\">WARNING:".
6794: " Trying to get resource data for ".
6795: $uname." at ".$udom.": ".
6796: $tmp."</font>");
6797: } elsif ($tmp=~/error: 2 /) {
6798: #&EXT_cache_set($udom,$uname);
6799: &do_cache_new('userres',$hashid,undef,600);
6800: undef($tmp); # not really an error so don't send it back
6801: }
6802: return $tmp;
6803: }
6804: #----------------------------------------------- resdata - return resource data
6805: # Purpose:
6806: # Return resource data for either users or for a course.
6807: # Parameters:
6808: # $name - Course/user name.
6809: # $domain - Name of the domain the user/course is registered on.
6810: # $type - Type of thing $name is (must be 'course' or 'user'
6811: # @which - Array of names of resources desired.
6812: # Returns:
6813: # The value of the first reasource in @which that is found in the
6814: # resource hash.
6815: # Exceptional Conditions:
6816: # If the $type passed in is not valid (not the string 'course' or
6817: # 'user', an undefined reference is returned.
6818: # If none of the resources are found, an undef is returned
6819: sub resdata {
6820: my ($name,$domain,$type,@which)=@_;
6821: my $result;
6822: if ($type eq 'course') {
6823: $result=&get_courseresdata($name,$domain);
6824: } elsif ($type eq 'user') {
6825: $result=&get_userresdata($name,$domain);
6826: }
6827: if (!ref($result)) { return $result; }
6828: foreach my $item (@which) {
6829: if (defined($result->{$item->[0]})) {
6830: return [$result->{$item->[0]},$item->[1]];
6831: }
6832: }
6833: return undef;
6834: }
6835:
6836: #
6837: # EXT resource caching routines
6838: #
6839:
6840: sub clear_EXT_cache_status {
6841: &delenv('cache.EXT.');
6842: }
6843:
6844: sub EXT_cache_status {
6845: my ($target_domain,$target_user) = @_;
6846: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
6847: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
6848: # We know already the user has no data
6849: return 1;
6850: } else {
6851: return 0;
6852: }
6853: }
6854:
6855: sub EXT_cache_set {
6856: my ($target_domain,$target_user) = @_;
6857: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
6858: #&appenv({$cachename => time});
6859: }
6860:
6861: # --------------------------------------------------------- Value of a Variable
6862: sub EXT {
6863:
6864: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
6865: unless ($varname) { return ''; }
6866: #get real user name/domain, courseid and symb
6867: my $courseid;
6868: my $publicuser;
6869: if ($symbparm) {
6870: $symbparm=&get_symb_from_alias($symbparm);
6871: }
6872: if (!($uname && $udom)) {
6873: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
6874: if (!$symbparm) { $symbparm=$cursymb; }
6875: } else {
6876: $courseid=$env{'request.course.id'};
6877: }
6878: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
6879: my $rest;
6880: if (defined($therest[0])) {
6881: $rest=join('.',@therest);
6882: } else {
6883: $rest='';
6884: }
6885:
6886: my $qualifierrest=$qualifier;
6887: if ($rest) { $qualifierrest.='.'.$rest; }
6888: my $spacequalifierrest=$space;
6889: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
6890: if ($realm eq 'user') {
6891: # --------------------------------------------------------------- user.resource
6892: if ($space eq 'resource') {
6893: if ( (defined($Apache::lonhomework::parsing_a_problem)
6894: || defined($Apache::lonhomework::parsing_a_task))
6895: &&
6896: ($symbparm eq &symbread()) ) {
6897: # if we are in the middle of processing the resource the
6898: # get the value we are planning on committing
6899: if (defined($Apache::lonhomework::results{$qualifierrest})) {
6900: return $Apache::lonhomework::results{$qualifierrest};
6901: } else {
6902: return $Apache::lonhomework::history{$qualifierrest};
6903: }
6904: } else {
6905: my %restored;
6906: if ($publicuser || $env{'request.state'} eq 'construct') {
6907: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
6908: } else {
6909: %restored=&restore($symbparm,$courseid,$udom,$uname);
6910: }
6911: return $restored{$qualifierrest};
6912: }
6913: # ----------------------------------------------------------------- user.access
6914: } elsif ($space eq 'access') {
6915: # FIXME - not supporting calls for a specific user
6916: return &allowed($qualifier,$rest);
6917: # ------------------------------------------ user.preferences, user.environment
6918: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
6919: if (($uname eq $env{'user.name'}) &&
6920: ($udom eq $env{'user.domain'})) {
6921: return $env{join('.',('environment',$qualifierrest))};
6922: } else {
6923: my %returnhash;
6924: if (!$publicuser) {
6925: %returnhash=&userenvironment($udom,$uname,
6926: $qualifierrest);
6927: }
6928: return $returnhash{$qualifierrest};
6929: }
6930: # ----------------------------------------------------------------- user.course
6931: } elsif ($space eq 'course') {
6932: # FIXME - not supporting calls for a specific user
6933: return $env{join('.',('request.course',$qualifier))};
6934: # ------------------------------------------------------------------- user.role
6935: } elsif ($space eq 'role') {
6936: # FIXME - not supporting calls for a specific user
6937: my ($role,$where)=split(/\./,$env{'request.role'});
6938: if ($qualifier eq 'value') {
6939: return $role;
6940: } elsif ($qualifier eq 'extent') {
6941: return $where;
6942: }
6943: # ----------------------------------------------------------------- user.domain
6944: } elsif ($space eq 'domain') {
6945: return $udom;
6946: # ------------------------------------------------------------------- user.name
6947: } elsif ($space eq 'name') {
6948: return $uname;
6949: # ---------------------------------------------------- Any other user namespace
6950: } else {
6951: my %reply;
6952: if (!$publicuser) {
6953: %reply=&get($space,[$qualifierrest],$udom,$uname);
6954: }
6955: return $reply{$qualifierrest};
6956: }
6957: } elsif ($realm eq 'query') {
6958: # ---------------------------------------------- pull stuff out of query string
6959: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
6960: [$spacequalifierrest]);
6961: return $env{'form.'.$spacequalifierrest};
6962: } elsif ($realm eq 'request') {
6963: # ------------------------------------------------------------- request.browser
6964: if ($space eq 'browser') {
6965: if ($qualifier eq 'textremote') {
6966: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
6967: return 1;
6968: } else {
6969: return 0;
6970: }
6971: } else {
6972: return $env{'browser.'.$qualifier};
6973: }
6974: # ------------------------------------------------------------ request.filename
6975: } else {
6976: return $env{'request.'.$spacequalifierrest};
6977: }
6978: } elsif ($realm eq 'course') {
6979: # ---------------------------------------------------------- course.description
6980: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
6981: } elsif ($realm eq 'resource') {
6982:
6983: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
6984: if (!$symbparm) { $symbparm=&symbread(); }
6985: }
6986:
6987: if ($space eq 'title') {
6988: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
6989: return &gettitle($symbparm);
6990: }
6991:
6992: if ($space eq 'map') {
6993: my ($map) = &decode_symb($symbparm);
6994: return &symbread($map);
6995: }
6996: if ($space eq 'filename') {
6997: if ($symbparm) {
6998: return &clutter((&decode_symb($symbparm))[2]);
6999: }
7000: return &hreflocation('',$env{'request.filename'});
7001: }
7002:
7003: my ($section, $group, @groups);
7004: my ($courselevelm,$courselevel);
7005: if ($symbparm && defined($courseid) &&
7006: $courseid eq $env{'request.course.id'}) {
7007:
7008: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
7009:
7010: # ----------------------------------------------------- Cascading lookup scheme
7011: my $symbp=$symbparm;
7012: my $mapp=&deversion((&decode_symb($symbp))[0]);
7013:
7014: my $symbparm=$symbp.'.'.$spacequalifierrest;
7015: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
7016:
7017: if (($env{'user.name'} eq $uname) &&
7018: ($env{'user.domain'} eq $udom)) {
7019: $section=$env{'request.course.sec'};
7020: @groups = split(/:/,$env{'request.course.groups'});
7021: @groups=&sort_course_groups($courseid,@groups);
7022: } else {
7023: if (! defined($usection)) {
7024: $section=&getsection($udom,$uname,$courseid);
7025: } else {
7026: $section = $usection;
7027: }
7028: @groups = &get_users_groups($udom,$uname,$courseid);
7029: }
7030:
7031: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
7032: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
7033: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
7034:
7035: $courselevel=$courseid.'.'.$spacequalifierrest;
7036: my $courselevelr=$courseid.'.'.$symbparm;
7037: $courselevelm=$courseid.'.'.$mapparm;
7038:
7039: # ----------------------------------------------------------- first, check user
7040:
7041: my $userreply=&resdata($uname,$udom,'user',
7042: ([$courselevelr,'resource'],
7043: [$courselevelm,'map' ],
7044: [$courselevel, 'course' ]));
7045: if (defined($userreply)) { return &get_reply($userreply); }
7046:
7047: # ------------------------------------------------ second, check some of course
7048: my $coursereply;
7049: if (@groups > 0) {
7050: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
7051: $mapparm,$spacequalifierrest);
7052: if (defined($coursereply)) { return &get_reply($coursereply); }
7053: }
7054:
7055: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7056: $env{'course.'.$courseid.'.domain'},
7057: 'course',
7058: ([$seclevelr, 'resource'],
7059: [$seclevelm, 'map' ],
7060: [$seclevel, 'course' ],
7061: [$courselevelr,'resource']));
7062: if (defined($coursereply)) { return &get_reply($coursereply); }
7063:
7064: # ------------------------------------------------------ third, check map parms
7065: my %parmhash=();
7066: my $thisparm='';
7067: if (tie(%parmhash,'GDBM_File',
7068: $env{'request.course.fn'}.'_parms.db',
7069: &GDBM_READER(),0640)) {
7070: $thisparm=$parmhash{$symbparm};
7071: untie(%parmhash);
7072: }
7073: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
7074: }
7075: # ------------------------------------------ fourth, look in resource metadata
7076:
7077: $spacequalifierrest=~s/\./\_/;
7078: my $filename;
7079: if (!$symbparm) { $symbparm=&symbread(); }
7080: if ($symbparm) {
7081: $filename=(&decode_symb($symbparm))[2];
7082: } else {
7083: $filename=$env{'request.filename'};
7084: }
7085: my $metadata=&metadata($filename,$spacequalifierrest);
7086: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7087: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
7088: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
7089:
7090: # ---------------------------------------------- fourth, look in rest of course
7091: if ($symbparm && defined($courseid) &&
7092: $courseid eq $env{'request.course.id'}) {
7093: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
7094: $env{'course.'.$courseid.'.domain'},
7095: 'course',
7096: ([$courselevelm,'map' ],
7097: [$courselevel, 'course']));
7098: if (defined($coursereply)) { return &get_reply($coursereply); }
7099: }
7100: # ------------------------------------------------------------------ Cascade up
7101: unless ($space eq '0') {
7102: my @parts=split(/_/,$space);
7103: my $id=pop(@parts);
7104: my $part=join('_',@parts);
7105: if ($part eq '') { $part='0'; }
7106: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
7107: $symbparm,$udom,$uname,$section,1);
7108: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
7109: }
7110: if ($recurse) { return undef; }
7111: my $pack_def=&packages_tab_default($filename,$varname);
7112: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
7113: # ---------------------------------------------------- Any other user namespace
7114: } elsif ($realm eq 'environment') {
7115: # ----------------------------------------------------------------- environment
7116: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
7117: return $env{'environment.'.$spacequalifierrest};
7118: } else {
7119: if ($uname eq 'anonymous' && $udom eq '') {
7120: return '';
7121: }
7122: my %returnhash=&userenvironment($udom,$uname,
7123: $spacequalifierrest);
7124: return $returnhash{$spacequalifierrest};
7125: }
7126: } elsif ($realm eq 'system') {
7127: # ----------------------------------------------------------------- system.time
7128: if ($space eq 'time') {
7129: return time;
7130: }
7131: } elsif ($realm eq 'server') {
7132: # ----------------------------------------------------------------- system.time
7133: if ($space eq 'name') {
7134: return $ENV{'SERVER_NAME'};
7135: }
7136: }
7137: return '';
7138: }
7139:
7140: sub get_reply {
7141: my ($reply_value) = @_;
7142: if (ref($reply_value) eq 'ARRAY') {
7143: if (wantarray) {
7144: return @$reply_value;
7145: }
7146: return $reply_value->[0];
7147: } else {
7148: return $reply_value;
7149: }
7150: }
7151:
7152: sub check_group_parms {
7153: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
7154: my @groupitems = ();
7155: my $resultitem;
7156: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
7157: foreach my $group (@{$groups}) {
7158: foreach my $level (@levels) {
7159: my $item = $courseid.'.['.$group.'].'.$level->[0];
7160: push(@groupitems,[$item,$level->[1]]);
7161: }
7162: }
7163: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
7164: $env{'course.'.$courseid.'.domain'},
7165: 'course',@groupitems);
7166: return $coursereply;
7167: }
7168:
7169: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
7170: my ($courseid,@groups) = @_;
7171: @groups = sort(@groups);
7172: return @groups;
7173: }
7174:
7175: sub packages_tab_default {
7176: my ($uri,$varname)=@_;
7177: my (undef,$part,$name)=split(/\./,$varname);
7178:
7179: my (@extension,@specifics,$do_default);
7180: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
7181: my ($pack_type,$pack_part)=split(/_/,$package,2);
7182: if ($pack_type eq 'default') {
7183: $do_default=1;
7184: } elsif ($pack_type eq 'extension') {
7185: push(@extension,[$package,$pack_type,$pack_part]);
7186: } elsif ($pack_part eq $part || $pack_type eq 'part') {
7187: # only look at packages defaults for packages that this id is
7188: push(@specifics,[$package,$pack_type,$pack_part]);
7189: }
7190: }
7191: # first look for a package that matches the requested part id
7192: foreach my $package (@specifics) {
7193: my (undef,$pack_type,$pack_part)=@{$package};
7194: next if ($pack_part ne $part);
7195: if (defined($packagetab{"$pack_type&$name&default"})) {
7196: return $packagetab{"$pack_type&$name&default"};
7197: }
7198: }
7199: # look for any possible matching non extension_ package
7200: foreach my $package (@specifics) {
7201: my (undef,$pack_type,$pack_part)=@{$package};
7202: if (defined($packagetab{"$pack_type&$name&default"})) {
7203: return $packagetab{"$pack_type&$name&default"};
7204: }
7205: if ($pack_type eq 'part') { $pack_part='0'; }
7206: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
7207: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
7208: }
7209: }
7210: # look for any posible extension_ match
7211: foreach my $package (@extension) {
7212: my ($package,$pack_type)=@{$package};
7213: if (defined($packagetab{"$pack_type&$name&default"})) {
7214: return $packagetab{"$pack_type&$name&default"};
7215: }
7216: if (defined($packagetab{$package."&$name&default"})) {
7217: return $packagetab{$package."&$name&default"};
7218: }
7219: }
7220: # look for a global default setting
7221: if ($do_default && defined($packagetab{"default&$name&default"})) {
7222: return $packagetab{"default&$name&default"};
7223: }
7224: return undef;
7225: }
7226:
7227: sub add_prefix_and_part {
7228: my ($prefix,$part)=@_;
7229: my $keyroot;
7230: if (defined($prefix) && $prefix !~ /^__/) {
7231: # prefix that has a part already
7232: $keyroot=$prefix;
7233: } elsif (defined($prefix)) {
7234: # prefix that is missing a part
7235: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
7236: } else {
7237: # no prefix at all
7238: if (defined($part)) { $keyroot='_'.$part; }
7239: }
7240: return $keyroot;
7241: }
7242:
7243: # ---------------------------------------------------------------- Get metadata
7244:
7245: my %metaentry;
7246: sub metadata {
7247: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
7248: $uri=&declutter($uri);
7249: # if it is a non metadata possible uri return quickly
7250: if (($uri eq '') ||
7251: (($uri =~ m|^/*adm/|) &&
7252: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
7253: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) ) {
7254: return undef;
7255: }
7256: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
7257: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
7258: return undef;
7259: }
7260: my $filename=$uri;
7261: $uri=~s/\.meta$//;
7262: #
7263: # Is the metadata already cached?
7264: # Look at timestamp of caching
7265: # Everything is cached by the main uri, libraries are never directly cached
7266: #
7267: if (!defined($liburi)) {
7268: my ($result,$cached)=&is_cached_new('meta',$uri);
7269: if (defined($cached)) { return $result->{':'.$what}; }
7270: }
7271: {
7272: #
7273: # Is this a recursive call for a library?
7274: #
7275: # if (! exists($metacache{$uri})) {
7276: # $metacache{$uri}={};
7277: # }
7278: my $cachetime = 60*60;
7279: if ($liburi) {
7280: $liburi=&declutter($liburi);
7281: $filename=$liburi;
7282: } else {
7283: &devalidate_cache_new('meta',$uri);
7284: undef(%metaentry);
7285: }
7286: my %metathesekeys=();
7287: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
7288: my $metastring;
7289: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
7290: my $which = &hreflocation('','/'.($liburi || $uri));
7291: $metastring =
7292: &Apache::lonnet::ssi_body($which,
7293: ('grade_target' => 'meta'));
7294: $cachetime = 1; # only want this cached in the child not long term
7295: } elsif ($uri !~ m -^(editupload)/-) {
7296: my $file=&filelocation('',&clutter($filename));
7297: #push(@{$metaentry{$uri.'.file'}},$file);
7298: $metastring=&getfile($file);
7299: }
7300: my $parser=HTML::LCParser->new(\$metastring);
7301: my $token;
7302: undef %metathesekeys;
7303: while ($token=$parser->get_token) {
7304: if ($token->[0] eq 'S') {
7305: if (defined($token->[2]->{'package'})) {
7306: #
7307: # This is a package - get package info
7308: #
7309: my $package=$token->[2]->{'package'};
7310: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7311: if (defined($token->[2]->{'id'})) {
7312: $keyroot.='_'.$token->[2]->{'id'};
7313: }
7314: if ($metaentry{':packages'}) {
7315: $metaentry{':packages'}.=','.$package.$keyroot;
7316: } else {
7317: $metaentry{':packages'}=$package.$keyroot;
7318: }
7319: foreach my $pack_entry (keys(%packagetab)) {
7320: my $part=$keyroot;
7321: $part=~s/^\_//;
7322: if ($pack_entry=~/^\Q$package\E\&/ ||
7323: $pack_entry=~/^\Q$package\E_0\&/) {
7324: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
7325: # ignore package.tab specified default values
7326: # here &package_tab_default() will fetch those
7327: if ($subp eq 'default') { next; }
7328: my $value=$packagetab{$pack_entry};
7329: my $unikey;
7330: if ($pack =~ /_0$/) {
7331: $unikey='parameter_0_'.$name;
7332: $part=0;
7333: } else {
7334: $unikey='parameter'.$keyroot.'_'.$name;
7335: }
7336: if ($subp eq 'display') {
7337: $value.=' [Part: '.$part.']';
7338: }
7339: $metaentry{':'.$unikey.'.part'}=$part;
7340: $metathesekeys{$unikey}=1;
7341: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7342: $metaentry{':'.$unikey.'.'.$subp}=$value;
7343: }
7344: if (defined($metaentry{':'.$unikey.'.default'})) {
7345: $metaentry{':'.$unikey}=
7346: $metaentry{':'.$unikey.'.default'};
7347: }
7348: }
7349: }
7350: } else {
7351: #
7352: # This is not a package - some other kind of start tag
7353: #
7354: my $entry=$token->[1];
7355: my $unikey;
7356: if ($entry eq 'import') {
7357: $unikey='';
7358: } else {
7359: $unikey=$entry;
7360: }
7361: $unikey.=&add_prefix_and_part($prefix,$token->[2]->{'part'});
7362:
7363: if (defined($token->[2]->{'id'})) {
7364: $unikey.='_'.$token->[2]->{'id'};
7365: }
7366:
7367: if ($entry eq 'import') {
7368: #
7369: # Importing a library here
7370: #
7371: if ($depthcount<20) {
7372: my $location=$parser->get_text('/import');
7373: my $dir=$filename;
7374: $dir=~s|[^/]*$||;
7375: $location=&filelocation($dir,$location);
7376: my $metadata =
7377: &metadata($uri,'keys', $location,$unikey,
7378: $depthcount+1);
7379: foreach my $meta (split(',',$metadata)) {
7380: $metaentry{':'.$meta}=$metaentry{':'.$meta};
7381: $metathesekeys{$meta}=1;
7382: }
7383: }
7384: } else {
7385:
7386: if (defined($token->[2]->{'name'})) {
7387: $unikey.='_'.$token->[2]->{'name'};
7388: }
7389: $metathesekeys{$unikey}=1;
7390: foreach my $param (@{$token->[3]}) {
7391: $metaentry{':'.$unikey.'.'.$param} =
7392: $token->[2]->{$param};
7393: }
7394: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
7395: my $default=$metaentry{':'.$unikey.'.default'};
7396: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
7397: # only ws inside the tag, and not in default, so use default
7398: # as value
7399: $metaentry{':'.$unikey}=$default;
7400: } elsif ( $internaltext =~ /\S/ ) {
7401: # something interesting inside the tag
7402: $metaentry{':'.$unikey}=$internaltext;
7403: } else {
7404: # no interesting values, don't set a default
7405: }
7406: # end of not-a-package not-a-library import
7407: }
7408: # end of not-a-package start tag
7409: }
7410: # the next is the end of "start tag"
7411: }
7412: }
7413: my ($extension) = ($uri =~ /\.(\w+)$/);
7414: $extension = lc($extension);
7415: if ($extension eq 'htm') { $extension='html'; }
7416:
7417: foreach my $key (keys(%packagetab)) {
7418: #no specific packages #how's our extension
7419: if ($key!~/^extension_\Q$extension\E&/) { next; }
7420: &metadata_create_package_def($uri,$key,'extension_'.$extension,
7421: \%metathesekeys);
7422: }
7423:
7424: if (!exists($metaentry{':packages'})
7425: || $packagetab{"import_defaults&extension_$extension"}) {
7426: foreach my $key (keys(%packagetab)) {
7427: #no specific packages well let's get default then
7428: if ($key!~/^default&/) { next; }
7429: &metadata_create_package_def($uri,$key,'default',
7430: \%metathesekeys);
7431: }
7432: }
7433: # are there custom rights to evaluate
7434: if ($metaentry{':copyright'} eq 'custom') {
7435:
7436: #
7437: # Importing a rights file here
7438: #
7439: unless ($depthcount) {
7440: my $location=$metaentry{':customdistributionfile'};
7441: my $dir=$filename;
7442: $dir=~s|[^/]*$||;
7443: $location=&filelocation($dir,$location);
7444: my $rights_metadata =
7445: &metadata($uri,'keys',$location,'_rights',
7446: $depthcount+1);
7447: foreach my $rights (split(',',$rights_metadata)) {
7448: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
7449: $metathesekeys{$rights}=1;
7450: }
7451: }
7452: }
7453: # uniqifiy package listing
7454: my %seen;
7455: my @uniq_packages =
7456: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
7457: $metaentry{':packages'} = join(',',@uniq_packages);
7458:
7459: $metaentry{':keys'} = join(',',keys(%metathesekeys));
7460: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
7461: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
7462: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
7463: # this is the end of "was not already recently cached
7464: }
7465: return $metaentry{':'.$what};
7466: }
7467:
7468: sub metadata_create_package_def {
7469: my ($uri,$key,$package,$metathesekeys)=@_;
7470: my ($pack,$name,$subp)=split(/\&/,$key);
7471: if ($subp eq 'default') { next; }
7472:
7473: if (defined($metaentry{':packages'})) {
7474: $metaentry{':packages'}.=','.$package;
7475: } else {
7476: $metaentry{':packages'}=$package;
7477: }
7478: my $value=$packagetab{$key};
7479: my $unikey;
7480: $unikey='parameter_0_'.$name;
7481: $metaentry{':'.$unikey.'.part'}=0;
7482: $$metathesekeys{$unikey}=1;
7483: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
7484: $metaentry{':'.$unikey.'.'.$subp}=$value;
7485: }
7486: if (defined($metaentry{':'.$unikey.'.default'})) {
7487: $metaentry{':'.$unikey}=
7488: $metaentry{':'.$unikey.'.default'};
7489: }
7490: }
7491:
7492: sub metadata_generate_part0 {
7493: my ($metadata,$metacache,$uri) = @_;
7494: my %allnames;
7495: foreach my $metakey (keys(%$metadata)) {
7496: if ($metakey=~/^parameter\_(.*)/) {
7497: my $part=$$metacache{':'.$metakey.'.part'};
7498: my $name=$$metacache{':'.$metakey.'.name'};
7499: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
7500: $allnames{$name}=$part;
7501: }
7502: }
7503: }
7504: foreach my $name (keys(%allnames)) {
7505: $$metadata{"parameter_0_$name"}=1;
7506: my $key=":parameter_0_$name";
7507: $$metacache{"$key.part"}='0';
7508: $$metacache{"$key.name"}=$name;
7509: $$metacache{"$key.type"}=$$metacache{':parameter_'.
7510: $allnames{$name}.'_'.$name.
7511: '.type'};
7512: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
7513: '.display'};
7514: my $expr='[Part: '.$allnames{$name}.']';
7515: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
7516: $$metacache{"$key.display"}=$olddis;
7517: }
7518: }
7519:
7520: # ------------------------------------------------------ Devalidate title cache
7521:
7522: sub devalidate_title_cache {
7523: my ($url)=@_;
7524: if (!$env{'request.course.id'}) { return; }
7525: my $symb=&symbread($url);
7526: if (!$symb) { return; }
7527: my $key=$env{'request.course.id'}."\0".$symb;
7528: &devalidate_cache_new('title',$key);
7529: }
7530:
7531: # ------------------------------------------------- Get the title of a resource
7532:
7533: sub gettitle {
7534: my $urlsymb=shift;
7535: my $symb=&symbread($urlsymb);
7536: if ($symb) {
7537: my $key=$env{'request.course.id'}."\0".$symb;
7538: my ($result,$cached)=&is_cached_new('title',$key);
7539: if (defined($cached)) {
7540: return $result;
7541: }
7542: my ($map,$resid,$url)=&decode_symb($symb);
7543: my $title='';
7544: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
7545: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
7546: } else {
7547: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7548: &GDBM_READER(),0640)) {
7549: my $mapid=$bighash{'map_pc_'.&clutter($map)};
7550: $title=$bighash{'title_'.$mapid.'.'.$resid};
7551: untie(%bighash);
7552: }
7553: }
7554: $title=~s/\&colon\;/\:/gs;
7555: if ($title) {
7556: return &do_cache_new('title',$key,$title,600);
7557: }
7558: $urlsymb=$url;
7559: }
7560: my $title=&metadata($urlsymb,'title');
7561: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
7562: return $title;
7563: }
7564:
7565: sub get_slot {
7566: my ($which,$cnum,$cdom)=@_;
7567: if (!$cnum || !$cdom) {
7568: (undef,my $courseid)=&whichuser();
7569: $cdom=$env{'course.'.$courseid.'.domain'};
7570: $cnum=$env{'course.'.$courseid.'.num'};
7571: }
7572: my $key=join("\0",'slots',$cdom,$cnum,$which);
7573: my %slotinfo;
7574: if (exists($remembered{$key})) {
7575: $slotinfo{$which} = $remembered{$key};
7576: } else {
7577: %slotinfo=&get('slots',[$which],$cdom,$cnum);
7578: &Apache::lonhomework::showhash(%slotinfo);
7579: my ($tmp)=keys(%slotinfo);
7580: if ($tmp=~/^error:/) { return (); }
7581: $remembered{$key} = $slotinfo{$which};
7582: }
7583: if (ref($slotinfo{$which}) eq 'HASH') {
7584: return %{$slotinfo{$which}};
7585: }
7586: return $slotinfo{$which};
7587: }
7588: # ------------------------------------------------- Update symbolic store links
7589:
7590: sub symblist {
7591: my ($mapname,%newhash)=@_;
7592: $mapname=&deversion(&declutter($mapname));
7593: my %hash;
7594: if (($env{'request.course.fn'}) && (%newhash)) {
7595: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
7596: &GDBM_WRCREAT(),0640)) {
7597: foreach my $url (keys %newhash) {
7598: next if ($url eq 'last_known'
7599: && $env{'form.no_update_last_known'});
7600: $hash{declutter($url)}=&encode_symb($mapname,
7601: $newhash{$url}->[1],
7602: $newhash{$url}->[0]);
7603: }
7604: if (untie(%hash)) {
7605: return 'ok';
7606: }
7607: }
7608: }
7609: return 'error';
7610: }
7611:
7612: # --------------------------------------------------------------- Verify a symb
7613:
7614: sub symbverify {
7615: my ($symb,$thisurl)=@_;
7616: my $thisfn=$thisurl;
7617: $thisfn=&declutter($thisfn);
7618: # direct jump to resource in page or to a sequence - will construct own symbs
7619: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
7620: # check URL part
7621: my ($map,$resid,$url)=&decode_symb($symb);
7622:
7623: unless ($url eq $thisfn) { return 0; }
7624:
7625: $symb=&symbclean($symb);
7626: $thisurl=&deversion($thisurl);
7627: $thisfn=&deversion($thisfn);
7628:
7629: my %bighash;
7630: my $okay=0;
7631:
7632: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7633: &GDBM_READER(),0640)) {
7634: my $ids=$bighash{'ids_'.&clutter($thisurl)};
7635: unless ($ids) {
7636: $ids=$bighash{'ids_/'.$thisurl};
7637: }
7638: if ($ids) {
7639: # ------------------------------------------------------------------- Has ID(s)
7640: foreach my $id (split(/\,/,$ids)) {
7641: my ($mapid,$resid)=split(/\./,$id);
7642: if (
7643: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
7644: eq $symb) {
7645: if (($env{'request.role.adv'}) ||
7646: $bighash{'encrypted_'.$id} eq $env{'request.enc'}) {
7647: $okay=1;
7648: }
7649: }
7650: }
7651: }
7652: untie(%bighash);
7653: }
7654: return $okay;
7655: }
7656:
7657: # --------------------------------------------------------------- Clean-up symb
7658:
7659: sub symbclean {
7660: my $symb=shift;
7661: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7662: # remove version from map
7663: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
7664:
7665: # remove version from URL
7666: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
7667:
7668: # remove wrapper
7669:
7670: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
7671: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
7672: return $symb;
7673: }
7674:
7675: # ---------------------------------------------- Split symb to find map and url
7676:
7677: sub encode_symb {
7678: my ($map,$resid,$url)=@_;
7679: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
7680: }
7681:
7682: sub decode_symb {
7683: my $symb=shift;
7684: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
7685: my ($map,$resid,$url)=split(/___/,$symb);
7686: return (&fixversion($map),$resid,&fixversion($url));
7687: }
7688:
7689: sub fixversion {
7690: my $fn=shift;
7691: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
7692: my %bighash;
7693: my $uri=&clutter($fn);
7694: my $key=$env{'request.course.id'}.'_'.$uri;
7695: # is this cached?
7696: my ($result,$cached)=&is_cached_new('courseresversion',$key);
7697: if (defined($cached)) { return $result; }
7698: # unfortunately not cached, or expired
7699: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7700: &GDBM_READER(),0640)) {
7701: if ($bighash{'version_'.$uri}) {
7702: my $version=$bighash{'version_'.$uri};
7703: unless (($version eq 'mostrecent') ||
7704: ($version==&getversion($uri))) {
7705: $uri=~s/\.(\w+)$/\.$version\.$1/;
7706: }
7707: }
7708: untie %bighash;
7709: }
7710: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
7711: }
7712:
7713: sub deversion {
7714: my $url=shift;
7715: $url=~s/\.\d+\.(\w+)$/\.$1/;
7716: return $url;
7717: }
7718:
7719: # ------------------------------------------------------ Return symb list entry
7720:
7721: sub symbread {
7722: my ($thisfn,$donotrecurse)=@_;
7723: my $cache_str='request.symbread.cached.'.$thisfn;
7724: if (defined($env{$cache_str})) { return $env{$cache_str}; }
7725: # no filename provided? try from environment
7726: unless ($thisfn) {
7727: if ($env{'request.symb'}) {
7728: return $env{$cache_str}=&symbclean($env{'request.symb'});
7729: }
7730: $thisfn=$env{'request.filename'};
7731: }
7732: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
7733: # is that filename actually a symb? Verify, clean, and return
7734: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
7735: if (&symbverify($thisfn,$1)) {
7736: return $env{$cache_str}=&symbclean($thisfn);
7737: }
7738: }
7739: $thisfn=declutter($thisfn);
7740: my %hash;
7741: my %bighash;
7742: my $syval='';
7743: if (($env{'request.course.fn'}) && ($thisfn)) {
7744: my $targetfn = $thisfn;
7745: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
7746: $targetfn = 'adm/wrapper/'.$thisfn;
7747: }
7748: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
7749: $targetfn=$1;
7750: }
7751: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
7752: &GDBM_READER(),0640)) {
7753: $syval=$hash{$targetfn};
7754: untie(%hash);
7755: }
7756: # ---------------------------------------------------------- There was an entry
7757: if ($syval) {
7758: #unless ($syval=~/\_\d+$/) {
7759: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
7760: #&appenv({'request.ambiguous' => $thisfn});
7761: #return $env{$cache_str}='';
7762: #}
7763: #$syval.=$1;
7764: #}
7765: } else {
7766: # ------------------------------------------------------- Was not in symb table
7767: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
7768: &GDBM_READER(),0640)) {
7769: # ---------------------------------------------- Get ID(s) for current resource
7770: my $ids=$bighash{'ids_'.&clutter($thisfn)};
7771: unless ($ids) {
7772: $ids=$bighash{'ids_/'.$thisfn};
7773: }
7774: unless ($ids) {
7775: # alias?
7776: $ids=$bighash{'mapalias_'.$thisfn};
7777: }
7778: if ($ids) {
7779: # ------------------------------------------------------------------- Has ID(s)
7780: my @possibilities=split(/\,/,$ids);
7781: if ($#possibilities==0) {
7782: # ----------------------------------------------- There is only one possibility
7783: my ($mapid,$resid)=split(/\./,$ids);
7784: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7785: $resid,$thisfn);
7786: } elsif (!$donotrecurse) {
7787: # ------------------------------------------ There is more than one possibility
7788: my $realpossible=0;
7789: foreach my $id (@possibilities) {
7790: my $file=$bighash{'src_'.$id};
7791: if (&allowed('bre',$file)) {
7792: my ($mapid,$resid)=split(/\./,$id);
7793: if ($bighash{'map_type_'.$mapid} ne 'page') {
7794: $realpossible++;
7795: $syval=&encode_symb($bighash{'map_id_'.$mapid},
7796: $resid,$thisfn);
7797: }
7798: }
7799: }
7800: if ($realpossible!=1) { $syval=''; }
7801: } else {
7802: $syval='';
7803: }
7804: }
7805: untie(%bighash)
7806: }
7807: }
7808: if ($syval) {
7809: return $env{$cache_str}=$syval;
7810: }
7811: }
7812: &appenv({'request.ambiguous' => $thisfn});
7813: return $env{$cache_str}='';
7814: }
7815:
7816: # ---------------------------------------------------------- Return random seed
7817:
7818: sub numval {
7819: my $txt=shift;
7820: $txt=~tr/A-J/0-9/;
7821: $txt=~tr/a-j/0-9/;
7822: $txt=~tr/K-T/0-9/;
7823: $txt=~tr/k-t/0-9/;
7824: $txt=~tr/U-Z/0-5/;
7825: $txt=~tr/u-z/0-5/;
7826: $txt=~s/\D//g;
7827: if ($_64bit) { if ($txt > 2**32) { return -1; } }
7828: return int($txt);
7829: }
7830:
7831: sub numval2 {
7832: my $txt=shift;
7833: $txt=~tr/A-J/0-9/;
7834: $txt=~tr/a-j/0-9/;
7835: $txt=~tr/K-T/0-9/;
7836: $txt=~tr/k-t/0-9/;
7837: $txt=~tr/U-Z/0-5/;
7838: $txt=~tr/u-z/0-5/;
7839: $txt=~s/\D//g;
7840: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7841: my $total;
7842: foreach my $val (@txts) { $total+=$val; }
7843: if ($_64bit) { if ($total > 2**32) { return -1; } }
7844: return int($total);
7845: }
7846:
7847: sub numval3 {
7848: use integer;
7849: my $txt=shift;
7850: $txt=~tr/A-J/0-9/;
7851: $txt=~tr/a-j/0-9/;
7852: $txt=~tr/K-T/0-9/;
7853: $txt=~tr/k-t/0-9/;
7854: $txt=~tr/U-Z/0-5/;
7855: $txt=~tr/u-z/0-5/;
7856: $txt=~s/\D//g;
7857: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
7858: my $total;
7859: foreach my $val (@txts) { $total+=$val; }
7860: if ($_64bit) { $total=(($total<<32)>>32); }
7861: return $total;
7862: }
7863:
7864: sub digest {
7865: my ($data)=@_;
7866: my $digest=&Digest::MD5::md5($data);
7867: my ($a,$b,$c,$d)=unpack("iiii",$digest);
7868: my ($e,$f);
7869: {
7870: use integer;
7871: $e=($a+$b);
7872: $f=($c+$d);
7873: if ($_64bit) {
7874: $e=(($e<<32)>>32);
7875: $f=(($f<<32)>>32);
7876: }
7877: }
7878: if (wantarray) {
7879: return ($e,$f);
7880: } else {
7881: my $g;
7882: {
7883: use integer;
7884: $g=($e+$f);
7885: if ($_64bit) {
7886: $g=(($g<<32)>>32);
7887: }
7888: }
7889: return $g;
7890: }
7891: }
7892:
7893: sub latest_rnd_algorithm_id {
7894: return '64bit5';
7895: }
7896:
7897: sub get_rand_alg {
7898: my ($courseid)=@_;
7899: if (!$courseid) { $courseid=(&whichuser())[1]; }
7900: if ($courseid) {
7901: return $env{"course.$courseid.rndseed"};
7902: }
7903: return &latest_rnd_algorithm_id();
7904: }
7905:
7906: sub validCODE {
7907: my ($CODE)=@_;
7908: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
7909: return 0;
7910: }
7911:
7912: sub getCODE {
7913: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
7914: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
7915: defined($Apache::lonhomework::parsing_a_task) ) &&
7916: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
7917: return $Apache::lonhomework::history{'resource.CODE'};
7918: }
7919: return undef;
7920: }
7921:
7922: sub rndseed {
7923: my ($symb,$courseid,$domain,$username)=@_;
7924: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
7925: if (!defined($symb)) {
7926: unless ($symb=$wsymb) { return time; }
7927: }
7928: if (!$courseid) { $courseid=$wcourseid; }
7929: if (!$domain) { $domain=$wdomain; }
7930: if (!$username) { $username=$wusername }
7931: my $which=&get_rand_alg();
7932:
7933: if (defined(&getCODE())) {
7934: if ($which eq '64bit5') {
7935: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
7936: } elsif ($which eq '64bit4') {
7937: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
7938: } else {
7939: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
7940: }
7941: } elsif ($which eq '64bit5') {
7942: return &rndseed_64bit5($symb,$courseid,$domain,$username);
7943: } elsif ($which eq '64bit4') {
7944: return &rndseed_64bit4($symb,$courseid,$domain,$username);
7945: } elsif ($which eq '64bit3') {
7946: return &rndseed_64bit3($symb,$courseid,$domain,$username);
7947: } elsif ($which eq '64bit2') {
7948: return &rndseed_64bit2($symb,$courseid,$domain,$username);
7949: } elsif ($which eq '64bit') {
7950: return &rndseed_64bit($symb,$courseid,$domain,$username);
7951: }
7952: return &rndseed_32bit($symb,$courseid,$domain,$username);
7953: }
7954:
7955: sub rndseed_32bit {
7956: my ($symb,$courseid,$domain,$username)=@_;
7957: {
7958: use integer;
7959: my $symbchck=unpack("%32C*",$symb) << 27;
7960: my $symbseed=numval($symb) << 22;
7961: my $namechck=unpack("%32C*",$username) << 17;
7962: my $nameseed=numval($username) << 12;
7963: my $domainseed=unpack("%32C*",$domain) << 7;
7964: my $courseseed=unpack("%32C*",$courseid);
7965: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
7966: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7967: #&logthis("rndseed :$num:$symb");
7968: if ($_64bit) { $num=(($num<<32)>>32); }
7969: return $num;
7970: }
7971: }
7972:
7973: sub rndseed_64bit {
7974: my ($symb,$courseid,$domain,$username)=@_;
7975: {
7976: use integer;
7977: my $symbchck=unpack("%32S*",$symb) << 21;
7978: my $symbseed=numval($symb) << 10;
7979: my $namechck=unpack("%32S*",$username);
7980:
7981: my $nameseed=numval($username) << 21;
7982: my $domainseed=unpack("%32S*",$domain) << 10;
7983: my $courseseed=unpack("%32S*",$courseid);
7984:
7985: my $num1=$symbchck+$symbseed+$namechck;
7986: my $num2=$nameseed+$domainseed+$courseseed;
7987: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
7988: #&logthis("rndseed :$num:$symb");
7989: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
7990: return "$num1,$num2";
7991: }
7992: }
7993:
7994: sub rndseed_64bit2 {
7995: my ($symb,$courseid,$domain,$username)=@_;
7996: {
7997: use integer;
7998: # strings need to be an even # of cahracters long, it it is odd the
7999: # last characters gets thrown away
8000: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8001: my $symbseed=numval($symb) << 10;
8002: my $namechck=unpack("%32S*",$username.' ');
8003:
8004: my $nameseed=numval($username) << 21;
8005: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8006: my $courseseed=unpack("%32S*",$courseid.' ');
8007:
8008: my $num1=$symbchck+$symbseed+$namechck;
8009: my $num2=$nameseed+$domainseed+$courseseed;
8010: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8011: #&logthis("rndseed :$num:$symb");
8012: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8013: return "$num1,$num2";
8014: }
8015: }
8016:
8017: sub rndseed_64bit3 {
8018: my ($symb,$courseid,$domain,$username)=@_;
8019: {
8020: use integer;
8021: # strings need to be an even # of cahracters long, it it is odd the
8022: # last characters gets thrown away
8023: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8024: my $symbseed=numval2($symb) << 10;
8025: my $namechck=unpack("%32S*",$username.' ');
8026:
8027: my $nameseed=numval2($username) << 21;
8028: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8029: my $courseseed=unpack("%32S*",$courseid.' ');
8030:
8031: my $num1=$symbchck+$symbseed+$namechck;
8032: my $num2=$nameseed+$domainseed+$courseseed;
8033: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8034: #&logthis("rndseed :$num1:$num2:$_64bit");
8035: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8036:
8037: return "$num1:$num2";
8038: }
8039: }
8040:
8041: sub rndseed_64bit4 {
8042: my ($symb,$courseid,$domain,$username)=@_;
8043: {
8044: use integer;
8045: # strings need to be an even # of cahracters long, it it is odd the
8046: # last characters gets thrown away
8047: my $symbchck=unpack("%32S*",$symb.' ') << 21;
8048: my $symbseed=numval3($symb) << 10;
8049: my $namechck=unpack("%32S*",$username.' ');
8050:
8051: my $nameseed=numval3($username) << 21;
8052: my $domainseed=unpack("%32S*",$domain.' ') << 10;
8053: my $courseseed=unpack("%32S*",$courseid.' ');
8054:
8055: my $num1=$symbchck+$symbseed+$namechck;
8056: my $num2=$nameseed+$domainseed+$courseseed;
8057: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
8058: #&logthis("rndseed :$num1:$num2:$_64bit");
8059: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
8060:
8061: return "$num1:$num2";
8062: }
8063: }
8064:
8065: sub rndseed_64bit5 {
8066: my ($symb,$courseid,$domain,$username)=@_;
8067: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
8068: return "$num1:$num2";
8069: }
8070:
8071: sub rndseed_CODE_64bit {
8072: my ($symb,$courseid,$domain,$username)=@_;
8073: {
8074: use integer;
8075: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8076: my $symbseed=numval2($symb);
8077: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8078: my $CODEseed=numval(&getCODE());
8079: my $courseseed=unpack("%32S*",$courseid.' ');
8080: my $num1=$symbseed+$CODEchck;
8081: my $num2=$CODEseed+$courseseed+$symbchck;
8082: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8083: #&logthis("rndseed :$num1:$num2:$symb");
8084: if ($_64bit) { $num1=(($num1<<32)>>32); }
8085: if ($_64bit) { $num2=(($num2<<32)>>32); }
8086: return "$num1:$num2";
8087: }
8088: }
8089:
8090: sub rndseed_CODE_64bit4 {
8091: my ($symb,$courseid,$domain,$username)=@_;
8092: {
8093: use integer;
8094: my $symbchck=unpack("%32S*",$symb.' ') << 16;
8095: my $symbseed=numval3($symb);
8096: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
8097: my $CODEseed=numval3(&getCODE());
8098: my $courseseed=unpack("%32S*",$courseid.' ');
8099: my $num1=$symbseed+$CODEchck;
8100: my $num2=$CODEseed+$courseseed+$symbchck;
8101: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
8102: #&logthis("rndseed :$num1:$num2:$symb");
8103: if ($_64bit) { $num1=(($num1<<32)>>32); }
8104: if ($_64bit) { $num2=(($num2<<32)>>32); }
8105: return "$num1:$num2";
8106: }
8107: }
8108:
8109: sub rndseed_CODE_64bit5 {
8110: my ($symb,$courseid,$domain,$username)=@_;
8111: my $code = &getCODE();
8112: my ($num1,$num2)=&digest("$symb,$courseid,$code");
8113: return "$num1:$num2";
8114: }
8115:
8116: sub setup_random_from_rndseed {
8117: my ($rndseed)=@_;
8118: if ($rndseed =~/([,:])/) {
8119: my ($num1,$num2)=split(/[,:]/,$rndseed);
8120: &Math::Random::random_set_seed(abs($num1),abs($num2));
8121: } else {
8122: &Math::Random::random_set_seed_from_phrase($rndseed);
8123: }
8124: }
8125:
8126: sub latest_receipt_algorithm_id {
8127: return 'receipt3';
8128: }
8129:
8130: sub recunique {
8131: my $fucourseid=shift;
8132: my $unique;
8133: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
8134: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8135: $unique=$env{"course.$fucourseid.internal.encseed"};
8136: } else {
8137: $unique=$perlvar{'lonReceipt'};
8138: }
8139: return unpack("%32C*",$unique);
8140: }
8141:
8142: sub recprefix {
8143: my $fucourseid=shift;
8144: my $prefix;
8145: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
8146: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
8147: $prefix=$env{"course.$fucourseid.internal.encpref"};
8148: } else {
8149: $prefix=$perlvar{'lonHostID'};
8150: }
8151: return unpack("%32C*",$prefix);
8152: }
8153:
8154: sub ireceipt {
8155: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
8156:
8157: my $return =&recprefix($fucourseid).'-';
8158:
8159: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
8160: $env{'request.state'} eq 'construct') {
8161: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
8162: return $return;
8163: }
8164:
8165: my $cuname=unpack("%32C*",$funame);
8166: my $cudom=unpack("%32C*",$fudom);
8167: my $cucourseid=unpack("%32C*",$fucourseid);
8168: my $cusymb=unpack("%32C*",$fusymb);
8169: my $cunique=&recunique($fucourseid);
8170: my $cpart=unpack("%32S*",$part);
8171: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
8172:
8173: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
8174:
8175: $return.= ($cunique%$cuname+
8176: $cunique%$cudom+
8177: $cusymb%$cuname+
8178: $cusymb%$cudom+
8179: $cucourseid%$cuname+
8180: $cucourseid%$cudom+
8181: $cpart%$cuname+
8182: $cpart%$cudom);
8183: } else {
8184: $return.= ($cunique%$cuname+
8185: $cunique%$cudom+
8186: $cusymb%$cuname+
8187: $cusymb%$cudom+
8188: $cucourseid%$cuname+
8189: $cucourseid%$cudom);
8190: }
8191: return $return;
8192: }
8193:
8194: sub receipt {
8195: my ($part)=@_;
8196: my ($symb,$courseid,$domain,$name) = &whichuser();
8197: return &ireceipt($name,$domain,$courseid,$symb,$part);
8198: }
8199:
8200: sub whichuser {
8201: my ($passedsymb)=@_;
8202: my ($symb,$courseid,$domain,$name,$publicuser);
8203: if (defined($env{'form.grade_symb'})) {
8204: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
8205: my $allowed=&allowed('vgr',$tmp_courseid);
8206: if (!$allowed &&
8207: exists($env{'request.course.sec'}) &&
8208: $env{'request.course.sec'} !~ /^\s*$/) {
8209: $allowed=&allowed('vgr',$tmp_courseid.
8210: '/'.$env{'request.course.sec'});
8211: }
8212: if ($allowed) {
8213: ($symb)=&get_env_multiple('form.grade_symb');
8214: $courseid=$tmp_courseid;
8215: ($domain)=&get_env_multiple('form.grade_domain');
8216: ($name)=&get_env_multiple('form.grade_username');
8217: return ($symb,$courseid,$domain,$name,$publicuser);
8218: }
8219: }
8220: if (!$passedsymb) {
8221: $symb=&symbread();
8222: } else {
8223: $symb=$passedsymb;
8224: }
8225: $courseid=$env{'request.course.id'};
8226: $domain=$env{'user.domain'};
8227: $name=$env{'user.name'};
8228: if ($name eq 'public' && $domain eq 'public') {
8229: if (!defined($env{'form.username'})) {
8230: $env{'form.username'}.=time.rand(10000000);
8231: }
8232: $name.=$env{'form.username'};
8233: }
8234: return ($symb,$courseid,$domain,$name,$publicuser);
8235:
8236: }
8237:
8238: # ------------------------------------------------------------ Serves up a file
8239: # returns either the contents of the file or
8240: # -1 if the file doesn't exist
8241: #
8242: # if the target is a file that was uploaded via DOCS,
8243: # a check will be made to see if a current copy exists on the local server,
8244: # if it does this will be served, otherwise a copy will be retrieved from
8245: # the home server for the course and stored in /home/httpd/html/userfiles on
8246: # the local server.
8247:
8248: sub getfile {
8249: my ($file) = @_;
8250: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8251: &repcopy($file);
8252: return &readfile($file);
8253: }
8254:
8255: sub repcopy_userfile {
8256: my ($file)=@_;
8257: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
8258: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
8259: my ($cdom,$cnum,$filename) =
8260: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
8261: my $uri="/uploaded/$cdom/$cnum/$filename";
8262: if (-e "$file") {
8263: # we already have a local copy, check it out
8264: my @fileinfo = stat($file);
8265: my $rtncode;
8266: my $info;
8267: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
8268: if ($lwpresp ne 'ok') {
8269: # there is no such file anymore, even though we had a local copy
8270: if ($rtncode eq '404') {
8271: unlink($file);
8272: }
8273: return -1;
8274: }
8275: if ($info < $fileinfo[9]) {
8276: # nice, the file we have is up-to-date, just say okay
8277: return 'ok';
8278: } else {
8279: # the file is outdated, get rid of it
8280: unlink($file);
8281: }
8282: }
8283: # one way or the other, at this point, we don't have the file
8284: # construct the correct path for the file
8285: my @parts = ($cdom,$cnum);
8286: if ($filename =~ m|^(.+)/[^/]+$|) {
8287: push @parts, split(/\//,$1);
8288: }
8289: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
8290: foreach my $part (@parts) {
8291: $path .= '/'.$part;
8292: if (!-e $path) {
8293: mkdir($path,0770);
8294: }
8295: }
8296: # now the path exists for sure
8297: # get a user agent
8298: my $ua=new LWP::UserAgent;
8299: my $transferfile=$file.'.in.transfer';
8300: # FIXME: this should flock
8301: if (-e $transferfile) { return 'ok'; }
8302: my $request;
8303: $uri=~s/^\///;
8304: my $homeserver = &homeserver($cnum,$cdom);
8305: my $protocol = $protocol{$homeserver};
8306: $protocol = 'http' if ($protocol ne 'https');
8307: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
8308: my $response=$ua->request($request,$transferfile);
8309: # did it work?
8310: if ($response->is_error()) {
8311: unlink($transferfile);
8312: &logthis("Userfile repcopy failed for $uri");
8313: return -1;
8314: }
8315: # worked, rename the transfer file
8316: rename($transferfile,$file);
8317: return 'ok';
8318: }
8319:
8320: sub tokenwrapper {
8321: my $uri=shift;
8322: $uri=~s|^https?\://([^/]+)||;
8323: $uri=~s|^/||;
8324: $env{'user.environment'}=~/\/([^\/]+)\.id/;
8325: my $token=$1;
8326: my (undef,$udom,$uname,$file)=split('/',$uri,4);
8327: if ($udom && $uname && $file) {
8328: $file=~s|(\?\.*)*$||;
8329: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
8330: my $homeserver = &homeserver($uname,$udom);
8331: my $protocol = $protocol{$homeserver};
8332: $protocol = 'http' if ($protocol ne 'https');
8333: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
8334: (($uri=~/\?/)?'&':'?').'token='.$token.
8335: '&tokenissued='.$perlvar{'lonHostID'};
8336: } else {
8337: return '/adm/notfound.html';
8338: }
8339: }
8340:
8341: # call with reqtype HEAD: get last modification time
8342: # call with reqtype GET: get the file contents
8343: # Do not call this with reqtype GET for large files! It loads everything into memory
8344: #
8345: sub getuploaded {
8346: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
8347: $uri=~s/^\///;
8348: my $homeserver = &homeserver($cnum,$cdom);
8349: my $protocol = $protocol{$homeserver};
8350: $protocol = 'http' if ($protocol ne 'https');
8351: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
8352: my $ua=new LWP::UserAgent;
8353: my $request=new HTTP::Request($reqtype,$uri);
8354: my $response=$ua->request($request);
8355: $$rtncode = $response->code;
8356: if (! $response->is_success()) {
8357: return 'failed';
8358: }
8359: if ($reqtype eq 'HEAD') {
8360: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
8361: } elsif ($reqtype eq 'GET') {
8362: $$info = $response->content;
8363: }
8364: return 'ok';
8365: }
8366:
8367: sub readfile {
8368: my $file = shift;
8369: if ( (! -e $file ) || ($file eq '') ) { return -1; };
8370: my $fh;
8371: open($fh,"<$file");
8372: my $a='';
8373: while (my $line = <$fh>) { $a .= $line; }
8374: return $a;
8375: }
8376:
8377: sub filelocation {
8378: my ($dir,$file) = @_;
8379: my $location;
8380: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
8381:
8382: if ($file =~ m-^/adm/-) {
8383: $file=~s-^/adm/wrapper/-/-;
8384: $file=~s-^/adm/coursedocs/showdoc/-/-;
8385: }
8386:
8387: if ($file=~m:^/~:) { # is a contruction space reference
8388: $location = $file;
8389: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
8390: } elsif ($file=~m{^/home/$match_username/public_html/}) {
8391: # is a correct contruction space reference
8392: $location = $file;
8393: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
8394: $location = $file;
8395: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
8396: my ($udom,$uname,$filename)=
8397: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
8398: my $home=&homeserver($uname,$udom);
8399: my $is_me=0;
8400: my @ids=¤t_machine_ids();
8401: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
8402: if ($is_me) {
8403: $location=&propath($udom,$uname).'/userfiles/'.$filename;
8404: } else {
8405: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
8406: $udom.'/'.$uname.'/'.$filename;
8407: }
8408: } elsif ($file =~ m-^/adm/-) {
8409: $location = $perlvar{'lonDocRoot'}.'/'.$file;
8410: } else {
8411: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8412: $file=~s:^/res/:/:;
8413: if ( !( $file =~ m:^/:) ) {
8414: $location = $dir. '/'.$file;
8415: } else {
8416: $location = '/home/httpd/html/res'.$file;
8417: }
8418: }
8419: $location=~s://+:/:g; # remove duplicate /
8420: while ($location=~m{/\.\./}) {
8421: if ($location =~ m{/[^/]+/\.\./}) {
8422: $location=~ s{/[^/]+/\.\./}{/}g;
8423: } else {
8424: $location=~ s{/\.\./}{/}g;
8425: }
8426: } #remove dir/..
8427: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
8428: return $location;
8429: }
8430:
8431: sub hreflocation {
8432: my ($dir,$file)=@_;
8433: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
8434: $file=filelocation($dir,$file);
8435: } elsif ($file=~m-^/adm/-) {
8436: $file=~s-^/adm/wrapper/-/-;
8437: $file=~s-^/adm/coursedocs/showdoc/-/-;
8438: }
8439: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
8440: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
8441: } elsif ($file=~m-/home/($match_username)/public_html/-) {
8442: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
8443: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
8444: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
8445: -/uploaded/$1/$2/-x;
8446: }
8447: if ($file=~ m{^/userfiles/}) {
8448: $file =~ s{^/userfiles/}{/uploaded/};
8449: }
8450: return $file;
8451: }
8452:
8453: sub current_machine_domains {
8454: return &machine_domains(&hostname($perlvar{'lonHostID'}));
8455: }
8456:
8457: sub machine_domains {
8458: my ($hostname) = @_;
8459: my @domains;
8460: my %hostname = &all_hostnames();
8461: while( my($id, $name) = each(%hostname)) {
8462: # &logthis("-$id-$name-$hostname-");
8463: if ($hostname eq $name) {
8464: push(@domains,&host_domain($id));
8465: }
8466: }
8467: return @domains;
8468: }
8469:
8470: sub current_machine_ids {
8471: return &machine_ids(&hostname($perlvar{'lonHostID'}));
8472: }
8473:
8474: sub machine_ids {
8475: my ($hostname) = @_;
8476: $hostname ||= &hostname($perlvar{'lonHostID'});
8477: my @ids;
8478: my %name_to_host = &all_names();
8479: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
8480: return @{ $name_to_host{$hostname} };
8481: }
8482: return;
8483: }
8484:
8485: sub additional_machine_domains {
8486: my @domains;
8487: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
8488: while( my $line = <$fh>) {
8489: $line =~ s/\s//g;
8490: push(@domains,$line);
8491: }
8492: return @domains;
8493: }
8494:
8495: sub default_login_domain {
8496: my $domain = $perlvar{'lonDefDomain'};
8497: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
8498: foreach my $posdom (¤t_machine_domains(),
8499: &additional_machine_domains()) {
8500: if (lc($posdom) eq lc($testdomain)) {
8501: $domain=$posdom;
8502: last;
8503: }
8504: }
8505: return $domain;
8506: }
8507:
8508: # ------------------------------------------------------------- Declutters URLs
8509:
8510: sub declutter {
8511: my $thisfn=shift;
8512: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
8513: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
8514: $thisfn=~s/^\///;
8515: $thisfn=~s|^adm/wrapper/||;
8516: $thisfn=~s|^adm/coursedocs/showdoc/||;
8517: $thisfn=~s/^res\///;
8518: $thisfn=~s/\?.+$//;
8519: return $thisfn;
8520: }
8521:
8522: # ------------------------------------------------------------- Clutter up URLs
8523:
8524: sub clutter {
8525: my $thisfn='/'.&declutter(shift);
8526: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
8527: || $thisfn =~ m{^/adm/(includes|pages)} ) {
8528: $thisfn='/res'.$thisfn;
8529: }
8530: if ($thisfn !~m|/adm|) {
8531: if ($thisfn =~ m|/ext/|) {
8532: $thisfn='/adm/wrapper'.$thisfn;
8533: } else {
8534: my ($ext) = ($thisfn =~ /\.(\w+)$/);
8535: my $embstyle=&Apache::loncommon::fileembstyle($ext);
8536: if ($embstyle eq 'ssi'
8537: || ($embstyle eq 'hdn')
8538: || ($embstyle eq 'rat')
8539: || ($embstyle eq 'prv')
8540: || ($embstyle eq 'ign')) {
8541: #do nothing with these
8542: } elsif (($embstyle eq 'img')
8543: || ($embstyle eq 'emb')
8544: || ($embstyle eq 'wrp')) {
8545: $thisfn='/adm/wrapper'.$thisfn;
8546: } elsif ($embstyle eq 'unk'
8547: && $thisfn!~/\.(sequence|page)$/) {
8548: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
8549: } else {
8550: # &logthis("Got a blank emb style");
8551: }
8552: }
8553: }
8554: return $thisfn;
8555: }
8556:
8557: sub clutter_with_no_wrapper {
8558: my $uri = &clutter(shift);
8559: if ($uri =~ m-^/adm/-) {
8560: $uri =~ s-^/adm/wrapper/-/-;
8561: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
8562: }
8563: return $uri;
8564: }
8565:
8566: sub freeze_escape {
8567: my ($value)=@_;
8568: if (ref($value)) {
8569: $value=&nfreeze($value);
8570: return '__FROZEN__'.&escape($value);
8571: }
8572: return &escape($value);
8573: }
8574:
8575:
8576: sub thaw_unescape {
8577: my ($value)=@_;
8578: if ($value =~ /^__FROZEN__/) {
8579: substr($value,0,10,undef);
8580: $value=&unescape($value);
8581: return &thaw($value);
8582: }
8583: return &unescape($value);
8584: }
8585:
8586: sub correct_line_ends {
8587: my ($result)=@_;
8588: $$result =~s/\r\n/\n/mg;
8589: $$result =~s/\r/\n/mg;
8590: }
8591: # ================================================================ Main Program
8592:
8593: sub goodbye {
8594: &logthis("Starting Shut down");
8595: #not converted to using infrastruture and probably shouldn't be
8596: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
8597: #converted
8598: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
8599: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
8600: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
8601: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
8602: #1.1 only
8603: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
8604: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
8605: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
8606: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
8607: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
8608: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
8609: &logthis(sprintf("%-20s is %s",'hits',$hits));
8610: &flushcourselogs();
8611: &logthis("Shutting down");
8612: }
8613:
8614: sub get_dns {
8615: my ($url,$func,$ignore_cache) = @_;
8616: if (!$ignore_cache) {
8617: my ($content,$cached)=
8618: &Apache::lonnet::is_cached_new('dns',$url);
8619: if ($cached) {
8620: &$func($content);
8621: return;
8622: }
8623: }
8624:
8625: my %alldns;
8626: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8627: foreach my $dns (<$config>) {
8628: next if ($dns !~ /^\^(\S*)/x);
8629: my $line = $1;
8630: my ($host,$protocol) = split(/:/,$line);
8631: if ($protocol ne 'https') {
8632: $protocol = 'http';
8633: }
8634: $alldns{$host} = $protocol;
8635: }
8636: while (%alldns) {
8637: my ($dns) = keys(%alldns);
8638: my $ua=new LWP::UserAgent;
8639: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
8640: my $response=$ua->request($request);
8641: delete($alldns{$dns});
8642: next if ($response->is_error());
8643: my @content = split("\n",$response->content);
8644: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
8645: &$func(\@content);
8646: return;
8647: }
8648: close($config);
8649: my $which = (split('/',$url))[3];
8650: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
8651: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
8652: my @content = <$config>;
8653: &$func(\@content);
8654: return;
8655: }
8656: # ------------------------------------------------------------ Read domain file
8657: {
8658: my $loaded;
8659: my %domain;
8660:
8661: sub parse_domain_tab {
8662: my ($lines) = @_;
8663: foreach my $line (@$lines) {
8664: next if ($line =~ /^(\#|\s*$ )/x);
8665:
8666: chomp($line);
8667: my ($name,@elements) = split(/:/,$line,9);
8668: my %this_domain;
8669: foreach my $field ('description', 'auth_def', 'auth_arg_def',
8670: 'lang_def', 'city', 'longi', 'lati',
8671: 'primary') {
8672: $this_domain{$field} = shift(@elements);
8673: }
8674: $domain{$name} = \%this_domain;
8675: }
8676: }
8677:
8678: sub reset_domain_info {
8679: undef($loaded);
8680: undef(%domain);
8681: }
8682:
8683: sub load_domain_tab {
8684: my ($ignore_cache) = @_;
8685: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
8686: my $fh;
8687: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
8688: my @lines = <$fh>;
8689: &parse_domain_tab(\@lines);
8690: }
8691: close($fh);
8692: $loaded = 1;
8693: }
8694:
8695: sub domain {
8696: &load_domain_tab() if (!$loaded);
8697:
8698: my ($name,$what) = @_;
8699: return if ( !exists($domain{$name}) );
8700:
8701: if (!$what) {
8702: return $domain{$name}{'description'};
8703: }
8704: return $domain{$name}{$what};
8705: }
8706:
8707: sub domain_info {
8708: &load_domain_tab() if (!$loaded);
8709: return %domain;
8710: }
8711:
8712: }
8713:
8714:
8715: # ------------------------------------------------------------- Read hosts file
8716: {
8717: my %hostname;
8718: my %hostdom;
8719: my %libserv;
8720: my $loaded;
8721: my %name_to_host;
8722:
8723: sub parse_hosts_tab {
8724: my ($file) = @_;
8725: foreach my $configline (@$file) {
8726: next if ($configline =~ /^(\#|\s*$ )/x);
8727: next if ($configline =~ /^\^/);
8728: chomp($configline);
8729: my ($id,$domain,$role,$name,$protocol)=split(/:/,$configline);
8730: $name=~s/\s//g;
8731: if ($id && $domain && $role && $name) {
8732: $hostname{$id}=$name;
8733: push(@{$name_to_host{$name}}, $id);
8734: $hostdom{$id}=$domain;
8735: if ($role eq 'library') { $libserv{$id}=$name; }
8736: if (defined($protocol)) {
8737: if ($protocol eq 'https') {
8738: $protocol{$id} = $protocol;
8739: } else {
8740: $protocol{$id} = 'http';
8741: }
8742: } else {
8743: $protocol{$id} = 'http';
8744: }
8745: }
8746: }
8747: }
8748:
8749: sub reset_hosts_info {
8750: &purge_remembered();
8751: &reset_domain_info();
8752: &reset_hosts_ip_info();
8753: undef(%name_to_host);
8754: undef(%hostname);
8755: undef(%hostdom);
8756: undef(%libserv);
8757: undef($loaded);
8758: }
8759:
8760: sub load_hosts_tab {
8761: my ($ignore_cache) = @_;
8762: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
8763: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
8764: my @config = <$config>;
8765: &parse_hosts_tab(\@config);
8766: close($config);
8767: $loaded=1;
8768: }
8769:
8770: sub hostname {
8771: &load_hosts_tab() if (!$loaded);
8772:
8773: my ($lonid) = @_;
8774: return $hostname{$lonid};
8775: }
8776:
8777: sub all_hostnames {
8778: &load_hosts_tab() if (!$loaded);
8779:
8780: return %hostname;
8781: }
8782:
8783: sub all_names {
8784: &load_hosts_tab() if (!$loaded);
8785:
8786: return %name_to_host;
8787: }
8788:
8789: sub all_host_domain {
8790: &load_hosts_tab() if (!$loaded);
8791: return %hostdom;
8792: }
8793:
8794: sub is_library {
8795: &load_hosts_tab() if (!$loaded);
8796:
8797: return exists($libserv{$_[0]});
8798: }
8799:
8800: sub all_library {
8801: &load_hosts_tab() if (!$loaded);
8802:
8803: return %libserv;
8804: }
8805:
8806: sub get_servers {
8807: &load_hosts_tab() if (!$loaded);
8808:
8809: my ($domain,$type) = @_;
8810: my %possible_hosts = ($type eq 'library') ? %libserv
8811: : %hostname;
8812: my %result;
8813: if (ref($domain) eq 'ARRAY') {
8814: while ( my ($host,$hostname) = each(%possible_hosts)) {
8815: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
8816: $result{$host} = $hostname;
8817: }
8818: }
8819: } else {
8820: while ( my ($host,$hostname) = each(%possible_hosts)) {
8821: if ($hostdom{$host} eq $domain) {
8822: $result{$host} = $hostname;
8823: }
8824: }
8825: }
8826: return %result;
8827: }
8828:
8829: sub host_domain {
8830: &load_hosts_tab() if (!$loaded);
8831:
8832: my ($lonid) = @_;
8833: return $hostdom{$lonid};
8834: }
8835:
8836: sub all_domains {
8837: &load_hosts_tab() if (!$loaded);
8838:
8839: my %seen;
8840: my @uniq = grep(!$seen{$_}++, values(%hostdom));
8841: return @uniq;
8842: }
8843: }
8844:
8845: {
8846: my %iphost;
8847: my %name_to_ip;
8848: my %lonid_to_ip;
8849:
8850: sub get_hosts_from_ip {
8851: my ($ip) = @_;
8852: my %iphosts = &get_iphost();
8853: if (ref($iphosts{$ip})) {
8854: return @{$iphosts{$ip}};
8855: }
8856: return;
8857: }
8858:
8859: sub reset_hosts_ip_info {
8860: undef(%iphost);
8861: undef(%name_to_ip);
8862: undef(%lonid_to_ip);
8863: }
8864:
8865: sub get_host_ip {
8866: my ($lonid) = @_;
8867: if (exists($lonid_to_ip{$lonid})) {
8868: return $lonid_to_ip{$lonid};
8869: }
8870: my $name=&hostname($lonid);
8871: my $ip = gethostbyname($name);
8872: return if (!$ip || length($ip) ne 4);
8873: $ip=inet_ntoa($ip);
8874: $name_to_ip{$name} = $ip;
8875: $lonid_to_ip{$lonid} = $ip;
8876: return $ip;
8877: }
8878:
8879: sub get_iphost {
8880: my ($ignore_cache) = @_;
8881:
8882: if (!$ignore_cache) {
8883: if (%iphost) {
8884: return %iphost;
8885: }
8886: my ($ip_info,$cached)=
8887: &Apache::lonnet::is_cached_new('iphost','iphost');
8888: if ($cached) {
8889: %iphost = %{$ip_info->[0]};
8890: %name_to_ip = %{$ip_info->[1]};
8891: %lonid_to_ip = %{$ip_info->[2]};
8892: return %iphost;
8893: }
8894: }
8895:
8896: # get yesterday's info for fallback
8897: my %old_name_to_ip;
8898: my ($ip_info,$cached)=
8899: &Apache::lonnet::is_cached_new('iphost','iphost');
8900: if ($cached) {
8901: %old_name_to_ip = %{$ip_info->[1]};
8902: }
8903:
8904: my %name_to_host = &all_names();
8905: foreach my $name (keys(%name_to_host)) {
8906: my $ip;
8907: if (!exists($name_to_ip{$name})) {
8908: $ip = gethostbyname($name);
8909: if (!$ip || length($ip) ne 4) {
8910: if (defined($old_name_to_ip{$name})) {
8911: $ip = $old_name_to_ip{$name};
8912: &logthis("Can't find $name defaulting to old $ip");
8913: } else {
8914: &logthis("Name $name no IP found");
8915: next;
8916: }
8917: } else {
8918: $ip=inet_ntoa($ip);
8919: }
8920: $name_to_ip{$name} = $ip;
8921: } else {
8922: $ip = $name_to_ip{$name};
8923: }
8924: foreach my $id (@{ $name_to_host{$name} }) {
8925: $lonid_to_ip{$id} = $ip;
8926: }
8927: push(@{$iphost{$ip}},@{$name_to_host{$name}});
8928: }
8929: &Apache::lonnet::do_cache_new('iphost','iphost',
8930: [\%iphost,\%name_to_ip,\%lonid_to_ip],
8931: 48*60*60);
8932:
8933: return %iphost;
8934: }
8935: }
8936:
8937: BEGIN {
8938:
8939: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
8940: unless ($readit) {
8941: {
8942: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
8943: %perlvar = (%perlvar,%{$configvars});
8944: }
8945:
8946:
8947: # ------------------------------------------------------ Read spare server file
8948: {
8949: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
8950:
8951: while (my $configline=<$config>) {
8952: chomp($configline);
8953: if ($configline) {
8954: my ($host,$type) = split(':',$configline,2);
8955: if (!defined($type) || $type eq '') { $type = 'default' };
8956: push(@{ $spareid{$type} }, $host);
8957: }
8958: }
8959: close($config);
8960: }
8961: # ------------------------------------------------------------ Read permissions
8962: {
8963: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
8964:
8965: while (my $configline=<$config>) {
8966: chomp($configline);
8967: if ($configline) {
8968: my ($role,$perm)=split(/ /,$configline);
8969: if ($perm ne '') { $pr{$role}=$perm; }
8970: }
8971: }
8972: close($config);
8973: }
8974:
8975: # -------------------------------------------- Read plain texts for permissions
8976: {
8977: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
8978:
8979: while (my $configline=<$config>) {
8980: chomp($configline);
8981: if ($configline) {
8982: my ($short,@plain)=split(/:/,$configline);
8983: %{$prp{$short}} = ();
8984: if (@plain > 0) {
8985: $prp{$short}{'std'} = $plain[0];
8986: for (my $i=1; $i<@plain; $i++) {
8987: $prp{$short}{'alt'.$i} = $plain[$i];
8988: }
8989: }
8990: }
8991: }
8992: close($config);
8993: }
8994:
8995: # ---------------------------------------------------------- Read package table
8996: {
8997: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
8998:
8999: while (my $configline=<$config>) {
9000: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
9001: chomp($configline);
9002: my ($short,$plain)=split(/:/,$configline);
9003: my ($pack,$name)=split(/\&/,$short);
9004: if ($plain ne '') {
9005: $packagetab{$pack.'&'.$name.'&name'}=$name;
9006: $packagetab{$short}=$plain;
9007: }
9008: }
9009: close($config);
9010: }
9011:
9012: # ------------- set up temporary directory
9013: {
9014: $tmpdir = $perlvar{'lonDaemons'}.'/tmp/';
9015:
9016: }
9017:
9018: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
9019: 'compress_threshold'=> 20_000,
9020: });
9021:
9022: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
9023: $dumpcount=0;
9024: $locknum=0;
9025:
9026: &logtouch();
9027: &logthis('<font color="yellow">INFO: Read configuration</font>');
9028: $readit=1;
9029: {
9030: use integer;
9031: my $test=(2**32)+1;
9032: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
9033: &logthis(" Detected 64bit platform ($_64bit)");
9034: }
9035: }
9036: }
9037:
9038: 1;
9039: __END__
9040:
9041: =pod
9042:
9043: =head1 NAME
9044:
9045: Apache::lonnet - Subroutines to ask questions about things in the network.
9046:
9047: =head1 SYNOPSIS
9048:
9049: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
9050:
9051: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
9052:
9053: Common parameters:
9054:
9055: =over 4
9056:
9057: =item *
9058:
9059: $uname : an internal username (if $cname expecting a course Id specifically)
9060:
9061: =item *
9062:
9063: $udom : a domain (if $cdom expecting a course's domain specifically)
9064:
9065: =item *
9066:
9067: $symb : a resource instance identifier
9068:
9069: =item *
9070:
9071: $namespace : the name of a .db file that contains the data needed or
9072: being set.
9073:
9074: =back
9075:
9076: =head1 OVERVIEW
9077:
9078: lonnet provides subroutines which interact with the
9079: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
9080: about classes, users, and resources.
9081:
9082: For many of these objects you can also use this to store data about
9083: them or modify them in various ways.
9084:
9085: =head2 Symbs
9086:
9087: To identify a specific instance of a resource, LON-CAPA uses symbols
9088: or "symbs"X<symb>. These identifiers are built from the URL of the
9089: map, the resource number of the resource in the map, and the URL of
9090: the resource itself. The latter is somewhat redundant, but might help
9091: if maps change.
9092:
9093: An example is
9094:
9095: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
9096:
9097: The respective map entry is
9098:
9099: <resource id="19" src="/res/msu/korte/tests/part12.problem"
9100: title="Problem 2">
9101: </resource>
9102:
9103: Symbs are used by the random number generator, as well as to store and
9104: restore data specific to a certain instance of for example a problem.
9105:
9106: =head2 Storing And Retrieving Data
9107:
9108: X<store()>X<cstore()>X<restore()>Three of the most important functions
9109: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
9110: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
9111: is is the non-critical message twin of cstore. These functions are for
9112: handlers to store a perl hash to a user's permanent data space in an
9113: easy manner, and to retrieve it again on another call. It is expected
9114: that a handler would use this once at the beginning to retrieve data,
9115: and then again once at the end to send only the new data back.
9116:
9117: The data is stored in the user's data directory on the user's
9118: homeserver under the ID of the course.
9119:
9120: The hash that is returned by restore will have all of the previous
9121: value for all of the elements of the hash.
9122:
9123: Example:
9124:
9125: #creating a hash
9126: my %hash;
9127: $hash{'foo'}='bar';
9128:
9129: #storing it
9130: &Apache::lonnet::cstore(\%hash);
9131:
9132: #changing a value
9133: $hash{'foo'}='notbar';
9134:
9135: #adding a new value
9136: $hash{'bar'}='foo';
9137: &Apache::lonnet::cstore(\%hash);
9138:
9139: #retrieving the hash
9140: my %history=&Apache::lonnet::restore();
9141:
9142: #print the hash
9143: foreach my $key (sort(keys(%history))) {
9144: print("\%history{$key} = $history{$key}");
9145: }
9146:
9147: Will print out:
9148:
9149: %history{1:foo} = bar
9150: %history{1:keys} = foo:timestamp
9151: %history{1:timestamp} = 990455579
9152: %history{2:bar} = foo
9153: %history{2:foo} = notbar
9154: %history{2:keys} = foo:bar:timestamp
9155: %history{2:timestamp} = 990455580
9156: %history{bar} = foo
9157: %history{foo} = notbar
9158: %history{timestamp} = 990455580
9159: %history{version} = 2
9160:
9161: Note that the special hash entries C<keys>, C<version> and
9162: C<timestamp> were added to the hash. C<version> will be equal to the
9163: total number of versions of the data that have been stored. The
9164: C<timestamp> attribute will be the UNIX time the hash was
9165: stored. C<keys> is available in every historical section to list which
9166: keys were added or changed at a specific historical revision of a
9167: hash.
9168:
9169: B<Warning>: do not store the hash that restore returns directly. This
9170: will cause a mess since it will restore the historical keys as if the
9171: were new keys. I.E. 1:foo will become 1:1:foo etc.
9172:
9173: Calling convention:
9174:
9175: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
9176: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
9177:
9178: For more detailed information, see lonnet specific documentation.
9179:
9180: =head1 RETURN MESSAGES
9181:
9182: =over 4
9183:
9184: =item * B<con_lost>: unable to contact remote host
9185:
9186: =item * B<con_delayed>: unable to contact remote host, message will be delivered
9187: when the connection is brought back up
9188:
9189: =item * B<con_failed>: unable to contact remote host and unable to save message
9190: for later delivery
9191:
9192: =item * B<error:>: an error a occurred, a description of the error follows the :
9193:
9194: =item * B<no_such_host>: unable to fund a host associated with the user/domain
9195: that was requested
9196:
9197: =back
9198:
9199: =head1 PUBLIC SUBROUTINES
9200:
9201: =head2 Session Environment Functions
9202:
9203: =over 4
9204:
9205: =item *
9206: X<appenv()>
9207: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
9208: the user envirnoment file, and will be restored for each access this
9209: user makes during this session, also modifies the %env for the current
9210: process. Optional rolesarrayref - if defined contains a reference to an array
9211: of roles which are exempt from the restriction on modifying user.role entries
9212: in the user's environment.db and in %env.
9213:
9214: =item *
9215: X<delenv()>
9216: B<delenv($regexp)>: removes all items from the session
9217: environment file that matches the regular expression in $regexp. The
9218: values are also delted from the current processes %env.
9219:
9220: =item * get_env_multiple($name)
9221:
9222: gets $name from the %env hash, it seemlessly handles the cases where multiple
9223: values may be defined and end up as an array ref.
9224:
9225: returns an array of values
9226:
9227: =back
9228:
9229: =head2 User Information
9230:
9231: =over 4
9232:
9233: =item *
9234: X<queryauthenticate()>
9235: B<queryauthenticate($uname,$udom)>: try to determine user's current
9236: authentication scheme
9237:
9238: =item *
9239: X<authenticate()>
9240: B<authenticate($uname,$upass,$udom)>: try to
9241: authenticate user from domain's lib servers (first use the current
9242: one). C<$upass> should be the users password.
9243:
9244: =item *
9245: X<homeserver()>
9246: B<homeserver($uname,$udom)>: find the server which has
9247: the user's directory and files (there must be only one), this caches
9248: the answer, and also caches if there is a borken connection.
9249:
9250: =item *
9251: X<idget()>
9252: B<idget($udom,@ids)>: find the usernames behind a list of IDs
9253: (IDs are a unique resource in a domain, there must be only 1 ID per
9254: username, and only 1 username per ID in a specific domain) (returns
9255: hash: id=>name,id=>name)
9256:
9257: =item *
9258: X<idrget()>
9259: B<idrget($udom,@unames)>: find the IDs behind a list of
9260: usernames (returns hash: name=>id,name=>id)
9261:
9262: =item *
9263: X<idput()>
9264: B<idput($udom,%ids)>: store away a list of names and associated IDs
9265:
9266: =item *
9267: X<rolesinit()>
9268: B<rolesinit($udom,$username,$authhost)>: get user privileges
9269:
9270: =item *
9271: X<getsection()>
9272: B<getsection($udom,$uname,$cname)>: finds the section of student in the
9273: course $cname, return section name/number or '' for "not in course"
9274: and '-1' for "no section"
9275:
9276: =item *
9277: X<userenvironment()>
9278: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
9279: passed in @what from the requested user's environment, returns a hash
9280:
9281: =item *
9282: X<userlog_query()>
9283: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
9284: activity.log file. %filters defines filters applied when parsing the
9285: log file. These can be start or end timestamps, or the type of action
9286: - log to look for Login or Logout events, check for Checkin or
9287: Checkout, role for role selection. The response is in the form
9288: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
9289: escaped strings of the action recorded in the activity.log file.
9290:
9291: =back
9292:
9293: =head2 User Roles
9294:
9295: =over 4
9296:
9297: =item *
9298:
9299: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
9300: F: full access
9301: U,I,K: authentication modes (cxx only)
9302: '': forbidden
9303: 1: user needs to choose course
9304: 2: browse allowed
9305: A: passphrase authentication needed
9306:
9307: =item *
9308:
9309: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
9310: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
9311: and course level
9312:
9313: =item *
9314:
9315: plaintext($short) : return value in %prp hash (rolesplain.tab); plain text
9316: explanation of a user role term
9317:
9318: =item *
9319:
9320: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
9321: All arguments are optional. Returns a hash of a roles, either for
9322: co-author/assistant author roles for a user's Construction Space
9323: (default), or if $context is 'userroles', roles for the user himself,
9324: In the hash, keys are set to colon-separated $uname,$udom,$role, and
9325: (optionally) if $withsec is true, a fourth colon-separated item - $section.
9326: For each key, value is set to colon-separated start and end times for
9327: the role. If no username and domain are specified, will default to
9328: current user/domain. Types, roles, and roledoms are references to arrays
9329: of role statuses (active, future or previous), roles
9330: (e.g., cc,in, st etc.) and domains of the roles which can be used
9331: to restrict the list of roles reported. If no array ref is
9332: provided for types, will default to return only active roles.
9333:
9334: =back
9335:
9336: =head2 User Modification
9337:
9338: =over 4
9339:
9340: =item *
9341:
9342: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
9343: user for the level given by URL. Optional start and end dates (leave empty
9344: string or zero for "no date")
9345:
9346: =item *
9347:
9348: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
9349: change a users, password, possible return values are: ok,
9350: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
9351: refused
9352:
9353: =item *
9354:
9355: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
9356:
9357: =item *
9358:
9359: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,
9360: $forceid,$desiredhome,$email,$inststatus) :
9361: modify user
9362:
9363: =item *
9364:
9365: modifystudent
9366:
9367: modify a student's enrollment and identification information.
9368: The course id is resolved based on the current users environment.
9369: This means the envoking user must be a course coordinator or otherwise
9370: associated with a course.
9371:
9372: This call is essentially a wrapper for lonnet::modifyuser and
9373: lonnet::modify_student_enrollment
9374:
9375: Inputs:
9376:
9377: =over 4
9378:
9379: =item B<$udom> Student's loncapa domain
9380:
9381: =item B<$uname> Student's loncapa login name
9382:
9383: =item B<$uid> Student/Employee ID
9384:
9385: =item B<$umode> Student's authentication mode
9386:
9387: =item B<$upass> Student's password
9388:
9389: =item B<$first> Student's first name
9390:
9391: =item B<$middle> Student's middle name
9392:
9393: =item B<$last> Student's last name
9394:
9395: =item B<$gene> Student's generation
9396:
9397: =item B<$usec> Student's section in course
9398:
9399: =item B<$end> Unix time of the roles expiration
9400:
9401: =item B<$start> Unix time of the roles start date
9402:
9403: =item B<$forceid> If defined, allow $uid to be changed
9404:
9405: =item B<$desiredhome> server to use as home server for student
9406:
9407: =item B<$email> Student's permanent e-mail address
9408:
9409: =item B<$type> Type of enrollment (auto or manual)
9410:
9411: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
9412:
9413: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
9414:
9415: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
9416:
9417: =item B<$context> role change context (shown in User Management Logs display in a course)
9418:
9419: =item B<$inststatus> institutional status of user - : separated string of escaped status types
9420:
9421: =back
9422:
9423: =item *
9424:
9425: modify_student_enrollment
9426:
9427: Change a students enrollment status in a class. The environment variable
9428: 'role.request.course' must be defined for this function to proceed.
9429:
9430: Inputs:
9431:
9432: =over 4
9433:
9434: =item $udom, students domain
9435:
9436: =item $uname, students name
9437:
9438: =item $uid, students user id
9439:
9440: =item $first, students first name
9441:
9442: =item $middle
9443:
9444: =item $last
9445:
9446: =item $gene
9447:
9448: =item $usec
9449:
9450: =item $end
9451:
9452: =item $start
9453:
9454: =item $type
9455:
9456: =item $locktype
9457:
9458: =item $cid
9459:
9460: =item $selfenroll
9461:
9462: =item $context
9463:
9464: =back
9465:
9466:
9467: =item *
9468:
9469: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
9470: custom role; give a custom role to a user for the level given by URL. Specify
9471: name and domain of role author, and role name
9472:
9473: =item *
9474:
9475: revokerole($udom,$uname,$url,$role) : revoke a role for url
9476:
9477: =item *
9478:
9479: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
9480:
9481: =back
9482:
9483: =head2 Course Infomation
9484:
9485: =over 4
9486:
9487: =item *
9488:
9489: coursedescription($courseid) : returns a hash of information about the
9490: specified course id, including all environment settings for the
9491: course, the description of the course will be in the hash under the
9492: key 'description'
9493:
9494: =item *
9495:
9496: resdata($name,$domain,$type,@which) : request for current parameter
9497: setting for a specific $type, where $type is either 'course' or 'user',
9498: @what should be a list of parameters to ask about. This routine caches
9499: answers for 5 minutes.
9500:
9501: =item *
9502:
9503: get_courseresdata($courseid, $domain) : dump the entire course resource
9504: data base, returning a hash that is keyed by the resource name and has
9505: values that are the resource value. I believe that the timestamps and
9506: versions are also returned.
9507:
9508:
9509: =back
9510:
9511: =head2 Course Modification
9512:
9513: =over 4
9514:
9515: =item *
9516:
9517: writecoursepref($courseid,%prefs) : write preferences (environment
9518: database) for a course
9519:
9520: =item *
9521:
9522: createcourse($udom,$description,$url) : make/modify course
9523:
9524: =back
9525:
9526: =head2 Resource Subroutines
9527:
9528: =over 4
9529:
9530: =item *
9531:
9532: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
9533:
9534: =item *
9535:
9536: repcopy($filename) : subscribes to the requested file, and attempts to
9537: replicate from the owning library server, Might return
9538: 'unavailable', 'not_found', 'forbidden', 'ok', or
9539: 'bad_request', also attempts to grab the metadata for the
9540: resource. Expects the local filesystem pathname
9541: (/home/httpd/html/res/....)
9542:
9543: =back
9544:
9545: =head2 Resource Information
9546:
9547: =over 4
9548:
9549: =item *
9550:
9551: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
9552: a vairety of different possible values, $varname should be a request
9553: string, and the other parameters can be used to specify who and what
9554: one is asking about.
9555:
9556: Possible values for $varname are environment.lastname (or other item
9557: from the envirnment hash), user.name (or someother aspect about the
9558: user), resource.0.maxtries (or some other part and parameter of a
9559: resource)
9560:
9561: =item *
9562:
9563: directcondval($number) : get current value of a condition; reads from a state
9564: string
9565:
9566: =item *
9567:
9568: condval($condidx) : value of condition index based on state
9569:
9570: =item *
9571:
9572: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
9573: resource's metadata, $what should be either a specific key, or either
9574: 'keys' (to get a list of possible keys) or 'packages' to get a list of
9575: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
9576:
9577: this function automatically caches all requests
9578:
9579: =item *
9580:
9581: metadata_query($query,$custom,$customshow) : make a metadata query against the
9582: network of library servers; returns file handle of where SQL and regex results
9583: will be stored for query
9584:
9585: =item *
9586:
9587: symbread($filename) : return symbolic list entry (filename argument optional);
9588: returns the data handle
9589:
9590: =item *
9591:
9592: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
9593: a possible symb for the URL in $thisfn, and if is an encryypted
9594: resource that the user accessed using /enc/ returns a 1 on success, 0
9595: on failure, user must be in a course, as it assumes the existance of
9596: the course initial hash, and uses $env('request.course.id'}
9597:
9598:
9599: =item *
9600:
9601: symbclean($symb) : removes versions numbers from a symb, returns the
9602: cleaned symb
9603:
9604: =item *
9605:
9606: is_on_map($uri) : checks if the $uri is somewhere on the current
9607: course map, user must be in a course for it to work.
9608:
9609: =item *
9610:
9611: numval($salt) : return random seed value (addend for rndseed)
9612:
9613: =item *
9614:
9615: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
9616: a random seed, all arguments are optional, if they aren't sent it uses the
9617: environment to derive them. Note: if symb isn't sent and it can't get one
9618: from &symbread it will use the current time as its return value
9619:
9620: =item *
9621:
9622: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
9623: unfakeable, receipt
9624:
9625: =item *
9626:
9627: receipt() : API to ireceipt working off of env values; given out to users
9628:
9629: =item *
9630:
9631: countacc($url) : count the number of accesses to a given URL
9632:
9633: =item *
9634:
9635: 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
9636:
9637: =item *
9638:
9639: 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)
9640:
9641: =item *
9642:
9643: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
9644:
9645: =item *
9646:
9647: devalidate($symb) : devalidate temporary spreadsheet calculations,
9648: forcing spreadsheet to reevaluate the resource scores next time.
9649:
9650: =back
9651:
9652: =head2 Storing/Retreiving Data
9653:
9654: =over 4
9655:
9656: =item *
9657:
9658: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
9659: for this url; hashref needs to be given and should be a \%hashname; the
9660: remaining args aren't required and if they aren't passed or are '' they will
9661: be derived from the env
9662:
9663: =item *
9664:
9665: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
9666: uses critical subroutine
9667:
9668: =item *
9669:
9670: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
9671: all args are optional
9672:
9673: =item *
9674:
9675: dumpstore($namespace,$udom,$uname,$regexp,$range) :
9676: dumps the complete (or key matching regexp) namespace into a hash
9677: ($udom, $uname, $regexp, $range are optional) for a namespace that is
9678: normally &store()ed into
9679:
9680: $range should be either an integer '100' (give me the first 100
9681: matching records)
9682: or be two integers sperated by a - with no spaces
9683: '30-50' (give me the 30th through the 50th matching
9684: records)
9685:
9686:
9687: =item *
9688:
9689: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
9690: replaces a &store() version of data with a replacement set of data
9691: for a particular resource in a namespace passed in the $storehash hash
9692: reference
9693:
9694: =item *
9695:
9696: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
9697: works very similar to store/cstore, but all data is stored in a
9698: temporary location and can be reset using tmpreset, $storehash should
9699: be a hash reference, returns nothing on success
9700:
9701: =item *
9702:
9703: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
9704: similar to restore, but all data is stored in a temporary location and
9705: can be reset using tmpreset. Returns a hash of values on success,
9706: error string otherwise.
9707:
9708: =item *
9709:
9710: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
9711: deltes all keys for $symb form the temporary storage hash.
9712:
9713: =item *
9714:
9715: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9716: reference filled in from namesp ($udom and $uname are optional)
9717:
9718: =item *
9719:
9720: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
9721: namesp ($udom and $uname are optional)
9722:
9723: =item *
9724:
9725: dump($namespace,$udom,$uname,$regexp,$range) :
9726: dumps the complete (or key matching regexp) namespace into a hash
9727: ($udom, $uname, $regexp, $range are optional)
9728:
9729: $range should be either an integer '100' (give me the first 100
9730: matching records)
9731: or be two integers sperated by a - with no spaces
9732: '30-50' (give me the 30th through the 50th matching
9733: records)
9734: =item *
9735:
9736: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
9737: $store can be a scalar, an array reference, or if the amount to be
9738: incremented is > 1, a hash reference.
9739:
9740: ($udom and $uname are optional)
9741:
9742: =item *
9743:
9744: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
9745: ($udom and $uname are optional)
9746:
9747: =item *
9748:
9749: cput($namespace,$storehash,$udom,$uname) : critical put
9750: ($udom and $uname are optional)
9751:
9752: =item *
9753:
9754: newput($namespace,$storehash,$udom,$uname) :
9755:
9756: Attempts to store the items in the $storehash, but only if they don't
9757: currently exist, if this succeeds you can be certain that you have
9758: successfully created a new key value pair in the $namespace db.
9759:
9760:
9761: Args:
9762: $namespace: name of database to store values to
9763: $storehash: hashref to store to the db
9764: $udom: (optional) domain of user containing the db
9765: $uname: (optional) name of user caontaining the db
9766:
9767: Returns:
9768: 'ok' -> succeeded in storing all keys of $storehash
9769: 'key_exists: <key>' -> failed to anything out of $storehash, as at
9770: least <key> already existed in the db (other
9771: requested keys may also already exist)
9772: 'error: <msg>' -> unable to tie the DB or other error occurred
9773: 'con_lost' -> unable to contact request server
9774: 'refused' -> action was not allowed by remote machine
9775:
9776:
9777: =item *
9778:
9779: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
9780: reference filled in from namesp (encrypts the return communication)
9781: ($udom and $uname are optional)
9782:
9783: =item *
9784:
9785: log($udom,$name,$home,$message) : write to permanent log for user; use
9786: critical subroutine
9787:
9788: =item *
9789:
9790: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
9791: array reference filled in from namespace found in domain level on either
9792: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
9793:
9794: =item *
9795:
9796: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
9797: domain level either on specified domain server ($uhome) or primary domain
9798: server ($udom and $uhome are optional)
9799:
9800: =item *
9801:
9802: get_domain_defaults($target_domain) : returns hash with defaults for
9803: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
9804: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
9805: or localauth), initial password or a kerberos realm, language (e.g., en-us).
9806: Values are retrieved from cache (if current), or from domain's configuration.db
9807: (if available), or lastly from values in lonTabs/dns_domain,tab,
9808: or lonTabs/domain.tab.
9809:
9810: %domdefaults = &get_auth_defaults($target_domain);
9811:
9812: =back
9813:
9814: =head2 Network Status Functions
9815:
9816: =over 4
9817:
9818: =item *
9819:
9820: dirlist($uri) : return directory list based on URI
9821:
9822: =item *
9823:
9824: spareserver() : find server with least workload from spare.tab
9825:
9826: =back
9827:
9828: =head2 Apache Request
9829:
9830: =over 4
9831:
9832: =item *
9833:
9834: ssi($url,%hash) : server side include, does a complete request cycle on url to
9835: localhost, posts hash
9836:
9837: =back
9838:
9839: =head2 Data to String to Data
9840:
9841: =over 4
9842:
9843: =item *
9844:
9845: hash2str(%hash) : convert a hash into a string complete with escaping and '='
9846: and '&' separators, supports elements that are arrayrefs and hashrefs
9847:
9848: =item *
9849:
9850: hashref2str($hashref) : convert a hashref into a string complete with
9851: escaping and '=' and '&' separators, supports elements that are
9852: arrayrefs and hashrefs
9853:
9854: =item *
9855:
9856: arrayref2str($arrayref) : convert an arrayref into a string complete
9857: with escaping and '&' separators, supports elements that are arrayrefs
9858: and hashrefs
9859:
9860: =item *
9861:
9862: str2hash($string) : convert string to hash using unescaping and
9863: splitting on '=' and '&', supports elements that are arrayrefs and
9864: hashrefs
9865:
9866: =item *
9867:
9868: str2array($string) : convert string to hash using unescaping and
9869: splitting on '&', supports elements that are arrayrefs and hashrefs
9870:
9871: =back
9872:
9873: =head2 Logging Routines
9874:
9875: =over 4
9876:
9877: These routines allow one to make log messages in the lonnet.log and
9878: lonnet.perm logfiles.
9879:
9880: =item *
9881:
9882: logtouch() : make sure the logfile, lonnet.log, exists
9883:
9884: =item *
9885:
9886: logthis() : append message to the normal lonnet.log file, it gets
9887: preiodically rolled over and deleted.
9888:
9889: =item *
9890:
9891: logperm() : append a permanent message to lonnet.perm.log, this log
9892: file never gets deleted by any automated portion of the system, only
9893: messages of critical importance should go in here.
9894:
9895: =back
9896:
9897: =head2 General File Helper Routines
9898:
9899: =over 4
9900:
9901: =item *
9902:
9903: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
9904: (a) files in /uploaded
9905: (i) If a local copy of the file exists -
9906: compares modification date of local copy with last-modified date for
9907: definitive version stored on home server for course. If local copy is
9908: stale, requests a new version from the home server and stores it.
9909: If the original has been removed from the home server, then local copy
9910: is unlinked.
9911: (ii) If local copy does not exist -
9912: requests the file from the home server and stores it.
9913:
9914: If $caller is 'uploadrep':
9915: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
9916: for request for files originally uploaded via DOCS.
9917: - returns 'ok' if fresh local copy now available, -1 otherwise.
9918:
9919: Otherwise:
9920: This indicates a call from the content generation phase of the request.
9921: - returns the entire contents of the file or -1.
9922:
9923: (b) files in /res
9924: - returns the entire contents of a file or -1;
9925: it properly subscribes to and replicates the file if neccessary.
9926:
9927:
9928: =item *
9929:
9930: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
9931: reference
9932:
9933: returns either a stat() list of data about the file or an empty list
9934: if the file doesn't exist or couldn't find out about it (connection
9935: problems or user unknown)
9936:
9937: =item *
9938:
9939: filelocation($dir,$file) : returns file system location of a file
9940: based on URI; meant to be "fairly clean" absolute reference, $dir is a
9941: directory that relative $file lookups are to looked in ($dir of /a/dir
9942: and a file of ../bob will become /a/bob)
9943:
9944: =item *
9945:
9946: hreflocation($dir,$file) : returns file system location or a URL; same as
9947: filelocation except for hrefs
9948:
9949: =item *
9950:
9951: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
9952:
9953: =back
9954:
9955: =head2 Usererfile file routines (/uploaded*)
9956:
9957: =over 4
9958:
9959: =item *
9960:
9961: userfileupload(): main rotine for putting a file in a user or course's
9962: filespace, arguments are,
9963:
9964: formname - required - this is the name of the element in $env where the
9965: filename, and the contents of the file to create/modifed exist
9966: the filename is in $env{'form.'.$formname.'.filename'} and the
9967: contents of the file is located in $env{'form.'.$formname}
9968: coursedoc - if true, store the file in the course of the active role
9969: of the current user
9970: subdir - required - subdirectory to put the file in under ../userfiles/
9971: if undefined, it will be placed in "unknown"
9972:
9973: (This routine calls clean_filename() to remove any dangerous
9974: characters from the filename, and then calls finuserfileupload() to
9975: complete the transaction)
9976:
9977: returns either the url of the uploaded file (/uploaded/....) if successful
9978: and /adm/notfound.html if unsuccessful
9979:
9980: =item *
9981:
9982: clean_filename(): routine for cleaing a filename up for storage in
9983: userfile space, argument is:
9984:
9985: filename - proposed filename
9986:
9987: returns: the new clean filename
9988:
9989: =item *
9990:
9991: finishuserfileupload(): routine that creaes and sends the file to
9992: userspace, probably shouldn't be called directly
9993:
9994: docuname: username or courseid of destination for the file
9995: docudom: domain of user/course of destination for the file
9996: formname: same as for userfileupload()
9997: fname: filename (inculding subdirectories) for the file
9998:
9999: returns either the url of the uploaded file (/uploaded/....) if successful
10000: and /adm/notfound.html if unsuccessful
10001:
10002: =item *
10003:
10004: renameuserfile(): renames an existing userfile to a new name
10005:
10006: Args:
10007: docuname: username or courseid of destination for the file
10008: docudom: domain of user/course of destination for the file
10009: old: current file name (including any subdirs under userfiles)
10010: new: desired file name (including any subdirs under userfiles)
10011:
10012: =item *
10013:
10014: mkdiruserfile(): creates a directory is a userfiles dir
10015:
10016: Args:
10017: docuname: username or courseid of destination for the file
10018: docudom: domain of user/course of destination for the file
10019: dir: dir to create (including any subdirs under userfiles)
10020:
10021: =item *
10022:
10023: removeuserfile(): removes a file that exists in userfiles
10024:
10025: Args:
10026: docuname: username or courseid of destination for the file
10027: docudom: domain of user/course of destination for the file
10028: fname: filname to delete (including any subdirs under userfiles)
10029:
10030: =item *
10031:
10032: removeuploadedurl(): convience function for removeuserfile()
10033:
10034: Args:
10035: url: a full /uploaded/... url to delete
10036:
10037: =item *
10038:
10039: get_portfile_permissions():
10040: Args:
10041: domain: domain of user or course contain the portfolio files
10042: user: name of user or num of course contain the portfolio files
10043: Returns:
10044: hashref of a dump of the proper file_permissions.db
10045:
10046:
10047: =item *
10048:
10049: get_access_controls():
10050:
10051: Args:
10052: current_permissions: the hash ref returned from get_portfile_permissions()
10053: group: (optional) the group you want the files associated with
10054: file: (optional) the file you want access info on
10055:
10056: Returns:
10057: a hash (keys are file names) of hashes containing
10058: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
10059: values are XML containing access control settings (see below)
10060:
10061: Internal notes:
10062:
10063: access controls are stored in file_permissions.db as key=value pairs.
10064: key -> path to file/file_name\0uniqueID:scope_end_start
10065: where scope -> public,guest,course,group,domains or users.
10066: end -> UNIX time for end of access (0 -> no end date)
10067: start -> UNIX time for start of access
10068:
10069: value -> XML description of access control
10070: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
10071: <start></start>
10072: <end></end>
10073:
10074: <password></password> for scope type = guest
10075:
10076: <domain></domain> for scope type = course or group
10077: <number></number>
10078: <roles id="">
10079: <role></role>
10080: <access></access>
10081: <section></section>
10082: <group></group>
10083: </roles>
10084:
10085: <dom></dom> for scope type = domains
10086:
10087: <users> for scope type = users
10088: <user>
10089: <uname></uname>
10090: <udom></udom>
10091: </user>
10092: </users>
10093: </scope>
10094:
10095: Access data is also aggregated for each file in an additional key=value pair:
10096: key -> path to file/file_name\0accesscontrol
10097: value -> reference to hash
10098: hash contains key = value pairs
10099: where key = uniqueID:scope_end_start
10100: value = UNIX time record was last updated
10101:
10102: Used to improve speed of look-ups of access controls for each file.
10103:
10104: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
10105:
10106: modify_access_controls():
10107:
10108: Modifies access controls for a portfolio file
10109: Args
10110: 1. file name
10111: 2. reference to hash of required changes,
10112: 3. domain
10113: 4. username
10114: where domain,username are the domain of the portfolio owner
10115: (either a user or a course)
10116:
10117: Returns:
10118: 1. result of additions or updates ('ok' or 'error', with error message).
10119: 2. result of deletions ('ok' or 'error', with error message).
10120: 3. reference to hash of any new or updated access controls.
10121: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
10122: key = integer (inbound ID)
10123: value = uniqueID
10124:
10125: =back
10126:
10127: =head2 HTTP Helper Routines
10128:
10129: =over 4
10130:
10131: =item *
10132:
10133: escape() : unpack non-word characters into CGI-compatible hex codes
10134:
10135: =item *
10136:
10137: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
10138:
10139: =back
10140:
10141: =head1 PRIVATE SUBROUTINES
10142:
10143: =head2 Underlying communication routines (Shouldn't call)
10144:
10145: =over 4
10146:
10147: =item *
10148:
10149: subreply() : tries to pass a message to lonc, returns con_lost if incapable
10150:
10151: =item *
10152:
10153: reply() : uses subreply to send a message to remote machine, logs all failures
10154:
10155: =item *
10156:
10157: critical() : passes a critical message to another server; if cannot
10158: get through then place message in connection buffer directory and
10159: returns con_delayed, if incapable of saving message, returns
10160: con_failed
10161:
10162: =item *
10163:
10164: reconlonc() : tries to reconnect lonc client processes.
10165:
10166: =back
10167:
10168: =head2 Resource Access Logging
10169:
10170: =over 4
10171:
10172: =item *
10173:
10174: flushcourselogs() : flush (save) buffer logs and access logs
10175:
10176: =item *
10177:
10178: courselog($what) : save message for course in hash
10179:
10180: =item *
10181:
10182: courseacclog($what) : save message for course using &courselog(). Perform
10183: special processing for specific resource types (problems, exams, quizzes, etc).
10184:
10185: =item *
10186:
10187: goodbye() : flush course logs and log shutting down; it is called in srm.conf
10188: as a PerlChildExitHandler
10189:
10190: =back
10191:
10192: =head2 Other
10193:
10194: =over 4
10195:
10196: =item *
10197:
10198: symblist($mapname,%newhash) : update symbolic storage links
10199:
10200: =back
10201:
10202: =cut
10203:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>