Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1133
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1133 ! foxr 4: # $Id: lonnet.pm,v 1.1132 2011/09/16 22:24:01 raeburn Exp $
1.178 www 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: #
1.169 harris41 28: ###
29:
1.971 jms 30: =pod
31:
1.972 jms 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:
1.971 jms 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:
1.1 albertel 71: package Apache::lonnet;
72:
73: use strict;
1.8 www 74: use LWP::UserAgent();
1.486 www 75: use HTTP::Date;
1.977 amueller 76: use Image::Magick;
77:
1.871 albertel 78: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1079 raeburn 79: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease);
1.871 albertel 80:
81: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
82: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
83: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 84: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 85:
1.1 albertel 86: use IO::Socket;
1.31 www 87: use GDBM_File;
1.208 albertel 88: use HTML::LCParser;
1.88 www 89: use Fcntl qw(:flock);
1.870 albertel 90: use Storable qw(thaw nfreeze);
1.539 albertel 91: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 92: use Cache::Memcached;
1.676 albertel 93: use Digest::MD5;
1.790 albertel 94: use Math::Random;
1.1024 raeburn 95: use File::MMagic;
1.807 albertel 96: use LONCAPA qw(:DEFAULT :match);
1.740 www 97: use LONCAPA::Configuration;
1.1117 foxr 98:
1.1090 raeburn 99: use File::Copy;
1.676 albertel 100:
1.195 www 101: my $readit;
1.550 foxr 102: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 103:
1.619 albertel 104: require Exporter;
105:
106: our @ISA = qw (Exporter);
107: our @EXPORT = qw(%env);
108:
1.449 matthew 109:
1.1 albertel 110: # --------------------------------------------------------------------- Logging
1.729 www 111: {
112: my $logid;
113: sub instructor_log {
1.957 raeburn 114: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
115: if (($cnum eq '') || ($cdom eq '')) {
116: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
117: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
118: }
1.729 www 119: $logid++;
1.957 raeburn 120: my $now = time();
121: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 122: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 123: { $id => {
124: 'exe_uname' => $env{'user.name'},
125: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 126: 'exe_time' => $now,
1.730 www 127: 'exe_ip' => $ENV{'REMOTE_ADDR'},
128: 'delflag' => $delflag,
129: 'logentry' => $storehash,
130: 'uname' => $uname,
131: 'udom' => $udom,
132: }
1.957 raeburn 133: },$cdom,$cnum);
1.729 www 134: }
135: }
1.1 albertel 136:
1.163 harris41 137: sub logtouch {
138: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 139: unless (-e "$execdir/logs/lonnet.log") {
140: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 141: close $fh;
142: }
143: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
144: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
145: }
146:
1.1 albertel 147: sub logthis {
148: my $message=shift;
149: my $execdir=$perlvar{'lonDaemons'};
150: my $now=time;
151: my $local=localtime($now);
1.448 albertel 152: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 153: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
154: print $fh $logstring;
1.448 albertel 155: close($fh);
156: }
1.1 albertel 157: return 1;
158: }
159:
160: sub logperm {
161: my $message=shift;
162: my $execdir=$perlvar{'lonDaemons'};
163: my $now=time;
164: my $local=localtime($now);
1.448 albertel 165: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
166: print $fh "$now:$message:$local\n";
167: close($fh);
168: }
1.1 albertel 169: return 1;
170: }
171:
1.850 albertel 172: sub create_connection {
1.853 albertel 173: my ($hostname,$lonid) = @_;
1.851 albertel 174: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 175: Type => SOCK_STREAM,
176: Timeout => 10);
177: return 0 if (!$client);
1.890 albertel 178: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 179: my $result = <$client>;
180: chomp($result);
181: return 1 if ($result eq 'done');
182: return 0;
183: }
184:
1.983 raeburn 185: sub get_server_timezone {
186: my ($cnum,$cdom) = @_;
187: my $home=&homeserver($cnum,$cdom);
188: if ($home ne 'no_host') {
189: my $cachetime = 24*3600;
190: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
191: if (defined($cached)) {
192: return $timezone;
193: } else {
194: my $timezone = &reply('servertimezone',$home);
195: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
196: }
197: }
198: }
1.850 albertel 199:
1.1106 raeburn 200: sub get_server_distarch {
201: my ($lonhost,$ignore_cache) = @_;
202: if (defined($lonhost)) {
203: if (!defined(&hostname($lonhost))) {
204: return;
205: }
206: my $cachetime = 12*3600;
207: if (!$ignore_cache) {
208: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
209: if (defined($cached)) {
210: return $distarch;
211: }
212: }
213: my $rep = &reply('serverdistarch',$lonhost);
214: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
215: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
216: $rep eq '') {
217: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
218: }
219: }
220: return;
221: }
222:
1.993 raeburn 223: sub get_server_loncaparev {
1.1073 raeburn 224: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 225: if (defined($lonhost)) {
226: if (!defined(&hostname($lonhost))) {
227: undef($lonhost);
228: }
229: }
230: if (!defined($lonhost)) {
231: if (defined(&domain($dom,'primary'))) {
232: $lonhost=&domain($dom,'primary');
233: if ($lonhost eq 'no_host') {
234: undef($lonhost);
235: }
236: }
237: }
238: if (defined($lonhost)) {
1.1073 raeburn 239: my $cachetime = 12*3600;
240: if (!$ignore_cache) {
241: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
242: if (defined($cached)) {
243: return $loncaparev;
244: }
245: }
246: my ($answer,$loncaparev);
247: my @ids=¤t_machine_ids();
248: if (grep(/^\Q$lonhost\E$/,@ids)) {
249: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 250: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 251: $loncaparev = $1;
252: }
253: } else {
254: $answer = &reply('serverloncaparev',$lonhost);
255: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
256: if ($caller eq 'loncron') {
257: my $ua=new LWP::UserAgent;
1.1082 raeburn 258: $ua->timeout(4);
1.1073 raeburn 259: my $protocol = $protocol{$lonhost};
260: $protocol = 'http' if ($protocol ne 'https');
261: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
262: my $request=new HTTP::Request('GET',$url);
263: my $response=$ua->request($request);
264: unless ($response->is_error()) {
265: my $content = $response->content;
1.1081 raeburn 266: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 267: $loncaparev = $1;
268: }
269: }
270: } else {
271: $loncaparev = $loncaparevs{$lonhost};
272: }
1.1081 raeburn 273: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 274: $loncaparev = $1;
275: }
1.993 raeburn 276: }
1.1073 raeburn 277: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 278: }
279: }
280:
1.1074 raeburn 281: sub get_server_homeID {
282: my ($hostname,$ignore_cache,$caller) = @_;
283: unless ($ignore_cache) {
284: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
285: if (defined($cached)) {
286: return $serverhomeID;
287: }
288: }
289: my $cachetime = 12*3600;
290: my $serverhomeID;
291: if ($caller eq 'loncron') {
292: my @machine_ids = &machine_ids($hostname);
293: foreach my $id (@machine_ids) {
294: my $response = &reply('serverhomeID',$id);
295: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
296: $serverhomeID = $response;
297: last;
298: }
299: }
300: if ($serverhomeID eq '') {
301: $serverhomeID = $machine_ids[-1];
302: }
303: } else {
304: $serverhomeID = $serverhomeIDs{$hostname};
305: }
306: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
307: }
308:
1.1121 raeburn 309: sub get_remote_globals {
310: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 311: my ($result,%returnhash,%whatneeded);
312: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 313: foreach my $what (sort(keys(%{$whathash}))) {
314: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 315: my ($response,$cached);
1.1121 raeburn 316: unless ($ignore_cache) {
1.1125 raeburn 317: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 318: }
319: if (defined($cached)) {
1.1125 raeburn 320: $returnhash{$what} = $response;
1.1121 raeburn 321: } else {
1.1125 raeburn 322: $whatneeded{$what} = 1;
1.1121 raeburn 323: }
324: }
1.1125 raeburn 325: if (keys(%whatneeded) == 0) {
326: $result = 'ok';
327: } else {
1.1121 raeburn 328: my $requested = &freeze_escape(\%whatneeded);
329: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 330: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
331: ($rep eq 'unknown_cmd')) {
332: $result = $rep;
333: } else {
334: $result = 'ok';
1.1121 raeburn 335: my @pairs=split(/\&/,$rep);
1.1125 raeburn 336: foreach my $item (@pairs) {
337: my ($key,$value)=split(/=/,$item,2);
338: my $what = &unescape($key);
339: my $hashid = $lonhost.'-'.$what;
340: $returnhash{$what}=&thaw_unescape($value);
341: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 342: }
343: }
344: }
345: }
1.1125 raeburn 346: return ($result,\%returnhash);
1.1121 raeburn 347: }
348:
1.1124 raeburn 349: sub remote_devalidate_cache {
350: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 351: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 352: return $response;
353: }
354:
1.1 albertel 355: # -------------------------------------------------- Non-critical communication
356: sub subreply {
357: my ($cmd,$server)=@_;
1.838 albertel 358: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 359: #
360: # With loncnew process trimming, there's a timing hole between lonc server
361: # process exit and the master server picking up the listen on the AF_UNIX
362: # socket. In that time interval, a lock file will exist:
363:
364: my $lockfile=$peerfile.".lock";
365: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
366: sleep(1);
367: }
368: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 369: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 370: #
1.550 foxr 371: # We'll give the connection a few tries before abandoning it. If
372: # connection is not possible, we'll con_lost back to the client.
373: #
374: my $client;
375: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
376: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
377: Type => SOCK_STREAM,
378: Timeout => 10);
1.869 albertel 379: if ($client) {
1.550 foxr 380: last; # Connected!
1.850 albertel 381: } else {
1.853 albertel 382: &create_connection(&hostname($server),$server);
1.550 foxr 383: }
1.850 albertel 384: sleep(1); # Try again later if failed connection.
1.550 foxr 385: }
386: my $answer;
387: if ($client) {
1.704 albertel 388: print $client "sethost:$server:$cmd\n";
1.550 foxr 389: $answer=<$client>;
390: if (!$answer) { $answer="con_lost"; }
391: chomp($answer);
392: } else {
393: $answer = 'con_lost'; # Failed connection.
394: }
1.1 albertel 395: return $answer;
396: }
397:
398: sub reply {
399: my ($cmd,$server)=@_;
1.838 albertel 400: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 401: my $answer=subreply($cmd,$server);
1.65 www 402: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 403: &logthis("<font color=\"blue\">WARNING:".
1.12 www 404: " $cmd to $server returned $answer</font>");
405: }
1.1 albertel 406: return $answer;
407: }
408:
409: # ----------------------------------------------------------- Send USR1 to lonc
410:
411: sub reconlonc {
1.891 albertel 412: my ($lonid) = @_;
413: my $hostname = &hostname($lonid);
414: if ($lonid) {
415: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
416: if ($hostname && -e $peerfile) {
417: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
418: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
419: Type => SOCK_STREAM,
420: Timeout => 10);
421: if ($client) {
422: print $client ("reset_retries\n");
423: my $answer=<$client>;
424: #reset just this one.
425: }
426: }
427: return;
428: }
429:
1.836 www 430: &logthis("Trying to reconnect lonc");
1.1 albertel 431: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 432: if (open(my $fh,"<$loncfile")) {
1.1 albertel 433: my $loncpid=<$fh>;
434: chomp($loncpid);
435: if (kill 0 => $loncpid) {
436: &logthis("lonc at pid $loncpid responding, sending USR1");
437: kill USR1 => $loncpid;
438: sleep 1;
1.836 www 439: } else {
1.12 www 440: &logthis(
1.672 albertel 441: "<font color=\"blue\">WARNING:".
1.12 www 442: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 443: }
444: } else {
1.836 www 445: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 446: }
447: }
448:
449: # ------------------------------------------------------ Critical communication
1.12 www 450:
1.1 albertel 451: sub critical {
452: my ($cmd,$server)=@_;
1.838 albertel 453: unless (&hostname($server)) {
1.672 albertel 454: &logthis("<font color=\"blue\">WARNING:".
1.89 www 455: " Critical message to unknown server ($server)</font>");
456: return 'no_such_host';
457: }
1.1 albertel 458: my $answer=reply($cmd,$server);
459: if ($answer eq 'con_lost') {
460: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 461: my $answer=reply($cmd,$server);
1.1 albertel 462: if ($answer eq 'con_lost') {
463: my $now=time;
464: my $middlename=$cmd;
1.5 www 465: $middlename=substr($middlename,0,16);
1.1 albertel 466: $middlename=~s/\W//g;
467: my $dfilename=
1.305 www 468: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
469: $dumpcount++;
1.1 albertel 470: {
1.448 albertel 471: my $dfh;
472: if (open($dfh,">$dfilename")) {
473: print $dfh "$cmd\n";
474: close($dfh);
475: }
1.1 albertel 476: }
477: sleep 2;
478: my $wcmd='';
479: {
1.448 albertel 480: my $dfh;
481: if (open($dfh,"<$dfilename")) {
482: $wcmd=<$dfh>;
483: close($dfh);
484: }
1.1 albertel 485: }
486: chomp($wcmd);
1.7 www 487: if ($wcmd eq $cmd) {
1.672 albertel 488: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 489: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 490: &logperm("D:$server:$cmd");
491: return 'con_delayed';
492: } else {
1.672 albertel 493: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 494: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 495: &logperm("F:$server:$cmd");
496: return 'con_failed';
497: }
498: }
499: }
500: return $answer;
1.405 albertel 501: }
502:
1.755 albertel 503: # ------------------------------------------- check if return value is an error
504:
505: sub error {
506: my ($result) = @_;
1.756 albertel 507: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 508: if ($2 == 2) { return undef; }
509: return $1;
510: }
511: return undef;
512: }
513:
1.783 albertel 514: sub convert_and_load_session_env {
515: my ($lonidsdir,$handle)=@_;
516: my @profile;
517: {
1.917 albertel 518: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
519: if (!$opened) {
1.915 albertel 520: return 0;
521: }
1.783 albertel 522: flock($idf,LOCK_SH);
523: @profile=<$idf>;
524: close($idf);
525: }
526: my %temp_env;
527: foreach my $line (@profile) {
1.786 albertel 528: if ($line !~ m/=/) {
529: return 0;
530: }
1.783 albertel 531: chomp($line);
532: my ($envname,$envvalue)=split(/=/,$line,2);
533: $temp_env{&unescape($envname)} = &unescape($envvalue);
534: }
535: unlink("$lonidsdir/$handle.id");
536: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
537: 0640)) {
538: %disk_env = %temp_env;
539: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
540: untie(%disk_env);
541: }
1.786 albertel 542: return 1;
1.783 albertel 543: }
544:
1.374 www 545: # ------------------------------------------- Transfer profile into environment
1.780 albertel 546: my $env_loaded;
547: sub transfer_profile_to_env {
1.788 albertel 548: my ($lonidsdir,$handle,$force_transfer) = @_;
549: if (!$force_transfer && $env_loaded) { return; }
1.374 www 550:
1.720 albertel 551: if (!defined($lonidsdir)) {
552: $lonidsdir = $perlvar{'lonIDsDir'};
553: }
554: if (!defined($handle)) {
555: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
556: }
557:
1.786 albertel 558: my $convert;
559: {
1.917 albertel 560: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
561: if (!$opened) {
1.915 albertel 562: return;
563: }
1.786 albertel 564: flock($idf,LOCK_SH);
565: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
566: &GDBM_READER(),0640)) {
567: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
568: untie(%disk_env);
569: } else {
570: $convert = 1;
571: }
572: }
573: if ($convert) {
574: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
575: &logthis("Failed to load session, or convert session.");
576: }
1.374 www 577: }
1.783 albertel 578:
1.786 albertel 579: my %remove;
1.783 albertel 580: while ( my $envname = each(%env) ) {
1.433 matthew 581: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
582: if ($time < time-300) {
1.783 albertel 583: $remove{$key}++;
1.433 matthew 584: }
585: }
586: }
1.783 albertel 587:
1.619 albertel 588: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 589: $env_loaded=1;
1.783 albertel 590: foreach my $expired_key (keys(%remove)) {
1.433 matthew 591: &delenv($expired_key);
1.374 www 592: }
1.1 albertel 593: }
594:
1.916 albertel 595: # ---------------------------------------------------- Check for valid session
596: sub check_for_valid_session {
597: my ($r) = @_;
598: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
599: my $lonid=$cookies{'lonID'};
600: return undef if (!$lonid);
601:
602: my $handle=&LONCAPA::clean_handle($lonid->value);
603: my $lonidsdir=$r->dir_config('lonIDsDir');
604: return undef if (!-e "$lonidsdir/$handle.id");
605:
1.917 albertel 606: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
607: return undef if (!$opened);
1.916 albertel 608:
609: flock($idf,LOCK_SH);
610: my %disk_env;
611: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
612: &GDBM_READER(),0640)) {
613: return undef;
614: }
615:
616: if (!defined($disk_env{'user.name'})
617: || !defined($disk_env{'user.domain'})) {
618: return undef;
619: }
620: return $handle;
621: }
622:
1.830 albertel 623: sub timed_flock {
624: my ($file,$lock_type) = @_;
625: my $failed=0;
626: eval {
627: local $SIG{__DIE__}='DEFAULT';
628: local $SIG{ALRM}=sub {
629: $failed=1;
630: die("failed lock");
631: };
632: alarm(13);
633: flock($file,$lock_type);
634: alarm(0);
635: };
636: if ($failed) {
637: return undef;
638: } else {
639: return 1;
640: }
641: }
642:
1.5 www 643: # ---------------------------------------------------------- Append Environment
644:
645: sub appenv {
1.949 raeburn 646: my ($newenv,$roles) = @_;
647: if (ref($newenv) eq 'HASH') {
648: foreach my $key (keys(%{$newenv})) {
649: my $refused = 0;
650: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
651: $refused = 1;
652: if (ref($roles) eq 'ARRAY') {
653: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
654: if (grep(/^\Q$role\E$/,@{$roles})) {
655: $refused = 0;
656: }
657: }
658: }
659: if ($refused) {
660: &logthis("<font color=\"blue\">WARNING: ".
661: "Attempt to modify environment ".$key." to ".$newenv->{$key}
662: .'</font>');
663: delete($newenv->{$key});
664: } else {
665: $env{$key}=$newenv->{$key};
666: }
667: }
668: my $opened = open(my $env_file,'+<',$env{'user.environment'});
669: if ($opened
670: && &timed_flock($env_file,LOCK_EX)
671: &&
672: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
673: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
674: while (my ($key,$value) = each(%{$newenv})) {
675: $disk_env{$key} = $value;
676: }
677: untie(%disk_env);
1.35 www 678: }
1.191 harris41 679: }
1.56 www 680: return 'ok';
681: }
682: # ----------------------------------------------------- Delete from Environment
683:
684: sub delenv {
1.1104 raeburn 685: my ($delthis,$regexp,$roles) = @_;
686: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
687: my $refused = 1;
688: if (ref($roles) eq 'ARRAY') {
689: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
690: if (grep(/^\Q$role\E$/,@{$roles})) {
691: $refused = 0;
692: }
693: }
694: if ($refused) {
695: &logthis("<font color=\"blue\">WARNING: ".
696: "Attempt to delete from environment ".$delthis);
697: return 'error';
698: }
1.56 www 699: }
1.917 albertel 700: my $opened = open(my $env_file,'+<',$env{'user.environment'});
701: if ($opened
1.915 albertel 702: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 703: &&
704: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
705: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 706: foreach my $key (keys(%disk_env)) {
1.987 raeburn 707: if ($regexp) {
708: if ($key=~/^$delthis/) {
709: delete($env{$key});
710: delete($disk_env{$key});
711: }
712: } else {
713: if ($key=~/^\Q$delthis\E/) {
714: delete($env{$key});
715: delete($disk_env{$key});
716: }
717: }
1.448 albertel 718: }
1.783 albertel 719: untie(%disk_env);
1.5 www 720: }
721: return 'ok';
1.369 albertel 722: }
723:
1.790 albertel 724: sub get_env_multiple {
725: my ($name) = @_;
726: my @values;
727: if (defined($env{$name})) {
728: # exists is it an array
729: if (ref($env{$name})) {
730: @values=@{ $env{$name} };
731: } else {
732: $values[0]=$env{$name};
733: }
734: }
735: return(@values);
736: }
737:
1.958 www 738: # ------------------------------------------------------------------- Locking
739:
740: sub set_lock {
741: my ($text)=@_;
742: $locknum++;
743: my $id=$$.'-'.$locknum;
744: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
745: 'session.lock.'.$id => $text});
746: return $id;
747: }
748:
749: sub get_locks {
750: my $num=0;
751: my %texts=();
752: foreach my $lock (split(/\,/,$env{'session.locks'})) {
753: if ($lock=~/\w/) {
754: $num++;
755: $texts{$lock}=$env{'session.lock.'.$lock};
756: }
757: }
758: return ($num,%texts);
759: }
760:
761: sub remove_lock {
762: my ($id)=@_;
763: my $newlocks='';
764: foreach my $lock (split(/\,/,$env{'session.locks'})) {
765: if (($lock=~/\w/) && ($lock ne $id)) {
766: $newlocks.=','.$lock;
767: }
768: }
769: &appenv({'session.locks' => $newlocks});
770: &delenv('session.lock.'.$id);
771: }
772:
773: sub remove_all_locks {
774: my $activelocks=$env{'session.locks'};
775: foreach my $lock (split(/\,/,$env{'session.locks'})) {
776: if ($lock=~/\w/) {
777: &remove_lock($lock);
778: }
779: }
780: }
781:
782:
1.369 albertel 783: # ------------------------------------------ Find out current server userload
784: sub userload {
785: my $numusers=0;
786: {
787: opendir(LONIDS,$perlvar{'lonIDsDir'});
788: my $filename;
789: my $curtime=time;
790: while ($filename=readdir(LONIDS)) {
1.925 albertel 791: next if ($filename eq '.' || $filename eq '..');
792: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 793: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 794: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 795: }
796: closedir(LONIDS);
797: }
798: my $userloadpercent=0;
799: my $maxuserload=$perlvar{'lonUserLoadLim'};
800: if ($maxuserload) {
1.371 albertel 801: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 802: }
1.372 albertel 803: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 804: return $userloadpercent;
1.283 www 805: }
806:
1.1 albertel 807: # ------------------------------ Find server with least workload from spare.tab
1.11 www 808:
1.1 albertel 809: sub spareserver {
1.1083 raeburn 810: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 811: my $spare_server;
1.370 albertel 812: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 813: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
814: : $userloadpercent;
1.1083 raeburn 815: my ($uint_dom,$remotesessions);
816: if (($udom ne '') && (&domain($udom) ne '')) {
817: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
818: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
819: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
820: $remotesessions = $udomdefaults{'remotesessions'};
821: }
1.1123 raeburn 822: my $spareshash = &this_host_spares($udom);
823: if (ref($spareshash) eq 'HASH') {
824: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
825: foreach my $try_server (@{ $spareshash->{'primary'} }) {
826: if ($uint_dom) {
827: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
828: $try_server));
829: }
830: ($spare_server, $lowest_load) =
831: &compare_server_load($try_server, $spare_server, $lowest_load);
832: }
1.1083 raeburn 833: }
1.784 albertel 834:
1.1123 raeburn 835: my $found_server = ($spare_server ne '' && $lowest_load < 100);
836:
837: if (!$found_server) {
838: if (ref($spareshash->{'default'}) eq 'ARRAY') {
839: foreach my $try_server (@{ $spareshash->{'default'} }) {
840: if ($uint_dom) {
841: next unless (&spare_can_host($udom,$uint_dom,
842: $remotesessions,$try_server));
843: }
844: ($spare_server, $lowest_load) =
845: &compare_server_load($try_server, $spare_server, $lowest_load);
846: }
847: }
848: }
1.784 albertel 849: }
850:
851: if (!$want_server_name) {
1.968 raeburn 852: my $protocol = 'http';
853: if ($protocol{$spare_server} eq 'https') {
854: $protocol = $protocol{$spare_server};
855: }
1.1001 raeburn 856: if (defined($spare_server)) {
857: my $hostname = &hostname($spare_server);
1.1083 raeburn 858: if (defined($hostname)) {
1.1001 raeburn 859: $spare_server = $protocol.'://'.$hostname;
860: }
861: }
1.784 albertel 862: }
863: return $spare_server;
864: }
865:
866: sub compare_server_load {
867: my ($try_server, $spare_server, $lowest_load) = @_;
868:
869: my $loadans = &reply('load', $try_server);
870: my $userloadans = &reply('userload',$try_server);
871:
872: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 873: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 874: }
875:
876: my $load;
877: if ($loadans =~ /\d/) {
878: if ($userloadans =~ /\d/) {
879: #both are numbers, pick the bigger one
880: $load = ($loadans > $userloadans) ? $loadans
881: : $userloadans;
1.411 albertel 882: } else {
1.784 albertel 883: $load = $loadans;
1.411 albertel 884: }
1.784 albertel 885: } else {
886: $load = $userloadans;
887: }
888:
889: if (($load =~ /\d/) && ($load < $lowest_load)) {
890: $spare_server = $try_server;
891: $lowest_load = $load;
1.370 albertel 892: }
1.784 albertel 893: return ($spare_server,$lowest_load);
1.202 matthew 894: }
1.914 albertel 895:
896: # --------------------------- ask offload servers if user already has a session
897: sub find_existing_session {
898: my ($udom,$uname) = @_;
1.1123 raeburn 899: my $spareshash = &this_host_spares($udom);
900: if (ref($spareshash) eq 'HASH') {
901: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
902: foreach my $try_server (@{ $spareshash->{'primary'} }) {
903: return $try_server if (&has_user_session($try_server, $udom, $uname));
904: }
905: }
906: if (ref($spareshash->{'default'}) eq 'ARRAY') {
907: foreach my $try_server (@{ $spareshash->{'default'} }) {
908: return $try_server if (&has_user_session($try_server, $udom, $uname));
909: }
910: }
1.914 albertel 911: }
912: return;
913: }
914:
915: # -------------------------------- ask if server already has a session for user
916: sub has_user_session {
917: my ($lonid,$udom,$uname) = @_;
918: my $result = &reply(join(':','userhassession',
919: map {&escape($_)} ($udom,$uname)),$lonid);
920: return 1 if ($result eq 'ok');
921:
922: return 0;
923: }
924:
1.1076 raeburn 925: # --------- determine least loaded server in a user's domain which allows login
926:
927: sub choose_server {
1.1115 raeburn 928: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 929: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 930: my %servers = &get_servers($udom);
1.1076 raeburn 931: my $lowest_load = 30000;
1.1116 raeburn 932: my ($login_host,$hostname,$portal_path);
1.1076 raeburn 933: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 934: my $loginvia;
935: if ($checkloginvia) {
936: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 937: if ($loginvia) {
938: my ($server,$path) = split(/:/,$loginvia);
939: ($login_host, $lowest_load) =
940: &compare_server_load($server, $login_host, $lowest_load);
941: if ($login_host eq $server) {
942: $portal_path = $path;
943: }
944: } else {
945: ($login_host, $lowest_load) =
946: &compare_server_load($lonhost, $login_host, $lowest_load);
947: if ($login_host eq $lonhost) {
948: $portal_path = '';
949: }
950: }
951: } else {
1.1076 raeburn 952: ($login_host, $lowest_load) =
1.1116 raeburn 953: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 954: }
955: }
956: if ($login_host ne '') {
1.1116 raeburn 957: $hostname = &hostname($login_host);
1.1076 raeburn 958: }
1.1116 raeburn 959: return ($login_host,$hostname,$portal_path);
1.1076 raeburn 960: }
961:
1.202 matthew 962: # --------------------------------------------- Try to change a user's password
963:
964: sub changepass {
1.799 raeburn 965: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 966: $currentpass = &escape($currentpass);
967: $newpass = &escape($newpass);
1.1030 raeburn 968: my $lonhost = $perlvar{'lonHostID'};
969: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 970: $server);
971: if (! $answer) {
972: &logthis("No reply on password change request to $server ".
973: "by $uname in domain $udom.");
974: } elsif ($answer =~ "^ok") {
975: &logthis("$uname in $udom successfully changed their password ".
976: "on $server.");
977: } elsif ($answer =~ "^pwchange_failure") {
978: &logthis("$uname in $udom was unable to change their password ".
979: "on $server. The action was blocked by either lcpasswd ".
980: "or pwchange");
981: } elsif ($answer =~ "^non_authorized") {
982: &logthis("$uname in $udom did not get their password correct when ".
983: "attempting to change it on $server.");
984: } elsif ($answer =~ "^auth_mode_error") {
985: &logthis("$uname in $udom attempted to change their password despite ".
986: "not being locally or internally authenticated on $server.");
987: } elsif ($answer =~ "^unknown_user") {
988: &logthis("$uname in $udom attempted to change their password ".
989: "on $server but were unable to because $server is not ".
990: "their home server.");
991: } elsif ($answer =~ "^refused") {
992: &logthis("$server refused to change $uname in $udom password because ".
993: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 994: } elsif ($answer =~ "invalid_client") {
995: &logthis("$server refused to change $uname in $udom password because ".
996: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 997: }
998: return $answer;
1.1 albertel 999: }
1000:
1.169 harris41 1001: # ----------------------- Try to determine user's current authentication scheme
1002:
1003: sub queryauthenticate {
1004: my ($uname,$udom)=@_;
1.456 albertel 1005: my $uhome=&homeserver($uname,$udom);
1006: if (!$uhome) {
1007: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1008: return 'no_host';
1009: }
1010: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1011: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1012: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1013: }
1.456 albertel 1014: return $answer;
1.169 harris41 1015: }
1016:
1.1 albertel 1017: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1018:
1.1 albertel 1019: sub authenticate {
1.1073 raeburn 1020: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1021: $upass=&escape($upass);
1022: $uname= &LONCAPA::clean_username($uname);
1.836 www 1023: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1024: my $newhome;
1.836 www 1025: if ((!$uhome) || ($uhome eq 'no_host')) {
1026: # Maybe the machine was offline and only re-appeared again recently?
1027: &reconlonc();
1028: # One more
1.952 raeburn 1029: $uhome=&homeserver($uname,$udom,1);
1030: if (($uhome eq 'no_host') && $checkdefauth) {
1031: if (defined(&domain($udom,'primary'))) {
1032: $newhome=&domain($udom,'primary');
1033: }
1034: if ($newhome ne '') {
1035: $uhome = $newhome;
1036: }
1037: }
1.836 www 1038: if ((!$uhome) || ($uhome eq 'no_host')) {
1039: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1040: return 'no_host';
1041: }
1.1 albertel 1042: }
1.1073 raeburn 1043: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1044: if ($answer eq 'authorized') {
1.952 raeburn 1045: if ($newhome) {
1046: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1047: return 'no_account_on_host';
1048: } else {
1049: &logthis("User $uname at $udom authorized by $uhome");
1050: return $uhome;
1051: }
1.471 albertel 1052: }
1053: if ($answer eq 'non_authorized') {
1054: &logthis("User $uname at $udom rejected by $uhome");
1055: return 'no_host';
1.9 www 1056: }
1.471 albertel 1057: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1058: return 'no_host';
1059: }
1060:
1.1073 raeburn 1061: sub can_host_session {
1.1074 raeburn 1062: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1063: my $canhost = 1;
1.1074 raeburn 1064: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1065: if (ref($remotesessions) eq 'HASH') {
1066: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1067: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1068: $canhost = 0;
1069: } else {
1070: $canhost = 1;
1071: }
1072: }
1073: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1074: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1075: $canhost = 1;
1076: } else {
1077: $canhost = 0;
1078: }
1079: }
1080: if ($canhost) {
1081: if ($remotesessions->{'version'} ne '') {
1082: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1083: if ($reqmajor ne '' && $reqminor ne '') {
1084: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1085: my $major = $1;
1086: my $minor = $2;
1087: if (($major < $reqmajor ) ||
1088: (($major == $reqmajor) && ($minor < $reqminor))) {
1089: $canhost = 0;
1090: }
1091: } else {
1092: $canhost = 0;
1093: }
1094: }
1095: }
1096: }
1097: }
1098: if ($canhost) {
1099: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1100: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1101: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1102: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1103: if (($uint_dom ne '') &&
1104: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1105: $canhost = 0;
1106: } else {
1107: $canhost = 1;
1108: }
1109: }
1110: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1111: if (($uint_dom ne '') &&
1112: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1113: $canhost = 1;
1114: } else {
1115: $canhost = 0;
1116: }
1117: }
1118: }
1119: }
1120: return $canhost;
1121: }
1122:
1.1083 raeburn 1123: sub spare_can_host {
1124: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1125: my $canhost=1;
1126: my @intdoms;
1127: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1128: if (ref($internet_names) eq 'ARRAY') {
1129: @intdoms = @{$internet_names};
1130: }
1131: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1132: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1133: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1134: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1135: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1136: $canhost = &can_host_session($udom,$try_server,$remoterev,
1137: $remotesessions,
1138: $defdomdefaults{'hostedsessions'});
1139: }
1140: return $canhost;
1141: }
1142:
1.1123 raeburn 1143: sub this_host_spares {
1144: my ($dom) = @_;
1.1126 raeburn 1145: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1146: my @hosts = ¤t_machine_ids();
1147: foreach my $lonhost (@hosts) {
1148: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1149: $dom_in_use = $dom;
1150: $lonhost_in_use = $lonhost;
1.1123 raeburn 1151: last;
1152: }
1153: }
1.1126 raeburn 1154: if ($dom_in_use ne '') {
1155: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1156: }
1157: if (ref($result) ne 'HASH') {
1158: $lonhost_in_use = $perlvar{'lonHostID'};
1159: $dom_in_use = &host_domain($lonhost_in_use);
1160: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1161: if (ref($result) ne 'HASH') {
1162: $result = \%spareid;
1163: }
1164: }
1165: return $result;
1166: }
1167:
1168: sub spares_for_offload {
1169: my ($dom_in_use,$lonhost_in_use) = @_;
1170: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1171: if (defined($cached)) {
1172: return $result;
1173: } else {
1.1126 raeburn 1174: my $cachetime = 60*60*24;
1175: my %domconfig =
1176: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1177: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1178: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1179: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1180: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1181: }
1182: }
1183: }
1184: }
1.1126 raeburn 1185: return;
1.1123 raeburn 1186: }
1187:
1.1129 raeburn 1188: sub get_lonbalancer_config {
1189: my ($servers) = @_;
1190: my ($currbalancer,$currtargets);
1191: if (ref($servers) eq 'HASH') {
1192: foreach my $server (keys(%{$servers})) {
1193: my %what = (
1194: spareid => 1,
1195: perlvar => 1,
1196: );
1197: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1198: if ($result eq 'ok') {
1199: if (ref($returnhash) eq 'HASH') {
1200: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1201: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1202: $currbalancer = $server;
1203: $currtargets = {};
1204: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1205: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1206: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1207: }
1208: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1209: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1210: }
1211: }
1212: last;
1213: }
1214: }
1215: }
1216: }
1217: }
1218: }
1219: return ($currbalancer,$currtargets);
1220: }
1221:
1222: sub check_loadbalancing {
1223: my ($uname,$udom) = @_;
1224: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1225: $offloadto,$otherserver);
1226: my $lonhost = $perlvar{'lonHostID'};
1227: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1228: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1229: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1230: my $serverhomedom = &host_domain($lonhost);
1231:
1232: my $cachetime = 60*60*24;
1233:
1234: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1235: $dom_in_use = $udom;
1236: $homeintdom = 1;
1237: } else {
1238: $dom_in_use = $serverhomedom;
1239: }
1240: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1241: unless (defined($cached)) {
1242: my %domconfig =
1243: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1244: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1245: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1246: }
1247: }
1248: if (ref($result) eq 'HASH') {
1249: my $currbalancer = $result->{'lonhost'};
1250: my $currtargets = $result->{'targets'};
1251: my $currrules = $result->{'rules'};
1252: if ($currbalancer ne '') {
1253: my @hosts = ¤t_machine_ids();
1254: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1255: $is_balancer = 1;
1256: }
1257: }
1258: if ($is_balancer) {
1259: if (ref($currrules) eq 'HASH') {
1260: if ($homeintdom) {
1261: if ($uname ne '') {
1262: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1263: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1264: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1265: $rule_in_effect = $currrules->{'_LC_author'};
1266: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1267: $rule_in_effect = $currrules->{'_LC_adv'}
1268: }
1269: }
1270: if ($rule_in_effect eq '') {
1271: my %userenv = &userenvironment($udom,$uname,'inststatus');
1272: if ($userenv{'inststatus'} ne '') {
1273: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1274: my ($othertitle,$usertypes,$types) =
1275: &Apache::loncommon::sorted_inst_types($udom);
1276: if (ref($types) eq 'ARRAY') {
1277: foreach my $type (@{$types}) {
1278: if (grep(/^\Q$type\E$/,@statuses)) {
1279: if (exists($currrules->{$type})) {
1280: $rule_in_effect = $currrules->{$type};
1281: }
1282: }
1283: }
1284: }
1285: } else {
1286: if (exists($currrules->{'default'})) {
1287: $rule_in_effect = $currrules->{'default'};
1288: }
1289: }
1290: }
1291: } else {
1292: if (exists($currrules->{'default'})) {
1293: $rule_in_effect = $currrules->{'default'};
1294: }
1295: }
1296: } else {
1297: if ($currrules->{'_LC_external'} ne '') {
1298: $rule_in_effect = $currrules->{'_LC_external'};
1299: }
1300: }
1301: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1302: $uname,$udom);
1303: }
1304: }
1305: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1306: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1307: unless (defined($cached)) {
1308: my %domconfig =
1309: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1310: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1311: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1312: }
1313: }
1314: if (ref($result) eq 'HASH') {
1315: my $currbalancer = $result->{'lonhost'};
1316: my $currtargets = $result->{'targets'};
1317: my $currrules = $result->{'rules'};
1318:
1319: if ($currbalancer eq $lonhost) {
1320: $is_balancer = 1;
1321: if (ref($currrules) eq 'HASH') {
1322: if ($currrules->{'_LC_internetdom'} ne '') {
1323: $rule_in_effect = $currrules->{'_LC_internetdom'};
1324: }
1325: }
1326: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1327: $uname,$udom);
1328: }
1329: } else {
1330: if ($perlvar{'lonBalancer'} eq 'yes') {
1331: $is_balancer = 1;
1332: $offloadto = &this_host_spares($dom_in_use);
1333: }
1334: }
1335: } else {
1336: if ($perlvar{'lonBalancer'} eq 'yes') {
1337: $is_balancer = 1;
1338: $offloadto = &this_host_spares($dom_in_use);
1339: }
1340: }
1341: my $lowest_load = 30000;
1342: if (ref($offloadto) eq 'HASH') {
1343: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1344: foreach my $try_server (@{$offloadto->{'primary'}}) {
1345: ($otherserver,$lowest_load) =
1346: &compare_server_load($try_server,$otherserver,$lowest_load);
1347: }
1348: }
1349: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1350:
1351: if (!$found_server) {
1352: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1353: foreach my $try_server (@{$offloadto->{'default'}}) {
1354: ($otherserver,$lowest_load) =
1355: &compare_server_load($try_server,$otherserver,$lowest_load);
1356: }
1357: }
1358: }
1359: } elsif (ref($offloadto) eq 'ARRAY') {
1360: if (@{$offloadto} == 1) {
1361: $otherserver = $offloadto->[0];
1362: } elsif (@{$offloadto} > 1) {
1363: foreach my $try_server (@{$offloadto}) {
1364: ($otherserver,$lowest_load) =
1365: &compare_server_load($try_server,$otherserver,$lowest_load);
1366: }
1367: }
1368: }
1369: return ($is_balancer,$otherserver);
1370: }
1371:
1372: sub get_loadbalancer_targets {
1373: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1374: my $offloadto;
1375: if ($rule_in_effect eq '') {
1376: $offloadto = $currtargets;
1377: } else {
1378: if ($rule_in_effect eq 'homeserver') {
1379: my $homeserver = &homeserver($uname,$udom);
1380: if ($homeserver ne 'no_host') {
1381: $offloadto = [$homeserver];
1382: }
1383: } elsif ($rule_in_effect eq 'externalbalancer') {
1384: my %domconfig =
1385: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1386: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1387: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1388: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1389: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1390: }
1391: }
1392: } else {
1393: my %servers = &dom_servers($udom);
1394: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1395: if (&hostname($remotebalancer) ne '') {
1396: $offloadto = [$remotebalancer];
1397: }
1398: }
1399: } elsif (&hostname($rule_in_effect) ne '') {
1400: $offloadto = [$rule_in_effect];
1401: }
1402: }
1403: return $offloadto;
1404: }
1405:
1.1127 raeburn 1406: sub internet_dom_servers {
1407: my ($dom) = @_;
1408: my (%uniqservers,%servers);
1409: my $primaryserver = &hostname(&domain($dom,'primary'));
1410: my @machinedoms = &machine_domains($primaryserver);
1411: foreach my $mdom (@machinedoms) {
1412: my %currservers = %servers;
1413: my %server = &get_servers($mdom);
1414: %servers = (%currservers,%server);
1415: }
1416: my %by_hostname;
1417: foreach my $id (keys(%servers)) {
1418: push(@{$by_hostname{$servers{$id}}},$id);
1419: }
1420: foreach my $hostname (sort(keys(%by_hostname))) {
1421: if (@{$by_hostname{$hostname}} > 1) {
1422: my $match = 0;
1423: foreach my $id (@{$by_hostname{$hostname}}) {
1424: if (&host_domain($id) eq $dom) {
1425: $uniqservers{$id} = $hostname;
1426: $match = 1;
1427: }
1428: }
1429: unless ($match) {
1430: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1431: }
1432: } else {
1433: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1434: }
1435: }
1436: return %uniqservers;
1437: }
1438:
1.1 albertel 1439: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1440:
1.599 albertel 1441: my %homecache;
1.1 albertel 1442: sub homeserver {
1.230 stredwic 1443: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1444: my $index="$uname:$udom";
1.426 albertel 1445:
1.599 albertel 1446: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1447:
1448: my %servers = &get_servers($udom,'library');
1449: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1450: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1451: exists($badServerCache{$tryserver}));
1.841 albertel 1452:
1453: my $answer=reply("home:$udom:$uname",$tryserver);
1454: if ($answer eq 'found') {
1455: delete($badServerCache{$tryserver});
1456: return $homecache{$index}=$tryserver;
1457: } elsif ($answer eq 'no_host') {
1458: $badServerCache{$tryserver}=1;
1459: }
1.1 albertel 1460: }
1461: return 'no_host';
1.70 www 1462: }
1463:
1464: # ------------------------------------- Find the usernames behind a list of IDs
1465:
1466: sub idget {
1467: my ($udom,@ids)=@_;
1468: my %returnhash=();
1469:
1.841 albertel 1470: my %servers = &get_servers($udom,'library');
1471: foreach my $tryserver (keys(%servers)) {
1472: my $idlist=join('&',@ids);
1473: $idlist=~tr/A-Z/a-z/;
1474: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1475: my @answer=();
1476: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1477: @answer=split(/\&/,$reply);
1478: } ;
1479: my $i;
1480: for ($i=0;$i<=$#ids;$i++) {
1481: if ($answer[$i]) {
1482: $returnhash{$ids[$i]}=$answer[$i];
1483: }
1484: }
1485: }
1.70 www 1486: return %returnhash;
1487: }
1488:
1489: # ------------------------------------- Find the IDs behind a list of usernames
1490:
1491: sub idrget {
1492: my ($udom,@unames)=@_;
1493: my %returnhash=();
1.800 albertel 1494: foreach my $uname (@unames) {
1495: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1496: }
1.70 www 1497: return %returnhash;
1498: }
1499:
1500: # ------------------------------- Store away a list of names and associated IDs
1501:
1502: sub idput {
1503: my ($udom,%ids)=@_;
1504: my %servers=();
1.800 albertel 1505: foreach my $uname (keys(%ids)) {
1506: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1507: my $uhom=&homeserver($uname,$udom);
1.70 www 1508: if ($uhom ne 'no_host') {
1.800 albertel 1509: my $id=&escape($ids{$uname});
1.70 www 1510: $id=~tr/A-Z/a-z/;
1.800 albertel 1511: my $esc_unam=&escape($uname);
1.70 www 1512: if ($servers{$uhom}) {
1.800 albertel 1513: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1514: } else {
1.800 albertel 1515: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1516: }
1517: }
1.191 harris41 1518: }
1.800 albertel 1519: foreach my $server (keys(%servers)) {
1520: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1521: }
1.344 www 1522: }
1523:
1.1023 raeburn 1524: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1525: sub dump_dom {
1.1023 raeburn 1526: my ($namespace,$udom,$regexp,$range)=@_;
1.1012 raeburn 1527: if (!$udom) {
1528: $udom=$env{'user.domain'};
1529: }
1530: my %returnhash;
1.1023 raeburn 1531: if ($udom) {
1532: my $uname = &get_domainconfiguser($udom);
1533: %returnhash = &dump($namespace,$udom,$uname,$regexp,$range);
1.1012 raeburn 1534: }
1535: return %returnhash;
1536: }
1537:
1.1023 raeburn 1538: # ------------------------------------------ get items from domain db files
1.806 raeburn 1539:
1540: sub get_dom {
1.860 raeburn 1541: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1542: my $items='';
1543: foreach my $item (@$storearr) {
1544: $items.=&escape($item).'&';
1545: }
1546: $items=~s/\&$//;
1.860 raeburn 1547: if (!$udom) {
1548: $udom=$env{'user.domain'};
1549: if (defined(&domain($udom,'primary'))) {
1550: $uhome=&domain($udom,'primary');
1551: } else {
1.874 albertel 1552: undef($uhome);
1.860 raeburn 1553: }
1554: } else {
1555: if (!$uhome) {
1556: if (defined(&domain($udom,'primary'))) {
1557: $uhome=&domain($udom,'primary');
1558: }
1559: }
1560: }
1561: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1562: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1563: my %returnhash;
1.875 albertel 1564: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1565: return %returnhash;
1566: }
1.806 raeburn 1567: my @pairs=split(/\&/,$rep);
1568: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1569: return @pairs;
1570: }
1571: my $i=0;
1572: foreach my $item (@$storearr) {
1573: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1574: $i++;
1575: }
1576: return %returnhash;
1577: } else {
1.880 banghart 1578: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1579: }
1580: }
1581:
1582: # -------------------------------------------- put items in domain db files
1583:
1584: sub put_dom {
1.860 raeburn 1585: my ($namespace,$storehash,$udom,$uhome)=@_;
1586: if (!$udom) {
1587: $udom=$env{'user.domain'};
1588: if (defined(&domain($udom,'primary'))) {
1589: $uhome=&domain($udom,'primary');
1590: } else {
1.874 albertel 1591: undef($uhome);
1.860 raeburn 1592: }
1593: } else {
1594: if (!$uhome) {
1595: if (defined(&domain($udom,'primary'))) {
1596: $uhome=&domain($udom,'primary');
1597: }
1598: }
1599: }
1600: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1601: my $items='';
1602: foreach my $item (keys(%$storehash)) {
1603: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1604: }
1605: $items=~s/\&$//;
1606: return &reply("putdom:$udom:$namespace:$items",$uhome);
1607: } else {
1.860 raeburn 1608: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1609: }
1610: }
1611:
1.1023 raeburn 1612: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1613: sub newput_dom {
1.1023 raeburn 1614: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1615: my $result;
1616: if (!$udom) {
1617: $udom=$env{'user.domain'};
1618: }
1.1023 raeburn 1619: if ($udom) {
1620: my $uname = &get_domainconfiguser($udom);
1621: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1622: }
1623: return $result;
1624: }
1625:
1.1023 raeburn 1626: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1627: sub del_dom {
1.1023 raeburn 1628: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1629: if (ref($storearr) eq 'ARRAY') {
1630: if (!$udom) {
1631: $udom=$env{'user.domain'};
1632: }
1.1023 raeburn 1633: if ($udom) {
1634: my $uname = &get_domainconfiguser($udom);
1635: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1636: }
1637: }
1638: }
1639:
1.1023 raeburn 1640: # ----------------------------------construct domainconfig user for a domain
1641: sub get_domainconfiguser {
1642: my ($udom) = @_;
1643: return $udom.'-domainconfig';
1644: }
1645:
1.837 raeburn 1646: sub retrieve_inst_usertypes {
1647: my ($udom) = @_;
1648: my (%returnhash,@order);
1.989 raeburn 1649: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1650: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1651: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1652: %returnhash = %{$domdefs{'inststatustypes'}};
1653: @order = @{$domdefs{'inststatusorder'}};
1654: } else {
1655: if (defined(&domain($udom,'primary'))) {
1656: my $uhome=&domain($udom,'primary');
1657: my $rep=&reply("inst_usertypes:$udom",$uhome);
1658: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1659: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1660: return (\%returnhash,\@order);
1661: }
1662: my ($hashitems,$orderitems) = split(/:/,$rep);
1663: my @pairs=split(/\&/,$hashitems);
1664: foreach my $item (@pairs) {
1665: my ($key,$value)=split(/=/,$item,2);
1666: $key = &unescape($key);
1667: next if ($key =~ /^error: 2 /);
1668: $returnhash{$key}=&thaw_unescape($value);
1669: }
1670: my @esc_order = split(/\&/,$orderitems);
1671: foreach my $item (@esc_order) {
1672: push(@order,&unescape($item));
1673: }
1674: } else {
1675: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1676: }
1677: }
1678: return (\%returnhash,\@order);
1679: }
1680:
1.868 raeburn 1681: sub is_domainimage {
1682: my ($url) = @_;
1683: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1684: if (&domain($1) ne '') {
1685: return '1';
1686: }
1687: }
1688: return;
1689: }
1690:
1.899 raeburn 1691: sub inst_directory_query {
1692: my ($srch) = @_;
1693: my $udom = $srch->{'srchdomain'};
1694: my %results;
1695: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1696: my $outcome;
1.899 raeburn 1697: if ($homeserver ne '') {
1.904 albertel 1698: my $queryid=&reply("querysend:instdirsearch:".
1699: &escape($srch->{'srchby'}).':'.
1700: &escape($srch->{'srchterm'}).':'.
1701: &escape($srch->{'srchtype'}),$homeserver);
1702: my $host=&hostname($homeserver);
1703: if ($queryid !~/^\Q$host\E\_/) {
1704: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1705: return;
1706: }
1707: my $response = &get_query_reply($queryid);
1708: my $maxtries = 5;
1709: my $tries = 1;
1710: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1711: $response = &get_query_reply($queryid);
1712: $tries ++;
1713: }
1714:
1715: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1716: if ($response eq 'unavailable') {
1717: $outcome = $response;
1718: } else {
1719: $outcome = 'ok';
1720: my @matches = split(/\n/,$response);
1721: foreach my $match (@matches) {
1722: my ($key,$value) = split(/=/,$match);
1723: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1724: }
1.899 raeburn 1725: }
1726: }
1727: }
1.909 raeburn 1728: return ($outcome,%results);
1.899 raeburn 1729: }
1730:
1731: sub usersearch {
1732: my ($srch) = @_;
1733: my $dom = $srch->{'srchdomain'};
1734: my %results;
1735: my %libserv = &all_library();
1736: my $query = 'usersearch';
1737: foreach my $tryserver (keys(%libserv)) {
1738: if (&host_domain($tryserver) eq $dom) {
1739: my $host=&hostname($tryserver);
1740: my $queryid=
1.911 raeburn 1741: &reply("querysend:".&escape($query).':'.
1742: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1743: &escape($srch->{'srchtype'}).':'.
1744: &escape($srch->{'srchterm'}),$tryserver);
1745: if ($queryid !~/^\Q$host\E\_/) {
1746: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1747: next;
1.899 raeburn 1748: }
1749: my $reply = &get_query_reply($queryid);
1750: my $maxtries = 1;
1751: my $tries = 1;
1752: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1753: $reply = &get_query_reply($queryid);
1754: $tries ++;
1755: }
1756: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1757: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1758: } else {
1.911 raeburn 1759: my @matches;
1760: if ($reply =~ /\n/) {
1761: @matches = split(/\n/,$reply);
1762: } else {
1763: @matches = split(/\&/,$reply);
1764: }
1.899 raeburn 1765: foreach my $match (@matches) {
1766: my ($uname,$udom,%userhash);
1.911 raeburn 1767: foreach my $entry (split(/:/,$match)) {
1768: my ($key,$value) =
1769: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1770: $userhash{$key} = $value;
1771: if ($key eq 'username') {
1772: $uname = $value;
1773: } elsif ($key eq 'domain') {
1774: $udom = $value;
1.911 raeburn 1775: }
1.899 raeburn 1776: }
1777: $results{$uname.':'.$udom} = \%userhash;
1778: }
1779: }
1780: }
1781: }
1782: return %results;
1783: }
1784:
1.912 raeburn 1785: sub get_instuser {
1786: my ($udom,$uname,$id) = @_;
1787: my $homeserver = &domain($udom,'primary');
1788: my ($outcome,%results);
1789: if ($homeserver ne '') {
1790: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1791: &escape($id).':'.&escape($udom),$homeserver);
1792: my $host=&hostname($homeserver);
1793: if ($queryid !~/^\Q$host\E\_/) {
1794: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1795: return;
1796: }
1797: my $response = &get_query_reply($queryid);
1798: my $maxtries = 5;
1799: my $tries = 1;
1800: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1801: $response = &get_query_reply($queryid);
1802: $tries ++;
1803: }
1804: if (!&error($response) && $response ne 'refused') {
1805: if ($response eq 'unavailable') {
1806: $outcome = $response;
1807: } else {
1808: $outcome = 'ok';
1809: my @matches = split(/\n/,$response);
1810: foreach my $match (@matches) {
1811: my ($key,$value) = split(/=/,$match);
1812: $results{&unescape($key)} = &thaw_unescape($value);
1813: }
1814: }
1815: }
1816: }
1817: my %userinfo;
1818: if (ref($results{$uname}) eq 'HASH') {
1819: %userinfo = %{$results{$uname}};
1820: }
1821: return ($outcome,%userinfo);
1822: }
1823:
1824: sub inst_rulecheck {
1.923 raeburn 1825: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1826: my %returnhash;
1827: if ($udom ne '') {
1828: if (ref($rules) eq 'ARRAY') {
1829: @{$rules} = map {&escape($_);} (@{$rules});
1830: my $rulestr = join(':',@{$rules});
1831: my $homeserver=&domain($udom,'primary');
1832: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1833: my $response;
1834: if ($item eq 'username') {
1835: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1836: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1837: $homeserver));
1.923 raeburn 1838: } elsif ($item eq 'id') {
1839: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1840: ':'.&escape($id).':'.$rulestr,
1841: $homeserver));
1.945 raeburn 1842: } elsif ($item eq 'selfcreate') {
1843: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1844: &escape($udom).':'.&escape($uname).
1845: ':'.$rulestr,$homeserver));
1.923 raeburn 1846: }
1.912 raeburn 1847: if ($response ne 'refused') {
1848: my @pairs=split(/\&/,$response);
1849: foreach my $item (@pairs) {
1850: my ($key,$value)=split(/=/,$item,2);
1851: $key = &unescape($key);
1852: next if ($key =~ /^error: 2 /);
1853: $returnhash{$key}=&thaw_unescape($value);
1854: }
1855: }
1856: }
1857: }
1858: }
1859: return %returnhash;
1860: }
1861:
1862: sub inst_userrules {
1.923 raeburn 1863: my ($udom,$check) = @_;
1.912 raeburn 1864: my (%ruleshash,@ruleorder);
1865: if ($udom ne '') {
1866: my $homeserver=&domain($udom,'primary');
1867: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1868: my $response;
1869: if ($check eq 'id') {
1870: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1871: $homeserver);
1.943 raeburn 1872: } elsif ($check eq 'email') {
1873: $response=&reply('instemailrules:'.&escape($udom),
1874: $homeserver);
1.923 raeburn 1875: } else {
1876: $response=&reply('instuserrules:'.&escape($udom),
1877: $homeserver);
1878: }
1.912 raeburn 1879: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1880: ($response ne 'unknown_cmd') &&
1.912 raeburn 1881: ($response ne 'no_such_host')) {
1882: my ($hashitems,$orderitems) = split(/:/,$response);
1883: my @pairs=split(/\&/,$hashitems);
1884: foreach my $item (@pairs) {
1885: my ($key,$value)=split(/=/,$item,2);
1886: $key = &unescape($key);
1887: next if ($key =~ /^error: 2 /);
1888: $ruleshash{$key}=&thaw_unescape($value);
1889: }
1890: my @esc_order = split(/\&/,$orderitems);
1891: foreach my $item (@esc_order) {
1892: push(@ruleorder,&unescape($item));
1893: }
1894: }
1895: }
1896: }
1897: return (\%ruleshash,\@ruleorder);
1898: }
1899:
1.976 raeburn 1900: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1901:
1902: sub get_domain_defaults {
1903: my ($domain) = @_;
1904: my $cachetime = 60*60*24;
1905: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1906: if (defined($cached)) {
1907: if (ref($result) eq 'HASH') {
1908: return %{$result};
1909: }
1910: }
1911: my %domdefaults;
1912: my %domconfig =
1.989 raeburn 1913: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1914: 'requestcourses','inststatus',
1.1073 raeburn 1915: 'coursedefaults','usersessions'],$domain);
1.943 raeburn 1916: if (ref($domconfig{'defaults'}) eq 'HASH') {
1917: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1918: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1919: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1920: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1921: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.943 raeburn 1922: } else {
1923: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1924: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1925: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1926: }
1.976 raeburn 1927: if (ref($domconfig{'quotas'}) eq 'HASH') {
1928: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1929: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1930: } else {
1931: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1932: }
1933: my @usertools = ('aboutme','blog','portfolio');
1934: foreach my $item (@usertools) {
1935: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1936: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1937: }
1938: }
1939: }
1.985 raeburn 1940: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1941: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1942: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1943: }
1944: }
1.989 raeburn 1945: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1946: foreach my $item ('inststatustypes','inststatusorder') {
1947: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1948: }
1949: }
1.1047 raeburn 1950: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1951: foreach my $item ('canuse_pdfforms') {
1952: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1953: }
1954: }
1.1073 raeburn 1955: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1956: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1957: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1958: }
1959: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1960: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1961: }
1962: }
1.943 raeburn 1963: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1964: $cachetime);
1965: return %domdefaults;
1966: }
1967:
1.344 www 1968: # --------------------------------------------------- Assign a key to a student
1969:
1970: sub assign_access_key {
1.364 www 1971: #
1972: # a valid key looks like uname:udom#comments
1973: # comments are being appended
1974: #
1.498 www 1975: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
1976: $kdom=
1.620 albertel 1977: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 1978: $knum=
1.620 albertel 1979: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 1980: $cdom=
1.620 albertel 1981: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 1982: $cnum=
1.620 albertel 1983: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1984: $udom=$env{'user.name'} unless (defined($udom));
1985: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 1986: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 1987: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 1988: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 1989: # assigned to this person
1990: # - this should not happen,
1.345 www 1991: # unless something went wrong
1992: # the first time around
1993: # ready to assign
1.364 www 1994: $logentry=$1.'; '.$logentry;
1.496 www 1995: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 1996: $kdom,$knum) eq 'ok') {
1.345 www 1997: # key now belongs to user
1.346 www 1998: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 1999: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2000: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2001: return 'ok';
2002: } else {
2003: return
2004: 'error: Count not permanently assign key, will need to be re-entered later.';
2005: }
2006: } else {
2007: return 'error: Could not assign key, try again later.';
2008: }
1.364 www 2009: } elsif (!$existing{$ckey}) {
1.345 www 2010: # the key does not exist
2011: return 'error: The key does not exist';
2012: } else {
2013: # the key is somebody else's
2014: return 'error: The key is already in use';
2015: }
1.344 www 2016: }
2017:
1.364 www 2018: # ------------------------------------------ put an additional comment on a key
2019:
2020: sub comment_access_key {
2021: #
2022: # a valid key looks like uname:udom#comments
2023: # comments are being appended
2024: #
2025: my ($ckey,$cdom,$cnum,$logentry)=@_;
2026: $cdom=
1.620 albertel 2027: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2028: $cnum=
1.620 albertel 2029: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2030: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2031: if ($existing{$ckey}) {
2032: $existing{$ckey}.='; '.$logentry;
2033: # ready to assign
1.367 www 2034: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2035: $cdom,$cnum) eq 'ok') {
2036: return 'ok';
2037: } else {
2038: return 'error: Count not store comment.';
2039: }
2040: } else {
2041: # the key does not exist
2042: return 'error: The key does not exist';
2043: }
2044: }
2045:
1.344 www 2046: # ------------------------------------------------------ Generate a set of keys
2047:
2048: sub generate_access_keys {
1.364 www 2049: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2050: $cdom=
1.620 albertel 2051: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2052: $cnum=
1.620 albertel 2053: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2054: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2055: unless (($cdom) && ($cnum)) { return 0; }
2056: if ($number>10000) { return 0; }
2057: sleep(2); # make sure don't get same seed twice
2058: srand(time()^($$+($$<<15))); # from "Programming Perl"
2059: my $total=0;
2060: for (my $i=1;$i<=$number;$i++) {
2061: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2062: sprintf("%lx",int(100000*rand)).'-'.
2063: sprintf("%lx",int(100000*rand));
2064: $newkey=~s/1/g/g; # folks mix up 1 and l
2065: $newkey=~s/0/h/g; # and also 0 and O
2066: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2067: if ($existing{$newkey}) {
2068: $i--;
2069: } else {
1.364 www 2070: if (&put('accesskeys',
2071: { $newkey => '# generated '.localtime().
1.620 albertel 2072: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2073: '; '.$logentry },
2074: $cdom,$cnum) eq 'ok') {
1.344 www 2075: $total++;
2076: }
2077: }
2078: }
1.620 albertel 2079: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2080: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2081: return $total;
2082: }
2083:
2084: # ------------------------------------------------------- Validate an accesskey
2085:
2086: sub validate_access_key {
2087: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2088: $cdom=
1.620 albertel 2089: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2090: $cnum=
1.620 albertel 2091: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2092: $udom=$env{'user.domain'} unless (defined($udom));
2093: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2094: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2095: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2096: }
2097:
2098: # ------------------------------------- Find the section of student in a course
1.652 albertel 2099: sub devalidate_getsection_cache {
2100: my ($udom,$unam,$courseid)=@_;
2101: my $hashid="$udom:$unam:$courseid";
2102: &devalidate_cache_new('getsection',$hashid);
2103: }
1.298 matthew 2104:
1.815 albertel 2105: sub courseid_to_courseurl {
2106: my ($courseid) = @_;
2107: #already url style courseid
2108: return $courseid if ($courseid =~ m{^/});
2109:
2110: if (exists($env{'course.'.$courseid.'.num'})) {
2111: my $cnum = $env{'course.'.$courseid.'.num'};
2112: my $cdom = $env{'course.'.$courseid.'.domain'};
2113: return "/$cdom/$cnum";
2114: }
2115:
2116: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2117: if (exists($courseinfo{'num'})) {
2118: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2119: }
2120:
2121: return undef;
2122: }
2123:
1.298 matthew 2124: sub getsection {
2125: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2126: my $cachetime=1800;
1.551 albertel 2127:
2128: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2129: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2130: if (defined($cached)) { return $result; }
2131:
1.298 matthew 2132: my %Pending;
2133: my %Expired;
2134: #
2135: # Each role can either have not started yet (pending), be active,
2136: # or have expired.
2137: #
2138: # If there is an active role, we are done.
2139: #
2140: # If there is more than one role which has not started yet,
2141: # choose the one which will start sooner
2142: # If there is one role which has not started yet, return it.
2143: #
2144: # If there is more than one expired role, choose the one which ended last.
2145: # If there is a role which has expired, return it.
2146: #
1.815 albertel 2147: $courseid = &courseid_to_courseurl($courseid);
1.1086 raeburn 2148: my $extra = &freeze_escape({'skipcheck' => 1});
2149: my %roleshash = &dump('roles',$udom,$unam,$courseid,undef,$extra);
1.817 raeburn 2150: foreach my $key (keys(%roleshash)) {
1.479 albertel 2151: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2152: my $section=$1;
2153: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2154: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2155: my $now=time;
1.548 albertel 2156: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2157: $Expired{$end}=$section;
2158: next;
2159: }
1.548 albertel 2160: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2161: $Pending{$start}=$section;
2162: next;
2163: }
1.599 albertel 2164: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2165: }
2166: #
2167: # Presumedly there will be few matching roles from the above
2168: # loop and the sorting time will be negligible.
2169: if (scalar(keys(%Pending))) {
2170: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2171: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2172: }
2173: if (scalar(keys(%Expired))) {
2174: my @sorted = sort {$a <=> $b} keys(%Expired);
2175: my $time = pop(@sorted);
1.599 albertel 2176: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2177: }
1.599 albertel 2178: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2179: }
1.70 www 2180:
1.599 albertel 2181: sub save_cache {
2182: &purge_remembered();
1.722 albertel 2183: #&Apache::loncommon::validate_page();
1.620 albertel 2184: undef(%env);
1.780 albertel 2185: undef($env_loaded);
1.599 albertel 2186: }
1.452 albertel 2187:
1.599 albertel 2188: my $to_remember=-1;
2189: my %remembered;
2190: my %accessed;
2191: my $kicks=0;
2192: my $hits=0;
1.849 albertel 2193: sub make_key {
2194: my ($name,$id) = @_;
1.872 albertel 2195: if (length($id) > 65
2196: && length(&escape($id)) > 200) {
2197: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2198: }
1.849 albertel 2199: return &escape($name.':'.$id);
2200: }
2201:
1.599 albertel 2202: sub devalidate_cache_new {
2203: my ($name,$id,$debug) = @_;
2204: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2205: $id=&make_key($name,$id);
1.599 albertel 2206: $memcache->delete($id);
2207: delete($remembered{$id});
2208: delete($accessed{$id});
2209: }
2210:
2211: sub is_cached_new {
2212: my ($name,$id,$debug) = @_;
1.849 albertel 2213: $id=&make_key($name,$id);
1.599 albertel 2214: if (exists($remembered{$id})) {
1.1133 ! foxr 2215: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2216: $accessed{$id}=[&gettimeofday()];
2217: $hits++;
2218: return ($remembered{$id},1);
2219: }
2220: my $value = $memcache->get($id);
2221: if (!(defined($value))) {
2222: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2223: return (undef,undef);
1.416 albertel 2224: }
1.599 albertel 2225: if ($value eq '__undef__') {
2226: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2227: $value=undef;
2228: }
2229: &make_room($id,$value,$debug);
2230: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2231: return ($value,1);
2232: }
2233:
2234: sub do_cache_new {
2235: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2236: $id=&make_key($name,$id);
1.599 albertel 2237: my $setvalue=$value;
2238: if (!defined($setvalue)) {
2239: $setvalue='__undef__';
2240: }
1.623 albertel 2241: if (!defined($time) ) {
2242: $time=600;
2243: }
1.599 albertel 2244: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2245: my $result = $memcache->set($id,$setvalue,$time);
2246: if (! $result) {
1.872 albertel 2247: &logthis("caching of id -> $id failed");
1.910 albertel 2248: $memcache->disconnect_all();
1.872 albertel 2249: }
1.600 albertel 2250: # need to make a copy of $value
1.919 albertel 2251: &make_room($id,$value,$debug);
1.599 albertel 2252: return $value;
2253: }
2254:
2255: sub make_room {
2256: my ($id,$value,$debug)=@_;
1.919 albertel 2257:
2258: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2259: : $value;
1.599 albertel 2260: if ($to_remember<0) { return; }
2261: $accessed{$id}=[&gettimeofday()];
2262: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2263: my $to_kick;
2264: my $max_time=0;
2265: foreach my $other (keys(%accessed)) {
2266: if (&tv_interval($accessed{$other}) > $max_time) {
2267: $to_kick=$other;
2268: $max_time=&tv_interval($accessed{$other});
2269: }
2270: }
2271: delete($remembered{$to_kick});
2272: delete($accessed{$to_kick});
2273: $kicks++;
2274: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2275: return;
2276: }
2277:
1.599 albertel 2278: sub purge_remembered {
1.604 albertel 2279: #&logthis("Tossing ".scalar(keys(%remembered)));
2280: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2281: undef(%remembered);
2282: undef(%accessed);
1.428 albertel 2283: }
1.70 www 2284: # ------------------------------------- Read an entry from a user's environment
2285:
2286: sub userenvironment {
2287: my ($udom,$unam,@what)=@_;
1.976 raeburn 2288: my $items;
2289: foreach my $item (@what) {
2290: $items.=&escape($item).'&';
2291: }
2292: $items=~s/\&$//;
1.70 www 2293: my %returnhash=();
1.1009 raeburn 2294: my $uhome = &homeserver($unam,$udom);
2295: unless ($uhome eq 'no_host') {
2296: my @answer=split(/\&/,
2297: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2298: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2299: return %returnhash;
2300: }
1.1009 raeburn 2301: my $i;
2302: for ($i=0;$i<=$#what;$i++) {
2303: $returnhash{$what[$i]}=&unescape($answer[$i]);
2304: }
1.70 www 2305: }
2306: return %returnhash;
1.1 albertel 2307: }
2308:
1.617 albertel 2309: # ---------------------------------------------------------- Get a studentphoto
2310: sub studentphoto {
2311: my ($udom,$unam,$ext) = @_;
2312: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2313: if (defined($env{'request.course.id'})) {
1.708 raeburn 2314: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2315: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2316: return(&retrievestudentphoto($udom,$unam,$ext));
2317: } else {
2318: my ($result,$perm_reqd)=
1.707 albertel 2319: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2320: if ($result eq 'ok') {
2321: if (!($perm_reqd eq 'yes')) {
2322: return(&retrievestudentphoto($udom,$unam,$ext));
2323: }
2324: }
2325: }
2326: }
2327: } else {
2328: my ($result,$perm_reqd) =
1.707 albertel 2329: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2330: if ($result eq 'ok') {
2331: if (!($perm_reqd eq 'yes')) {
2332: return(&retrievestudentphoto($udom,$unam,$ext));
2333: }
2334: }
2335: }
2336: return '/adm/lonKaputt/lonlogo_broken.gif';
2337: }
2338:
2339: sub retrievestudentphoto {
2340: my ($udom,$unam,$ext,$type) = @_;
2341: my $home=&Apache::lonnet::homeserver($unam,$udom);
2342: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2343: if ($ret eq 'ok') {
2344: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2345: if ($type eq 'thumbnail') {
2346: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2347: }
2348: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2349: return $tokenurl;
2350: } else {
2351: if ($type eq 'thumbnail') {
2352: return '/adm/lonKaputt/genericstudent_tn.gif';
2353: } else {
2354: return '/adm/lonKaputt/lonlogo_broken.gif';
2355: }
1.617 albertel 2356: }
2357: }
2358:
1.263 www 2359: # -------------------------------------------------------------------- New chat
2360:
2361: sub chatsend {
1.724 raeburn 2362: my ($newentry,$anon,$group)=@_;
1.620 albertel 2363: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2364: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2365: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2366: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2367: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2368: &escape($newentry)).':'.$group,$chome);
1.292 www 2369: }
2370:
2371: # ------------------------------------------ Find current version of a resource
2372:
2373: sub getversion {
2374: my $fname=&clutter(shift);
2375: unless ($fname=~/^\/res\//) { return -1; }
2376: return ¤tversion(&filelocation('',$fname));
2377: }
2378:
2379: sub currentversion {
2380: my $fname=shift;
2381: my $author=$fname;
2382: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2383: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2384: my $home=&homeserver($uname,$udom);
1.292 www 2385: if ($home eq 'no_host') {
2386: return -1;
2387: }
1.1112 www 2388: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2389: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2390: return -1;
2391: }
1.1112 www 2392: return $answer;
1.263 www 2393: }
2394:
1.1111 www 2395: #
2396: # Return special version number of resource if set by override, empty otherwise
2397: #
2398: sub usedversion {
2399: my $fname=shift;
2400: unless ($fname) { $fname=$env{'request.uri'}; }
2401: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2402: if ($urlversion) { return $urlversion; }
2403: return '';
2404: }
2405:
1.1 albertel 2406: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2407:
1.1 albertel 2408: sub subscribe {
2409: my $fname=shift;
1.761 raeburn 2410: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2411: $fname=~s/[\n\r]//g;
1.1 albertel 2412: my $author=$fname;
2413: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2414: my ($udom,$uname)=split(/\//,$author);
2415: my $home=homeserver($uname,$udom);
1.335 albertel 2416: if ($home eq 'no_host') {
2417: return 'not_found';
1.1 albertel 2418: }
2419: my $answer=reply("sub:$fname",$home);
1.64 www 2420: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2421: $answer.=' by '.$home;
2422: }
1.1 albertel 2423: return $answer;
2424: }
2425:
1.8 www 2426: # -------------------------------------------------------------- Replicate file
2427:
2428: sub repcopy {
2429: my $filename=shift;
1.23 www 2430: $filename=~s/\/+/\//g;
1.607 raeburn 2431: if ($filename=~m|^/home/httpd/html/adm/|) { return 'ok'; }
2432: if ($filename=~m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 2433: if ($filename=~m|^/home/httpd/html/userfiles/| or
1.609 banghart 2434: $filename=~m -^/*(uploaded|editupload)/-) {
1.538 albertel 2435: return &repcopy_userfile($filename);
2436: }
1.532 albertel 2437: $filename=~s/[\n\r]//g;
1.8 www 2438: my $transname="$filename.in.transfer";
1.828 www 2439: # FIXME: this should flock
1.607 raeburn 2440: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2441: my $remoteurl=subscribe($filename);
1.64 www 2442: if ($remoteurl =~ /^con_lost by/) {
2443: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2444: return 'unavailable';
1.8 www 2445: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2446: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2447: return 'not_found';
1.64 www 2448: } elsif ($remoteurl =~ /^rejected by/) {
2449: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2450: return 'forbidden';
1.20 www 2451: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2452: return 'ok';
1.8 www 2453: } else {
1.290 www 2454: my $author=$filename;
2455: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2456: my ($udom,$uname)=split(/\//,$author);
2457: my $home=homeserver($uname,$udom);
2458: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2459: my @parts=split(/\//,$filename);
2460: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
2461: if ($path ne "$perlvar{'lonDocRoot'}/res") {
2462: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2463: return 'bad_request';
1.8 www 2464: }
2465: my $count;
2466: for ($count=5;$count<$#parts;$count++) {
2467: $path.="/$parts[$count]";
2468: if ((-e $path)!=1) {
2469: mkdir($path,0777);
2470: }
2471: }
2472: my $ua=new LWP::UserAgent;
2473: my $request=new HTTP::Request('GET',"$remoteurl");
2474: my $response=$ua->request($request,$transname);
2475: if ($response->is_error()) {
2476: unlink($transname);
2477: my $message=$response->status_line;
1.672 albertel 2478: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2479: ." LWP get: $message: $filename</font>");
1.607 raeburn 2480: return 'unavailable';
1.8 www 2481: } else {
1.16 www 2482: if ($remoteurl!~/\.meta$/) {
2483: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2484: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2485: if ($mresponse->is_error()) {
2486: unlink($filename.'.meta');
2487: &logthis(
1.672 albertel 2488: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2489: }
2490: }
1.8 www 2491: rename($transname,$filename);
1.607 raeburn 2492: return 'ok';
1.8 www 2493: }
1.290 www 2494: }
1.8 www 2495: }
1.330 www 2496: }
2497:
2498: # ------------------------------------------------ Get server side include body
2499: sub ssi_body {
1.381 albertel 2500: my ($filelink,%form)=@_;
1.606 matthew 2501: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2502: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2503: }
1.953 www 2504: my $output='';
2505: my $response;
1.980 raeburn 2506: if ($filelink=~/^https?\:/) {
1.954 raeburn 2507: ($output,$response)=&externalssi($filelink);
1.953 www 2508: } else {
1.1004 droeschl 2509: $filelink .= $filelink=~/\?/ ? '&' : '?';
2510: $filelink .= 'inhibitmenu=yes';
1.953 www 2511: ($output,$response)=&ssi($filelink,%form);
2512: }
1.778 albertel 2513: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2514: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2515: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2516: if (wantarray) {
2517: return ($output, $response);
2518: } else {
2519: return $output;
2520: }
1.8 www 2521: }
2522:
1.15 www 2523: # --------------------------------------------------------- Server Side Include
2524:
1.782 albertel 2525: sub absolute_url {
2526: my ($host_name) = @_;
2527: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2528: if ($host_name eq '') {
2529: $host_name = $ENV{'SERVER_NAME'};
2530: }
2531: return $protocol.$host_name;
2532: }
2533:
1.942 foxr 2534: #
2535: # Server side include.
2536: # Parameters:
2537: # fn Possibly encrypted resource name/id.
2538: # form Hash that describes how the rendering should be done
2539: # and other things.
1.944 foxr 2540: # Returns:
1.950 raeburn 2541: # Scalar context: The content of the response.
2542: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2543: #
1.15 www 2544: sub ssi {
2545:
1.944 foxr 2546: my ($fn,%form)=@_;
1.15 www 2547: my $ua=new LWP::UserAgent;
1.23 www 2548: my $request;
1.711 albertel 2549:
2550: $form{'no_update_last_known'}=1;
1.895 albertel 2551: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2552: if (%form) {
1.782 albertel 2553: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2554: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2555: } else {
1.782 albertel 2556: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2557: }
2558:
1.15 www 2559: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
2560: my $response=$ua->request($request);
2561:
1.944 foxr 2562: if (wantarray) {
2563: return ($response->content, $response);
2564: } else {
2565: return $response->content;
1.942 foxr 2566: }
1.324 www 2567: }
2568:
2569: sub externalssi {
2570: my ($url)=@_;
2571: my $ua=new LWP::UserAgent;
2572: my $request=new HTTP::Request('GET',$url);
2573: my $response=$ua->request($request);
1.954 raeburn 2574: if (wantarray) {
2575: return ($response->content, $response);
2576: } else {
2577: return $response->content;
2578: }
1.15 www 2579: }
1.254 www 2580:
1.492 albertel 2581: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2582:
2583: sub allowuploaded {
2584: my ($srcurl,$url)=@_;
2585: $url=&clutter(&declutter($url));
2586: my $dir=$url;
2587: $dir=~s/\/[^\/]+$//;
2588: my %httpref=();
2589: my $httpurl=&hreflocation('',$url);
2590: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2591: &Apache::lonnet::appenv(\%httpref);
1.254 www 2592: }
1.477 raeburn 2593:
1.478 albertel 2594: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2595: # input: action, courseID, current domain, intended
1.637 raeburn 2596: # path to file, source of file, instruction to parse file for objects,
2597: # ref to hash for embedded objects,
2598: # ref to hash for codebase of java objects.
1.1095 raeburn 2599: # reference to scalar to accommodate mime type determined
2600: # from File::MMagic if $parser = parse.
1.637 raeburn 2601: #
1.485 raeburn 2602: # output: url to file (if action was uploaddoc),
2603: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2604: #
1.478 albertel 2605: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2606: # course.
1.477 raeburn 2607: #
1.478 albertel 2608: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2609: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2610: # course's home server.
1.477 raeburn 2611: #
1.478 albertel 2612: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2613: # be copied from $source (current location) to
2614: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2615: # and will then be copied to
2616: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2617: # course's home server.
1.485 raeburn 2618: #
1.481 raeburn 2619: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2620: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2621: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2622: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2623: # in course's home server.
1.637 raeburn 2624: #
1.477 raeburn 2625:
2626: sub process_coursefile {
1.1095 raeburn 2627: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2628: $mimetype)=@_;
1.477 raeburn 2629: my $fetchresult;
1.638 albertel 2630: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2631: if ($action eq 'propagate') {
1.638 albertel 2632: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2633: $home);
1.481 raeburn 2634: } else {
1.477 raeburn 2635: my $fpath = '';
2636: my $fname = $file;
1.478 albertel 2637: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2638: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2639: my $filepath = &build_filepath($fpath);
1.481 raeburn 2640: if ($action eq 'copy') {
2641: if ($source eq '') {
2642: $fetchresult = 'no source file';
2643: return $fetchresult;
2644: } else {
2645: my $destination = $filepath.'/'.$fname;
2646: rename($source,$destination);
2647: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2648: $home);
1.481 raeburn 2649: }
2650: } elsif ($action eq 'uploaddoc') {
2651: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2652: print $fh $env{'form.'.$source};
1.481 raeburn 2653: close($fh);
1.637 raeburn 2654: if ($parser eq 'parse') {
1.1024 raeburn 2655: my $mm = new File::MMagic;
1.1095 raeburn 2656: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2657: if ($type eq 'text/html') {
1.1024 raeburn 2658: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2659: unless ($parse_result eq 'ok') {
2660: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2661: }
1.637 raeburn 2662: }
1.1095 raeburn 2663: if (ref($mimetype)) {
2664: $$mimetype = $type;
2665: }
1.637 raeburn 2666: }
1.477 raeburn 2667: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2668: $home);
1.481 raeburn 2669: if ($fetchresult eq 'ok') {
2670: return '/uploaded/'.$fpath.'/'.$fname;
2671: } else {
2672: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2673: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2674: return '/adm/notfound.html';
2675: }
1.477 raeburn 2676: }
2677: }
1.485 raeburn 2678: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2679: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2680: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2681: }
2682: return $fetchresult;
2683: }
2684:
1.637 raeburn 2685: sub build_filepath {
2686: my ($fpath) = @_;
2687: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2688: unless ($fpath eq '') {
2689: my @parts=split('/',$fpath);
2690: foreach my $part (@parts) {
2691: $filepath.= '/'.$part;
2692: if ((-e $filepath)!=1) {
2693: mkdir($filepath,0777);
2694: }
2695: }
2696: }
2697: return $filepath;
2698: }
2699:
2700: sub store_edited_file {
1.638 albertel 2701: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2702: my $file = $primary_url;
2703: $file =~ s#^/uploaded/$docudom/$docuname/##;
2704: my $fpath = '';
2705: my $fname = $file;
2706: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2707: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2708: my $filepath = &build_filepath($fpath);
2709: open(my $fh,'>'.$filepath.'/'.$fname);
2710: print $fh $content;
2711: close($fh);
1.638 albertel 2712: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2713: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2714: $home);
1.637 raeburn 2715: if ($$fetchresult eq 'ok') {
2716: return '/uploaded/'.$fpath.'/'.$fname;
2717: } else {
1.638 albertel 2718: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2719: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2720: return '/adm/notfound.html';
2721: }
2722: }
2723:
1.531 albertel 2724: sub clean_filename {
1.831 albertel 2725: my ($fname,$args)=@_;
1.315 www 2726: # Replace Windows backslashes by forward slashes
1.257 www 2727: $fname=~s/\\/\//g;
1.831 albertel 2728: if (!$args->{'keep_path'}) {
2729: # Get rid of everything but the actual filename
2730: $fname=~s/^.*\/([^\/]+)$/$1/;
2731: }
1.315 www 2732: # Replace spaces by underscores
2733: $fname=~s/\s+/\_/g;
2734: # Replace all other weird characters by nothing
1.831 albertel 2735: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2736: # Replace all .\d. sequences with _\d. so they no longer look like version
2737: # numbers
2738: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2739: return $fname;
2740: }
1.1051 raeburn 2741: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2742: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2743: # image with the same aspect ratio as the original, but with dimensions which do
2744: # not exceed $resizewidth and $resizeheight.
2745:
1.984 neumanie 2746: sub resizeImage {
1.1051 raeburn 2747: my ($img_path,$resizewidth,$resizeheight) = @_;
2748: my $ima = Image::Magick->new;
2749: my $resized;
2750: if (-e $img_path) {
2751: $ima->Read($img_path);
2752: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2753: my $width = $ima->Get('width');
2754: my $height = $ima->Get('height');
2755: if ($width > $resizewidth) {
2756: my $factor = $width/$resizewidth;
2757: my $newheight = $height/$factor;
2758: $ima->Scale(width=>$resizewidth,height=>$newheight);
2759: $resized = 1;
2760: }
2761: }
2762: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2763: my $width = $ima->Get('width');
2764: my $height = $ima->Get('height');
2765: if ($height > $resizeheight) {
2766: my $factor = $height/$resizeheight;
2767: my $newwidth = $width/$factor;
2768: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2769: $resized = 1;
2770: }
2771: }
2772: if ($resized) {
2773: $ima->Write($img_path);
2774: }
2775: }
2776: return;
1.977 amueller 2777: }
2778:
1.608 albertel 2779: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2780: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2781: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2782: # $context - possible values: coursedoc, existingfile, overwrite,
2783: # canceloverwrite, or ''.
2784: # if 'coursedoc': upload to the current course
2785: # if 'existingfile': write file to tmp/overwrites directory
2786: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2787: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2788: # $subdir - directory in userfile to store the file into
1.858 raeburn 2789: # $parser - instruction to parse file for objects ($parser = parse)
2790: # $allfiles - reference to hash for embedded objects
2791: # $codebase - reference to hash for codebase of java objects
2792: # $desuname - username for permanent storage of uploaded file
2793: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2794: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2795: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2796: # $resizewidth - width (pixels) to which to resize uploaded image
2797: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2798: # $mimetype - reference to scalar to accommodate mime type determined
2799: # from File::MMagic if $parser = parse.
1.858 raeburn 2800: #
1.686 albertel 2801: # output: url of file in userspace, or error: <message>
2802: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2803:
1.531 albertel 2804: sub userfileupload {
1.1090 raeburn 2805: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2806: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2807: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2808: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2809: $fname=&clean_filename($fname);
1.1090 raeburn 2810: # See if there is anything left
1.257 www 2811: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2812: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2813: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2814: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2815: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2816: my $now = time;
1.1090 raeburn 2817: my $filepath;
1.1095 raeburn 2818: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2819: $filepath = 'tmp/helprequests/'.$now;
2820: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2821: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2822: '_'.$env{'user.domain'}.'/pending';
2823: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2824: my ($docuname,$docudom);
2825: if ($destudom) {
2826: $docudom = $destudom;
2827: } else {
2828: $docudom = $env{'user.domain'};
2829: }
2830: if ($destuname) {
2831: $docuname = $destuname;
2832: } else {
2833: $docuname = $env{'user.name'};
2834: }
2835: if (exists($env{'form.group'})) {
2836: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2837: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2838: }
2839: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2840: if ($context eq 'canceloverwrite') {
2841: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2842: if (-e $tempfile) {
2843: my @info = stat($tempfile);
2844: if ($info[9] eq $env{'form.timestamp'}) {
2845: unlink($tempfile);
2846: }
2847: }
2848: return;
1.523 raeburn 2849: }
2850: }
1.1090 raeburn 2851: # Create the directory if not present
1.741 raeburn 2852: my @parts=split(/\//,$filepath);
2853: my $fullpath = $perlvar{'lonDaemons'};
2854: for (my $i=0;$i<@parts;$i++) {
2855: $fullpath .= '/'.$parts[$i];
2856: if ((-e $fullpath)!=1) {
2857: mkdir($fullpath,0777);
2858: }
2859: }
2860: open(my $fh,'>'.$fullpath.'/'.$fname);
2861: print $fh $env{'form.'.$formname};
2862: close($fh);
1.1090 raeburn 2863: if ($context eq 'existingfile') {
2864: my @info = stat($fullpath.'/'.$fname);
2865: return ($fullpath.'/'.$fname,$info[9]);
2866: } else {
2867: return $fullpath.'/'.$fname;
2868: }
1.523 raeburn 2869: }
1.995 raeburn 2870: if ($subdir eq 'scantron') {
2871: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2872: } else {
1.995 raeburn 2873: $fname="$subdir/$fname";
2874: }
1.1090 raeburn 2875: if ($context eq 'coursedoc') {
1.638 albertel 2876: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2877: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2878: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2879: return &finishuserfileupload($docuname,$docudom,
2880: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2881: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2882: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2883: } else {
1.620 albertel 2884: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2885: return &process_coursefile('uploaddoc',$docuname,$docudom,
2886: $fname,$formname,$parser,
1.1095 raeburn 2887: $allfiles,$codebase,$mimetype);
1.481 raeburn 2888: }
1.719 banghart 2889: } elsif (defined($destuname)) {
2890: my $docuname=$destuname;
2891: my $docudom=$destudom;
1.860 raeburn 2892: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2893: $parser,$allfiles,$codebase,
1.1051 raeburn 2894: $thumbwidth,$thumbheight,
1.1095 raeburn 2895: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2896: } else {
1.638 albertel 2897: my $docuname=$env{'user.name'};
2898: my $docudom=$env{'user.domain'};
1.714 raeburn 2899: if (exists($env{'form.group'})) {
2900: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2901: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2902: }
1.860 raeburn 2903: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2904: $parser,$allfiles,$codebase,
1.1051 raeburn 2905: $thumbwidth,$thumbheight,
1.1095 raeburn 2906: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2907: }
1.271 www 2908: }
2909:
2910: sub finishuserfileupload {
1.860 raeburn 2911: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2912: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2913: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2914: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2915:
1.860 raeburn 2916: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2917: $file=$fname;
2918: if ($fname=~m|/|) {
2919: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2920: $path.=$fnamepath.'/';
2921: }
1.259 www 2922: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2923: my $count;
2924: for ($count=4;$count<=$#parts;$count++) {
2925: $filepath.="/$parts[$count]";
2926: if ((-e $filepath)!=1) {
2927: mkdir($filepath,0777);
2928: }
2929: }
1.984 neumanie 2930:
1.258 www 2931: # Save the file
2932: {
1.701 albertel 2933: if (!open(FH,'>'.$filepath.'/'.$file)) {
2934: &logthis('Failed to create '.$filepath.'/'.$file);
2935: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2936: return '/adm/notfound.html';
2937: }
1.1090 raeburn 2938: if ($context eq 'overwrite') {
1.1117 foxr 2939: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2940: my $target = $filepath.'/'.$file;
2941: if (-e $source) {
2942: my @info = stat($source);
2943: if ($info[9] eq $env{'form.timestamp'}) {
2944: unless (&File::Copy::move($source,$target)) {
2945: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2946: return "Moving from $source failed";
2947: }
2948: } else {
2949: return "Temporary file: $source had unexpected date/time for last modification";
2950: }
2951: } else {
2952: return "Temporary file: $source missing";
2953: }
2954: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2955: &logthis('Failed to write to '.$filepath.'/'.$file);
2956: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2957: return '/adm/notfound.html';
2958: }
1.570 albertel 2959: close(FH);
1.1051 raeburn 2960: if ($resizewidth && $resizeheight) {
2961: my $mm = new File::MMagic;
2962: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2963: if ($mime_type =~ m{^image/}) {
2964: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2965: }
1.977 amueller 2966: }
1.258 www 2967: }
1.637 raeburn 2968: if ($parser eq 'parse') {
1.1024 raeburn 2969: my $mm = new File::MMagic;
1.1095 raeburn 2970: my $type = $mm->checktype_filename($filepath.'/'.$file);
2971: if ($type eq 'text/html') {
1.1024 raeburn 2972: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
2973: $allfiles,$codebase);
2974: unless ($parse_result eq 'ok') {
2975: &logthis('Failed to parse '.$filepath.$file.
2976: ' for embedded media: '.$parse_result);
2977: }
1.637 raeburn 2978: }
1.1095 raeburn 2979: if (ref($mimetype)) {
2980: $$mimetype = $type;
2981: }
1.637 raeburn 2982: }
1.860 raeburn 2983: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
2984: my $input = $filepath.'/'.$file;
2985: my $output = $filepath.'/'.'tn-'.$file;
2986: my $thumbsize = $thumbwidth.'x'.$thumbheight;
2987: system("convert -sample $thumbsize $input $output");
2988: if (-e $filepath.'/'.'tn-'.$file) {
2989: $fetchthumb = 1;
2990: }
2991: }
1.858 raeburn 2992:
1.259 www 2993: # Notify homeserver to grep it
2994: #
1.984 neumanie 2995: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 2996: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 2997: if ($fetchresult eq 'ok') {
1.860 raeburn 2998: if ($fetchthumb) {
2999: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3000: if ($thumbresult ne 'ok') {
3001: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3002: $docuhome.': '.$thumbresult);
3003: }
3004: }
1.259 www 3005: #
1.258 www 3006: # Return the URL to it
1.494 albertel 3007: return '/uploaded/'.$path.$file;
1.263 www 3008: } else {
1.494 albertel 3009: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3010: ': '.$fetchresult);
1.263 www 3011: return '/adm/notfound.html';
1.858 raeburn 3012: }
1.493 albertel 3013: }
3014:
1.637 raeburn 3015: sub extract_embedded_items {
1.961 raeburn 3016: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3017: my @state = ();
3018: my %javafiles = (
3019: codebase => '',
3020: code => '',
3021: archive => ''
3022: );
3023: my %mediafiles = (
3024: src => '',
3025: movie => '',
3026: );
1.648 raeburn 3027: my $p;
3028: if ($content) {
3029: $p = HTML::LCParser->new($content);
3030: } else {
1.961 raeburn 3031: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3032: }
1.641 albertel 3033: while (my $t=$p->get_token()) {
1.640 albertel 3034: if ($t->[0] eq 'S') {
3035: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3036: push(@state, $tagname);
1.648 raeburn 3037: if (lc($tagname) eq 'allow') {
3038: &add_filetype($allfiles,$attr->{'src'},'src');
3039: }
1.640 albertel 3040: if (lc($tagname) eq 'img') {
3041: &add_filetype($allfiles,$attr->{'src'},'src');
3042: }
1.886 albertel 3043: if (lc($tagname) eq 'a') {
3044: &add_filetype($allfiles,$attr->{'href'},'href');
3045: }
1.645 raeburn 3046: if (lc($tagname) eq 'script') {
3047: if ($attr->{'archive'} =~ /\.jar$/i) {
3048: &add_filetype($allfiles,$attr->{'archive'},'archive');
3049: } else {
3050: &add_filetype($allfiles,$attr->{'src'},'src');
3051: }
3052: }
3053: if (lc($tagname) eq 'link') {
3054: if (lc($attr->{'rel'}) eq 'stylesheet') {
3055: &add_filetype($allfiles,$attr->{'href'},'href');
3056: }
3057: }
1.640 albertel 3058: if (lc($tagname) eq 'object' ||
3059: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3060: foreach my $item (keys(%javafiles)) {
3061: $javafiles{$item} = '';
3062: }
3063: }
3064: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3065: my $name = lc($attr->{'name'});
3066: foreach my $item (keys(%javafiles)) {
3067: if ($name eq $item) {
3068: $javafiles{$item} = $attr->{'value'};
3069: last;
3070: }
3071: }
3072: foreach my $item (keys(%mediafiles)) {
3073: if ($name eq $item) {
3074: &add_filetype($allfiles, $attr->{'value'}, 'value');
3075: last;
3076: }
3077: }
3078: }
3079: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3080: foreach my $item (keys(%javafiles)) {
3081: if ($attr->{$item}) {
3082: $javafiles{$item} = $attr->{$item};
3083: last;
3084: }
3085: }
3086: foreach my $item (keys(%mediafiles)) {
3087: if ($attr->{$item}) {
3088: &add_filetype($allfiles,$attr->{$item},$item);
3089: last;
3090: }
3091: }
3092: }
3093: } elsif ($t->[0] eq 'E') {
3094: my ($tagname) = ($t->[1]);
3095: if ($javafiles{'codebase'} ne '') {
3096: $javafiles{'codebase'} .= '/';
3097: }
3098: if (lc($tagname) eq 'applet' ||
3099: lc($tagname) eq 'object' ||
3100: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3101: ) {
3102: foreach my $item (keys(%javafiles)) {
3103: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3104: my $file=$javafiles{'codebase'}.$javafiles{$item};
3105: &add_filetype($allfiles,$file,$item);
3106: }
3107: }
3108: }
3109: pop @state;
3110: }
3111: }
1.637 raeburn 3112: return 'ok';
3113: }
3114:
1.639 albertel 3115: sub add_filetype {
3116: my ($allfiles,$file,$type)=@_;
3117: if (exists($allfiles->{$file})) {
3118: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3119: push(@{$allfiles->{$file}}, &escape($type));
3120: }
3121: } else {
3122: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3123: }
3124: }
3125:
1.493 albertel 3126: sub removeuploadedurl {
1.984 neumanie 3127: my ($url)=@_;
3128: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3129: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3130: }
3131:
3132: sub removeuserfile {
3133: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3134: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3135: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3136: if ($result eq 'ok') {
1.798 raeburn 3137: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3138: my $metafile = $fname.'.meta';
3139: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3140: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3141: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3142: my $sqlresult =
1.823 albertel 3143: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3144: 'portfolio_metadata',$group,
3145: 'delete');
1.798 raeburn 3146: }
3147: }
3148: return $result;
1.257 www 3149: }
1.15 www 3150:
1.530 albertel 3151: sub mkdiruserfile {
3152: my ($docuname,$docudom,$dir)=@_;
3153: my $home=&homeserver($docuname,$docudom);
3154: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3155: }
3156:
1.531 albertel 3157: sub renameuserfile {
3158: my ($docuname,$docudom,$old,$new)=@_;
3159: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3160: my $result = &reply("renameuserfile:$docudom:$docuname:".
3161: &escape("$old").':'.&escape("$new"),$home);
3162: if ($result eq 'ok') {
3163: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3164: my $oldmeta = $old.'.meta';
3165: my $newmeta = $new.'.meta';
3166: my $metaresult =
3167: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3168: my $url = "/uploaded/$docudom/$docuname/$old";
3169: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3170: my $sqlresult =
1.823 albertel 3171: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3172: 'portfolio_metadata',$group,
3173: 'delete');
1.798 raeburn 3174: }
3175: }
3176: return $result;
1.531 albertel 3177: }
3178:
1.14 www 3179: # ------------------------------------------------------------------------- Log
3180:
3181: sub log {
3182: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3183: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3184: }
3185:
3186: # ------------------------------------------------------------------ Course Log
1.352 www 3187: #
3188: # This routine flushes several buffers of non-mission-critical nature
3189: #
1.157 www 3190:
3191: sub flushcourselogs {
1.352 www 3192: &logthis('Flushing log buffers');
3193: #
3194: # course logs
3195: # This is a log of all transactions in a course, which can be used
3196: # for data mining purposes
3197: #
3198: # It also collects the courseid database, which lists last transaction
3199: # times and course titles for all courseids
3200: #
3201: my %courseidbuffer=();
1.921 raeburn 3202: foreach my $crsid (keys(%courselogs)) {
1.352 www 3203: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3204: &escape($courselogs{$crsid}),
3205: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3206: delete $courselogs{$crsid};
3207: } else {
3208: &logthis('Failed to flush log buffer for '.$crsid);
3209: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3210: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3211: " exceeded maximum size, deleting.</font>");
3212: delete $courselogs{$crsid};
3213: }
1.352 www 3214: }
1.920 raeburn 3215: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3216: 'description' => $coursedescrbuf{$crsid},
3217: 'inst_code' => $courseinstcodebuf{$crsid},
3218: 'type' => $coursetypebuf{$crsid},
3219: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3220: };
1.191 harris41 3221: }
1.352 www 3222: #
3223: # Write course id database (reverse lookup) to homeserver of courses
3224: # Is used in pickcourse
3225: #
1.840 albertel 3226: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3227: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3228: $courseidbuffer{$crs_home},
3229: $crs_home,'timeonly');
1.352 www 3230: }
3231: #
3232: # File accesses
3233: # Writes to the dynamic metadata of resources to get hit counts, etc.
3234: #
1.449 matthew 3235: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3236: if ($entry =~ /___count$/) {
3237: my ($dom,$name);
1.807 albertel 3238: ($dom,$name,undef)=
1.811 albertel 3239: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3240: if (! defined($dom) || $dom eq '' ||
3241: ! defined($name) || $name eq '') {
1.620 albertel 3242: my $cid = $env{'request.course.id'};
3243: $dom = $env{'request.'.$cid.'.domain'};
3244: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3245: }
1.450 matthew 3246: my $value = $accesshash{$entry};
3247: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3248: my %temphash=($url => $value);
1.449 matthew 3249: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3250: if ($result eq 'ok') {
3251: delete $accesshash{$entry};
3252: } elsif ($result eq 'unknown_cmd') {
3253: # Target server has old code running on it.
1.450 matthew 3254: my %temphash=($entry => $value);
1.449 matthew 3255: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3256: delete $accesshash{$entry};
3257: }
3258: }
3259: } else {
1.811 albertel 3260: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.450 matthew 3261: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3262: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3263: delete $accesshash{$entry};
3264: }
1.185 www 3265: }
1.191 harris41 3266: }
1.352 www 3267: #
3268: # Roles
3269: # Reverse lookup of user roles for course faculty/staff and co-authorship
3270: #
1.800 albertel 3271: foreach my $entry (keys(%userrolehash)) {
1.351 www 3272: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3273: split(/\:/,$entry);
3274: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3275: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3276: $rudom,$runame) eq 'ok') {
3277: delete $userrolehash{$entry};
3278: }
3279: }
1.662 raeburn 3280: #
3281: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3282: #
3283: my %domrolebuffer = ();
1.1000 raeburn 3284: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3285: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3286: if ($domrolebuffer{$rudom}) {
3287: $domrolebuffer{$rudom}.='&'.&escape($entry).
3288: '='.&escape($domainrolehash{$entry});
3289: } else {
3290: $domrolebuffer{$rudom}.=&escape($entry).
3291: '='.&escape($domainrolehash{$entry});
3292: }
3293: delete $domainrolehash{$entry};
3294: }
3295: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3296: my %servers = &get_servers($dom,'library');
3297: foreach my $tryserver (keys(%servers)) {
3298: unless (&reply('domroleput:'.$dom.':'.
3299: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3300: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3301: }
1.662 raeburn 3302: }
3303: }
1.186 www 3304: $dumpcount++;
1.157 www 3305: }
3306:
3307: sub courselog {
3308: my $what=shift;
1.158 www 3309: $what=time.':'.$what;
1.620 albertel 3310: unless ($env{'request.course.id'}) { return ''; }
3311: $coursedombuf{$env{'request.course.id'}}=
3312: $env{'course.'.$env{'request.course.id'}.'.domain'};
3313: $coursenumbuf{$env{'request.course.id'}}=
3314: $env{'course.'.$env{'request.course.id'}.'.num'};
3315: $coursehombuf{$env{'request.course.id'}}=
3316: $env{'course.'.$env{'request.course.id'}.'.home'};
3317: $coursedescrbuf{$env{'request.course.id'}}=
3318: $env{'course.'.$env{'request.course.id'}.'.description'};
3319: $courseinstcodebuf{$env{'request.course.id'}}=
3320: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3321: $courseownerbuf{$env{'request.course.id'}}=
3322: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3323: $coursetypebuf{$env{'request.course.id'}}=
3324: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3325: if (defined $courselogs{$env{'request.course.id'}}) {
3326: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3327: } else {
1.620 albertel 3328: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3329: }
1.620 albertel 3330: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3331: &flushcourselogs();
3332: }
1.158 www 3333: }
3334:
3335: sub courseacclog {
3336: my $fnsymb=shift;
1.620 albertel 3337: unless ($env{'request.course.id'}) { return ''; }
3338: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.657 albertel 3339: if ($fnsymb=~/(problem|exam|quiz|assess|survey|form|task|page)$/) {
1.187 www 3340: $what.=':POST';
1.583 matthew 3341: # FIXME: Probably ought to escape things....
1.800 albertel 3342: foreach my $key (keys(%env)) {
3343: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3344: my $formitem = $1;
3345: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3346: $what.=':'.$formitem.'='.$env{$key};
3347: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3348: $what.=':'.$formitem.'='.$env{$key};
3349: }
1.158 www 3350: }
1.191 harris41 3351: }
1.583 matthew 3352: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3353: # FIXME: We should not be depending on a form parameter that someone
3354: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3355: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3356: $what.= ':POST';
3357: # FIXME: Probably ought to escape things....
3358: foreach my $element ('courseexp','crsfulltext','crsrelated',
3359: 'crsdiscuss') {
1.620 albertel 3360: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3361: }
3362: }
1.158 www 3363: }
3364: &courselog($what);
1.149 www 3365: }
3366:
1.185 www 3367: sub countacc {
3368: my $url=&declutter(shift);
1.458 matthew 3369: return if (! defined($url) || $url eq '');
1.620 albertel 3370: unless ($env{'request.course.id'}) { return ''; }
3371: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.281 www 3372: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3373: $accesshash{$key}++;
1.185 www 3374: }
1.349 www 3375:
1.361 www 3376: sub linklog {
3377: my ($from,$to)=@_;
3378: $from=&declutter($from);
3379: $to=&declutter($to);
3380: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3381: $accesshash{$to.'___'.$from.'___goto'}=1;
3382: }
3383:
1.349 www 3384: sub userrolelog {
3385: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.661 raeburn 3386: if (($trole=~/^ca/) || ($trole=~/^aa/) ||
1.662 raeburn 3387: ($trole=~/^in/) || ($trole=~/^cc/) ||
1.661 raeburn 3388: ($trole=~/^ep/) || ($trole=~/^cr/) ||
1.1041 raeburn 3389: ($trole=~/^ta/) || ($trole=~/^co/)) {
1.350 www 3390: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3391: $userrolehash
3392: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3393: =$tend.':'.$tstart;
1.662 raeburn 3394: }
1.898 albertel 3395: if (($env{'request.role'} =~ /dc\./) &&
3396: (($trole=~/^au/) || ($trole=~/^in/) ||
3397: ($trole=~/^cc/) || ($trole=~/^ep/) ||
1.1041 raeburn 3398: ($trole=~/^cr/) || ($trole=~/^ta/) ||
3399: ($trole=~/^co/))) {
1.898 albertel 3400: $userrolehash
3401: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3402: =$tend.':'.$tstart;
3403: }
1.662 raeburn 3404: if (($trole=~/^dc/) || ($trole=~/^ad/) ||
3405: ($trole=~/^li/) || ($trole=~/^li/) ||
3406: ($trole=~/^au/) || ($trole=~/^dg/) ||
3407: ($trole=~/^sc/)) {
3408: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3409: $domainrolehash
3410: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3411: = $tend.':'.$tstart;
3412: }
1.351 www 3413: }
3414:
1.957 raeburn 3415: sub courserolelog {
3416: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3417: if (($trole eq 'cc') || ($trole eq 'in') ||
3418: ($trole eq 'ep') || ($trole eq 'ad') ||
3419: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3420: ($trole=~/^cr/) || ($trole eq 'gr') ||
3421: ($trole eq 'co')) {
1.957 raeburn 3422: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3423: my $cdom = $1;
3424: my $cnum = $2;
3425: my $sec = $3;
3426: my $namespace = 'rolelog';
3427: my %storehash = (
3428: role => $trole,
3429: start => $tstart,
3430: end => $tend,
3431: selfenroll => $selfenroll,
3432: context => $context,
3433: );
3434: if ($trole eq 'gr') {
3435: $namespace = 'groupslog';
3436: $storehash{'group'} = $sec;
3437: } else {
3438: $storehash{'section'} = $sec;
3439: }
3440: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3441: if (($trole ne 'st') || ($sec ne '')) {
3442: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3443: }
1.957 raeburn 3444: }
3445: }
3446: return;
3447: }
3448:
1.351 www 3449: sub get_course_adv_roles {
1.948 raeburn 3450: my ($cid,$codes) = @_;
1.620 albertel 3451: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3452: my %coursehash=&coursedescription($cid);
1.988 raeburn 3453: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3454: my %nothide=();
1.800 albertel 3455: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3456: if ($user !~ /:/) {
3457: $nothide{join(':',split(/[\@]/,$user))}=1;
3458: } else {
3459: $nothide{$user}=1;
3460: }
1.470 www 3461: }
1.351 www 3462: my %returnhash=();
3463: my %dumphash=
3464: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3465: my $now=time;
1.997 raeburn 3466: my %privileged;
1.1000 raeburn 3467: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3468: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3469: if (($tstart) && ($tstart<0)) { next; }
3470: if (($tend) && ($tend<$now)) { next; }
3471: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3472: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3473: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3474: unless (ref($privileged{$domain}) eq 'HASH') {
3475: my %dompersonnel =
1.998 raeburn 3476: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3477: $privileged{$domain} = {};
3478: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3479: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3480: foreach my $user (keys(%{$dompersonnel{$server}})) {
3481: my ($trole,$uname,$udom) = split(/:/,$user);
3482: $privileged{$udom}{$uname} = 1;
3483: }
3484: }
3485: }
3486: }
3487: if ((exists($privileged{$domain}{$username})) &&
3488: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3489: if ($role eq 'cr') { next; }
1.948 raeburn 3490: if ($codes) {
3491: if ($section) { $role .= ':'.$section; }
3492: if ($returnhash{$role}) {
3493: $returnhash{$role}.=','.$username.':'.$domain;
3494: } else {
3495: $returnhash{$role}=$username.':'.$domain;
3496: }
1.351 www 3497: } else {
1.988 raeburn 3498: my $key=&plaintext($role,$crstype);
1.973 bisitz 3499: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3500: if ($returnhash{$key}) {
3501: $returnhash{$key}.=','.$username.':'.$domain;
3502: } else {
3503: $returnhash{$key}=$username.':'.$domain;
3504: }
1.351 www 3505: }
1.948 raeburn 3506: }
1.400 www 3507: return %returnhash;
3508: }
3509:
3510: sub get_my_roles {
1.937 raeburn 3511: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3512: unless (defined($uname)) { $uname=$env{'user.name'}; }
3513: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3514: my (%dumphash,%nothide);
1.1086 raeburn 3515: if ($context eq 'userroles') {
3516: my $extra = &freeze_escape({'skipcheck' => 1});
3517: %dumphash = &dump('roles',$udom,$uname,'.',undef,$extra);
1.858 raeburn 3518: } else {
3519: %dumphash=
1.400 www 3520: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3521: if ($hidepriv) {
3522: my %coursehash=&coursedescription($udom.'_'.$uname);
3523: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3524: if ($user !~ /:/) {
3525: $nothide{join(':',split(/[\@]/,$user))} = 1;
3526: } else {
3527: $nothide{$user} = 1;
3528: }
3529: }
3530: }
1.858 raeburn 3531: }
1.400 www 3532: my %returnhash=();
3533: my $now=time;
1.999 raeburn 3534: my %privileged;
1.800 albertel 3535: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3536: my ($role,$tend,$tstart);
3537: if ($context eq 'userroles') {
3538: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3539: } else {
3540: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3541: }
1.400 www 3542: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3543: my $status = 'active';
1.939 raeburn 3544: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3545: $status = 'previous';
3546: }
3547: if (($tstart) && ($now<$tstart)) {
3548: $status = 'future';
3549: }
3550: if (ref($types) eq 'ARRAY') {
3551: if (!grep(/^\Q$status\E$/,@{$types})) {
3552: next;
3553: }
3554: } else {
3555: if ($status ne 'active') {
3556: next;
3557: }
3558: }
1.867 raeburn 3559: my ($rolecode,$username,$domain,$section,$area);
3560: if ($context eq 'userroles') {
3561: ($area,$rolecode) = split(/_/,$entry);
3562: (undef,$domain,$username,$section) = split(/\//,$area);
3563: } else {
3564: ($role,$username,$domain,$section) = split(/\:/,$entry);
3565: }
1.832 raeburn 3566: if (ref($roledoms) eq 'ARRAY') {
3567: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3568: next;
3569: }
3570: }
3571: if (ref($roles) eq 'ARRAY') {
3572: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3573: if ($role =~ /^cr\//) {
3574: if (!grep(/^cr$/,@{$roles})) {
3575: next;
3576: }
1.1104 raeburn 3577: } elsif ($role =~ /^gr\//) {
3578: if (!grep(/^gr$/,@{$roles})) {
3579: next;
3580: }
1.922 raeburn 3581: } else {
3582: next;
3583: }
1.832 raeburn 3584: }
1.867 raeburn 3585: }
1.937 raeburn 3586: if ($hidepriv) {
1.999 raeburn 3587: if ($context eq 'userroles') {
3588: if ((&privileged($username,$domain)) &&
3589: (!$nothide{$username.':'.$domain})) {
3590: next;
3591: }
3592: } else {
3593: unless (ref($privileged{$domain}) eq 'HASH') {
3594: my %dompersonnel =
3595: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3596: $privileged{$domain} = {};
3597: if (keys(%dompersonnel)) {
3598: foreach my $server (keys(%dompersonnel)) {
3599: if (ref($dompersonnel{$server}) eq 'HASH') {
3600: foreach my $user (keys(%{$dompersonnel{$server}})) {
3601: my ($trole,$uname,$udom) = split(/:/,$user);
3602: $privileged{$udom}{$uname} = $trole;
3603: }
3604: }
3605: }
3606: }
3607: }
3608: if (exists($privileged{$domain}{$username})) {
3609: if (!$nothide{$username.':'.$domain}) {
3610: next;
3611: }
3612: }
1.937 raeburn 3613: }
3614: }
1.933 raeburn 3615: if ($withsec) {
3616: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3617: $tstart.':'.$tend;
3618: } else {
3619: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3620: }
1.832 raeburn 3621: }
1.373 www 3622: return %returnhash;
1.399 www 3623: }
3624:
3625: # ----------------------------------------------------- Frontpage Announcements
3626: #
3627: #
3628:
3629: sub postannounce {
3630: my ($server,$text)=@_;
1.844 albertel 3631: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3632: unless ($text=~/\w/) { $text=''; }
3633: return &reply('setannounce:'.&escape($text),$server);
3634: }
3635:
3636: sub getannounce {
1.448 albertel 3637:
3638: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3639: my $announcement='';
1.800 albertel 3640: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3641: close($fh);
1.399 www 3642: if ($announcement=~/\w/) {
3643: return
3644: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3645: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3646: } else {
3647: return '';
3648: }
3649: } else {
3650: return '';
3651: }
1.351 www 3652: }
1.353 www 3653:
3654: # ---------------------------------------------------------- Course ID routines
3655: # Deal with domain's nohist_courseid.db files
3656: #
3657:
3658: sub courseidput {
1.921 raeburn 3659: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3660: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3661: my $outcome;
3662: if ($caller eq 'timeonly') {
3663: my $cids = '';
3664: foreach my $item (keys(%$storehash)) {
3665: $cids.=&escape($item).'&';
3666: }
3667: $cids=~s/\&$//;
3668: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3669: $coursehome);
3670: } else {
3671: my $items = '';
3672: foreach my $item (keys(%$storehash)) {
3673: $items.= &escape($item).'='.
3674: &freeze_escape($$storehash{$item}).'&';
3675: }
3676: $items=~s/\&$//;
3677: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3678: $coursehome);
1.918 raeburn 3679: }
3680: if ($outcome eq 'unknown_cmd') {
3681: my $what;
3682: foreach my $cid (keys(%$storehash)) {
3683: $what .= &escape($cid).'=';
1.921 raeburn 3684: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3685: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3686: }
3687: $what =~ s/\:$/&/;
3688: }
3689: $what =~ s/\&$//;
3690: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3691: } else {
3692: return $outcome;
3693: }
1.353 www 3694: }
3695:
3696: sub courseiddump {
1.921 raeburn 3697: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3698: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3699: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3700: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3701: my $as_hash = 1;
3702: my %returnhash;
3703: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3704: my %libserv = &all_library();
3705: foreach my $tryserver (keys(%libserv)) {
3706: if ( ( $hostidflag == 1
3707: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3708: || (!defined($hostidflag)) ) {
3709:
1.918 raeburn 3710: if (($domfilter eq '') ||
3711: (&host_domain($tryserver) eq $domfilter)) {
3712: my $rep =
3713: &reply('courseiddump:'.&host_domain($tryserver).':'.
3714: $sincefilter.':'.&escape($descfilter).':'.
3715: &escape($instcodefilter).':'.&escape($ownerfilter).
3716: ':'.&escape($coursefilter).':'.&escape($typefilter).
1.947 raeburn 3717: ':'.&escape($regexp_ok).':'.$as_hash.':'.
1.962 raeburn 3718: &escape($selfenrollonly).':'.&escape($catfilter).':'.
1.1008 raeburn 3719: $showhidden.':'.$caller.':'.&escape($cloner).':'.
1.1029 raeburn 3720: &escape($cc_clone).':'.$cloneonly.':'.
3721: &escape($createdbefore).':'.&escape($createdafter).':'.
1.1071 raeburn 3722: &escape($creationcontext).':'.$domcloner,
3723: $tryserver);
1.918 raeburn 3724: my @pairs=split(/\&/,$rep);
3725: foreach my $item (@pairs) {
3726: my ($key,$value)=split(/\=/,$item,2);
3727: $key = &unescape($key);
3728: next if ($key =~ /^error: 2 /);
3729: my $result = &thaw_unescape($value);
3730: if (ref($result) eq 'HASH') {
3731: $returnhash{$key}=$result;
3732: } else {
1.921 raeburn 3733: my @responses = split(/:/,$value);
3734: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3735: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3736: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3737: }
1.1008 raeburn 3738: }
1.353 www 3739: }
3740: }
3741: }
3742: }
3743: return %returnhash;
3744: }
3745:
1.1055 raeburn 3746: sub courselastaccess {
3747: my ($cdom,$cnum,$hostidref) = @_;
3748: my %returnhash;
3749: if ($cdom && $cnum) {
3750: my $chome = &homeserver($cnum,$cdom);
3751: if ($chome ne 'no_host') {
3752: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3753: &extract_lastaccess(\%returnhash,$rep);
3754: }
3755: } else {
3756: if (!$cdom) { $cdom=''; }
3757: my %libserv = &all_library();
3758: foreach my $tryserver (keys(%libserv)) {
3759: if (ref($hostidref) eq 'ARRAY') {
3760: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3761: }
3762: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3763: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3764: &extract_lastaccess(\%returnhash,$rep);
3765: }
3766: }
3767: }
3768: return %returnhash;
3769: }
3770:
3771: sub extract_lastaccess {
3772: my ($returnhash,$rep) = @_;
3773: if (ref($returnhash) eq 'HASH') {
3774: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3775: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3776: $rep eq '') {
3777: my @pairs=split(/\&/,$rep);
3778: foreach my $item (@pairs) {
3779: my ($key,$value)=split(/\=/,$item,2);
3780: $key = &unescape($key);
3781: next if ($key =~ /^error: 2 /);
3782: $returnhash->{$key} = &thaw_unescape($value);
3783: }
3784: }
3785: }
3786: return;
3787: }
3788:
1.658 raeburn 3789: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3790:
3791: sub dcmailput {
1.685 raeburn 3792: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3793: my $status = &Apache::lonnet::critical(
1.740 www 3794: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3795: &escape($message),$server);
1.662 raeburn 3796: return $status;
3797: }
3798:
1.658 raeburn 3799: sub dcmaildump {
3800: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3801: my %returnhash=();
1.846 albertel 3802:
3803: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3804: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3805: &escape($enddate).':';
3806: my @esc_senders=map { &escape($_)} @$senders;
3807: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3808: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3809: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3810: if (($key) && ($value)) {
3811: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3812: }
3813: }
3814: }
3815: return %returnhash;
3816: }
1.662 raeburn 3817: # ---------------------------------------------------------- Domain roles
3818:
3819: sub get_domain_roles {
3820: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3821: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3822: $startdate = '.';
3823: }
1.1018 raeburn 3824: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3825: $enddate = '.';
3826: }
1.922 raeburn 3827: my $rolelist;
3828: if (ref($roles) eq 'ARRAY') {
3829: $rolelist = join(':',@{$roles});
3830: }
1.662 raeburn 3831: my %personnel = ();
1.841 albertel 3832:
3833: my %servers = &get_servers($dom,'library');
3834: foreach my $tryserver (keys(%servers)) {
3835: %{$personnel{$tryserver}}=();
3836: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3837: &escape($startdate).':'.
3838: &escape($enddate).':'.
3839: &escape($rolelist), $tryserver))) {
3840: my ($key,$value) = split(/\=/,$line,2);
3841: if (($key) && ($value)) {
3842: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3843: }
3844: }
1.662 raeburn 3845: }
3846: return %personnel;
3847: }
1.658 raeburn 3848:
1.1057 www 3849: # ----------------------------------------------------------- Interval timing
1.149 www 3850:
1.504 albertel 3851: sub get_first_access {
3852: my ($type,$argsymb)=@_;
1.790 albertel 3853: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3854: if ($argsymb) { $symb=$argsymb; }
3855: my ($map,$id,$res)=&decode_symb($symb);
1.926 albertel 3856: if ($type eq 'course') {
3857: $res='course';
3858: } elsif ($type eq 'map') {
1.588 albertel 3859: $res=&symbread($map);
3860: } else {
3861: $res=$symb;
3862: }
3863: my %times=&get('firstaccesstimes',["$courseid\0$res"],$udom,$uname);
3864: return $times{"$courseid\0$res"};
1.504 albertel 3865: }
3866:
3867: sub set_first_access {
3868: my ($type)=@_;
1.790 albertel 3869: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 3870: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 3871: if ($type eq 'course') {
3872: $res='course';
3873: } elsif ($type eq 'map') {
1.588 albertel 3874: $res=&symbread($map);
3875: } else {
3876: $res=$symb;
3877: }
3878: my $firstaccess=&get_first_access($type,$symb);
1.505 albertel 3879: if (!$firstaccess) {
1.588 albertel 3880: return &put('firstaccesstimes',{"$courseid\0$res"=>time},$udom,$uname);
1.505 albertel 3881: }
3882: return 'already_set';
1.504 albertel 3883: }
3884:
1.110 www 3885: # --------------------------------------------- Set Expire Date for Spreadsheet
3886:
3887: sub expirespread {
3888: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 3889: my $cid=$env{'request.course.id'};
1.110 www 3890: if ($cid) {
3891: my $now=time;
3892: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 3893: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
3894: $env{'course.'.$cid.'.num'}.
1.110 www 3895: ':nohist_expirationdates:'.
3896: &escape($key).'='.$now,
1.620 albertel 3897: $env{'course.'.$cid.'.home'})
1.110 www 3898: }
3899: return 'ok';
1.14 www 3900: }
3901:
1.109 www 3902: # ----------------------------------------------------- Devalidate Spreadsheets
3903:
3904: sub devalidate {
1.325 www 3905: my ($symb,$uname,$udom)=@_;
1.620 albertel 3906: my $cid=$env{'request.course.id'};
1.109 www 3907: if ($cid) {
1.391 matthew 3908: # delete the stored spreadsheets for
3909: # - the student level sheet of this user in course's homespace
3910: # - the assessment level sheet for this resource
3911: # for this user in user's homespace
1.553 albertel 3912: # - current conditional state info
1.325 www 3913: my $key=$uname.':'.$udom.':';
1.109 www 3914: my $status=
1.299 matthew 3915: &del('nohist_calculatedsheets',
1.391 matthew 3916: [$key.'studentcalc:'],
1.620 albertel 3917: $env{'course.'.$cid.'.domain'},
3918: $env{'course.'.$cid.'.num'})
1.133 albertel 3919: .' '.
3920: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 3921: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 3922: unless ($status eq 'ok ok') {
3923: &logthis('Could not devalidate spreadsheet '.
1.325 www 3924: $uname.' at '.$udom.' for '.
1.109 www 3925: $symb.': '.$status);
1.133 albertel 3926: }
1.553 albertel 3927: &delenv('user.state.'.$cid);
1.109 www 3928: }
3929: }
3930:
1.265 albertel 3931: sub get_scalar {
3932: my ($string,$end) = @_;
3933: my $value;
3934: if ($$string =~ s/^([^&]*?)($end)/$2/) {
3935: $value = $1;
3936: } elsif ($$string =~ s/^([^&]*?)&//) {
3937: $value = $1;
3938: }
3939: return &unescape($value);
3940: }
3941:
3942: sub array2str {
3943: my (@array) = @_;
3944: my $result=&arrayref2str(\@array);
3945: $result=~s/^__ARRAY_REF__//;
3946: $result=~s/__END_ARRAY_REF__$//;
3947: return $result;
3948: }
3949:
1.204 albertel 3950: sub arrayref2str {
3951: my ($arrayref) = @_;
1.265 albertel 3952: my $result='__ARRAY_REF__';
1.204 albertel 3953: foreach my $elem (@$arrayref) {
1.265 albertel 3954: if(ref($elem) eq 'ARRAY') {
3955: $result.=&arrayref2str($elem).'&';
3956: } elsif(ref($elem) eq 'HASH') {
3957: $result.=&hashref2str($elem).'&';
3958: } elsif(ref($elem)) {
3959: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 3960: } else {
3961: $result.=&escape($elem).'&';
3962: }
3963: }
3964: $result=~s/\&$//;
1.265 albertel 3965: $result .= '__END_ARRAY_REF__';
1.204 albertel 3966: return $result;
3967: }
3968:
1.168 albertel 3969: sub hash2str {
1.204 albertel 3970: my (%hash) = @_;
3971: my $result=&hashref2str(\%hash);
1.265 albertel 3972: $result=~s/^__HASH_REF__//;
3973: $result=~s/__END_HASH_REF__$//;
1.204 albertel 3974: return $result;
3975: }
3976:
3977: sub hashref2str {
3978: my ($hashref)=@_;
1.265 albertel 3979: my $result='__HASH_REF__';
1.800 albertel 3980: foreach my $key (sort(keys(%$hashref))) {
3981: if (ref($key) eq 'ARRAY') {
3982: $result.=&arrayref2str($key).'=';
3983: } elsif (ref($key) eq 'HASH') {
3984: $result.=&hashref2str($key).'=';
3985: } elsif (ref($key)) {
1.265 albertel 3986: $result.='=';
1.800 albertel 3987: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 3988: } else {
1.1132 raeburn 3989: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 3990: }
3991:
1.800 albertel 3992: if(ref($hashref->{$key}) eq 'ARRAY') {
3993: $result.=&arrayref2str($hashref->{$key}).'&';
3994: } elsif(ref($hashref->{$key}) eq 'HASH') {
3995: $result.=&hashref2str($hashref->{$key}).'&';
3996: } elsif(ref($hashref->{$key})) {
1.265 albertel 3997: $result.='&';
1.800 albertel 3998: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 3999: } else {
1.800 albertel 4000: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4001: }
4002: }
1.168 albertel 4003: $result=~s/\&$//;
1.265 albertel 4004: $result .= '__END_HASH_REF__';
1.168 albertel 4005: return $result;
4006: }
4007:
4008: sub str2hash {
1.265 albertel 4009: my ($string)=@_;
4010: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4011: return %$hash;
4012: }
4013:
4014: sub str2hashref {
1.168 albertel 4015: my ($string) = @_;
1.265 albertel 4016:
4017: my %hash;
4018:
4019: if($string !~ /^__HASH_REF__/) {
4020: if (! ($string eq '' || !defined($string))) {
4021: $hash{'error'}='Not hash reference';
4022: }
4023: return (\%hash, $string);
4024: }
4025:
4026: $string =~ s/^__HASH_REF__//;
4027:
4028: while($string !~ /^__END_HASH_REF__/) {
4029: #key
4030: my $key='';
4031: if($string =~ /^__HASH_REF__/) {
4032: ($key, $string)=&str2hashref($string);
4033: if(defined($key->{'error'})) {
4034: $hash{'error'}='Bad data';
4035: return (\%hash, $string);
4036: }
4037: } elsif($string =~ /^__ARRAY_REF__/) {
4038: ($key, $string)=&str2arrayref($string);
4039: if($key->[0] eq 'Array reference error') {
4040: $hash{'error'}='Bad data';
4041: return (\%hash, $string);
4042: }
4043: } else {
4044: $string =~ s/^(.*?)=//;
1.267 albertel 4045: $key=&unescape($1);
1.265 albertel 4046: }
4047: $string =~ s/^=//;
4048:
4049: #value
4050: my $value='';
4051: if($string =~ /^__HASH_REF__/) {
4052: ($value, $string)=&str2hashref($string);
4053: if(defined($value->{'error'})) {
4054: $hash{'error'}='Bad data';
4055: return (\%hash, $string);
4056: }
4057: } elsif($string =~ /^__ARRAY_REF__/) {
4058: ($value, $string)=&str2arrayref($string);
4059: if($value->[0] eq 'Array reference error') {
4060: $hash{'error'}='Bad data';
4061: return (\%hash, $string);
4062: }
4063: } else {
4064: $value=&get_scalar(\$string,'__END_HASH_REF__');
4065: }
4066: $string =~ s/^&//;
4067:
4068: $hash{$key}=$value;
1.204 albertel 4069: }
1.265 albertel 4070:
4071: $string =~ s/^__END_HASH_REF__//;
4072:
4073: return (\%hash, $string);
1.204 albertel 4074: }
4075:
4076: sub str2array {
1.265 albertel 4077: my ($string)=@_;
4078: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4079: return @$array;
4080: }
4081:
4082: sub str2arrayref {
1.204 albertel 4083: my ($string) = @_;
1.265 albertel 4084: my @array;
4085:
4086: if($string !~ /^__ARRAY_REF__/) {
4087: if (! ($string eq '' || !defined($string))) {
4088: $array[0]='Array reference error';
4089: }
4090: return (\@array, $string);
4091: }
4092:
4093: $string =~ s/^__ARRAY_REF__//;
4094:
4095: while($string !~ /^__END_ARRAY_REF__/) {
4096: my $value='';
4097: if($string =~ /^__HASH_REF__/) {
4098: ($value, $string)=&str2hashref($string);
4099: if(defined($value->{'error'})) {
4100: $array[0] ='Array reference error';
4101: return (\@array, $string);
4102: }
4103: } elsif($string =~ /^__ARRAY_REF__/) {
4104: ($value, $string)=&str2arrayref($string);
4105: if($value->[0] eq 'Array reference error') {
4106: $array[0] ='Array reference error';
4107: return (\@array, $string);
4108: }
4109: } else {
4110: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4111: }
4112: $string =~ s/^&//;
4113:
4114: push(@array, $value);
1.191 harris41 4115: }
1.265 albertel 4116:
4117: $string =~ s/^__END_ARRAY_REF__//;
4118:
4119: return (\@array, $string);
1.168 albertel 4120: }
4121:
1.167 albertel 4122: # -------------------------------------------------------------------Temp Store
4123:
1.168 albertel 4124: sub tmpreset {
4125: my ($symb,$namespace,$domain,$stuname) = @_;
4126: if (!$symb) {
4127: $symb=&symbread();
1.620 albertel 4128: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4129: }
4130: $symb=escape($symb);
4131:
1.620 albertel 4132: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4133: $namespace=~s/\//\_/g;
4134: $namespace=~s/\W//g;
4135:
1.620 albertel 4136: if (!$domain) { $domain=$env{'user.domain'}; }
4137: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4138: if ($domain eq 'public' && $stuname eq 'public') {
4139: $stuname=$ENV{'REMOTE_ADDR'};
4140: }
1.1117 foxr 4141: my $path=LONCAPA::tempdir();
1.168 albertel 4142: my %hash;
4143: if (tie(%hash,'GDBM_File',
4144: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4145: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4146: foreach my $key (keys(%hash)) {
1.180 albertel 4147: if ($key=~ /:$symb/) {
1.168 albertel 4148: delete($hash{$key});
4149: }
4150: }
4151: }
4152: }
4153:
1.167 albertel 4154: sub tmpstore {
1.168 albertel 4155: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4156:
4157: if (!$symb) {
4158: $symb=&symbread();
1.620 albertel 4159: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4160: }
4161: $symb=escape($symb);
4162:
4163: if (!$namespace) {
4164: # I don't think we would ever want to store this for a course.
4165: # it seems this will only be used if we don't have a course.
1.620 albertel 4166: #$namespace=$env{'request.course.id'};
1.168 albertel 4167: #if (!$namespace) {
1.620 albertel 4168: $namespace=$env{'request.state'};
1.168 albertel 4169: #}
4170: }
4171: $namespace=~s/\//\_/g;
4172: $namespace=~s/\W//g;
1.620 albertel 4173: if (!$domain) { $domain=$env{'user.domain'}; }
4174: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4175: if ($domain eq 'public' && $stuname eq 'public') {
4176: $stuname=$ENV{'REMOTE_ADDR'};
4177: }
1.168 albertel 4178: my $now=time;
4179: my %hash;
1.1117 foxr 4180: my $path=LONCAPA::tempdir();
1.168 albertel 4181: if (tie(%hash,'GDBM_File',
4182: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4183: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4184: $hash{"version:$symb"}++;
4185: my $version=$hash{"version:$symb"};
4186: my $allkeys='';
4187: foreach my $key (keys(%$storehash)) {
4188: $allkeys.=$key.':';
1.591 albertel 4189: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4190: }
4191: $hash{"$version:$symb:timestamp"}=$now;
4192: $allkeys.='timestamp';
4193: $hash{"$version:keys:$symb"}=$allkeys;
4194: if (untie(%hash)) {
4195: return 'ok';
4196: } else {
4197: return "error:$!";
4198: }
4199: } else {
4200: return "error:$!";
4201: }
4202: }
1.167 albertel 4203:
1.168 albertel 4204: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4205:
1.168 albertel 4206: sub tmprestore {
4207: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4208:
1.168 albertel 4209: if (!$symb) {
4210: $symb=&symbread();
1.620 albertel 4211: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4212: }
4213: $symb=escape($symb);
4214:
1.620 albertel 4215: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4216:
1.620 albertel 4217: if (!$domain) { $domain=$env{'user.domain'}; }
4218: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4219: if ($domain eq 'public' && $stuname eq 'public') {
4220: $stuname=$ENV{'REMOTE_ADDR'};
4221: }
1.168 albertel 4222: my %returnhash;
4223: $namespace=~s/\//\_/g;
4224: $namespace=~s/\W//g;
4225: my %hash;
1.1117 foxr 4226: my $path=LONCAPA::tempdir();
1.168 albertel 4227: if (tie(%hash,'GDBM_File',
4228: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4229: &GDBM_READER(),0640)) {
1.168 albertel 4230: my $version=$hash{"version:$symb"};
4231: $returnhash{'version'}=$version;
4232: my $scope;
4233: for ($scope=1;$scope<=$version;$scope++) {
4234: my $vkeys=$hash{"$scope:keys:$symb"};
4235: my @keys=split(/:/,$vkeys);
4236: my $key;
4237: $returnhash{"$scope:keys"}=$vkeys;
4238: foreach $key (@keys) {
1.591 albertel 4239: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4240: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4241: }
4242: }
1.168 albertel 4243: if (!(untie(%hash))) {
4244: return "error:$!";
4245: }
4246: } else {
4247: return "error:$!";
4248: }
4249: return %returnhash;
1.167 albertel 4250: }
4251:
1.9 www 4252: # ----------------------------------------------------------------------- Store
4253:
4254: sub store {
1.124 www 4255: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4256: my $home='';
4257:
1.168 albertel 4258: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4259:
1.213 www 4260: $symb=&symbclean($symb);
1.122 albertel 4261: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4262:
1.620 albertel 4263: if (!$domain) { $domain=$env{'user.domain'}; }
4264: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4265:
4266: &devalidate($symb,$stuname,$domain);
1.109 www 4267:
4268: $symb=escape($symb);
1.187 www 4269: if (!$namespace) {
1.620 albertel 4270: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4271: return '';
4272: }
4273: }
1.620 albertel 4274: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4275:
4276: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4277: $$storehash{'host'}=$perlvar{'lonHostID'};
4278:
1.12 www 4279: my $namevalue='';
1.800 albertel 4280: foreach my $key (keys(%$storehash)) {
4281: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4282: }
1.12 www 4283: $namevalue=~s/\&$//;
1.187 www 4284: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4285: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4286: }
4287:
1.47 www 4288: # -------------------------------------------------------------- Critical Store
4289:
4290: sub cstore {
1.124 www 4291: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4292: my $home='';
4293:
1.168 albertel 4294: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4295:
1.213 www 4296: $symb=&symbclean($symb);
1.122 albertel 4297: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4298:
1.620 albertel 4299: if (!$domain) { $domain=$env{'user.domain'}; }
4300: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4301:
4302: &devalidate($symb,$stuname,$domain);
1.109 www 4303:
4304: $symb=escape($symb);
1.187 www 4305: if (!$namespace) {
1.620 albertel 4306: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4307: return '';
4308: }
4309: }
1.620 albertel 4310: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4311:
4312: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4313: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4314:
1.47 www 4315: my $namevalue='';
1.800 albertel 4316: foreach my $key (keys(%$storehash)) {
4317: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4318: }
1.47 www 4319: $namevalue=~s/\&$//;
1.187 www 4320: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4321: return critical
4322: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4323: }
4324:
1.9 www 4325: # --------------------------------------------------------------------- Restore
4326:
4327: sub restore {
1.124 www 4328: my ($symb,$namespace,$domain,$stuname) = @_;
4329: my $home='';
4330:
1.168 albertel 4331: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4332:
1.122 albertel 4333: if (!$symb) {
4334: unless ($symb=escape(&symbread())) { return ''; }
4335: } else {
1.213 www 4336: $symb=&escape(&symbclean($symb));
1.122 albertel 4337: }
1.188 www 4338: if (!$namespace) {
1.620 albertel 4339: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4340: return '';
4341: }
4342: }
1.620 albertel 4343: if (!$domain) { $domain=$env{'user.domain'}; }
4344: if (!$stuname) { $stuname=$env{'user.name'}; }
4345: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4346: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4347:
1.12 www 4348: my %returnhash=();
1.800 albertel 4349: foreach my $line (split(/\&/,$answer)) {
4350: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4351: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4352: }
1.75 www 4353: my $version;
4354: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4355: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4356: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4357: }
1.75 www 4358: }
1.13 www 4359: return %returnhash;
1.34 www 4360: }
4361:
4362: # ---------------------------------------------------------- Course Description
1.1118 foxr 4363: #
4364: #
1.34 www 4365:
4366: sub coursedescription {
1.731 albertel 4367: my ($courseid,$args)=@_;
1.34 www 4368: $courseid=~s/^\///;
1.49 www 4369: $courseid=~s/\_/\//g;
1.34 www 4370: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4371: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4372: my $normalid=$cdomain.'_'.$cnum;
4373: # need to always cache even if we get errors otherwise we keep
4374: # trying and trying and trying to get the course description.
4375: my %envhash=();
4376: my %returnhash=();
1.731 albertel 4377:
4378: my $expiretime=600;
4379: if ($env{'request.course.id'} eq $normalid) {
4380: $expiretime=120;
4381: }
4382:
4383: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4384: if (!$args->{'freshen_cache'}
4385: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4386: foreach my $key (keys(%env)) {
4387: next if ($key !~ /^\Q$prefix\E(.*)/);
4388: my ($setting) = $1;
4389: $returnhash{$setting} = $env{$key};
4390: }
4391: return %returnhash;
4392: }
4393:
1.1118 foxr 4394: # get the data again
4395:
1.731 albertel 4396: if (!$args->{'one_time'}) {
4397: $envhash{'course.'.$normalid.'.last_cache'}=time;
4398: }
1.811 albertel 4399:
1.34 www 4400: if ($chome ne 'no_host') {
1.302 albertel 4401: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4402: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4403: my $username = $env{'user.name'}; # Defult username
4404: if(defined $args->{'user'}) {
4405: $username = $args->{'user'};
4406: }
1.129 albertel 4407: $returnhash{'home'}= $chome;
4408: $returnhash{'domain'} = $cdomain;
4409: $returnhash{'num'} = $cnum;
1.741 raeburn 4410: if (!defined($returnhash{'type'})) {
4411: $returnhash{'type'} = 'Course';
4412: }
1.130 albertel 4413: while (my ($name,$value) = each %returnhash) {
1.53 www 4414: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4415: }
1.270 www 4416: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4417: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4418: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4419: $envhash{'course.'.$normalid.'.home'}=$chome;
4420: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4421: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4422: }
4423: }
1.731 albertel 4424: if (!$args->{'one_time'}) {
1.949 raeburn 4425: &appenv(\%envhash);
1.731 albertel 4426: }
1.302 albertel 4427: return %returnhash;
1.461 www 4428: }
4429:
1.1080 raeburn 4430: sub update_released_required {
4431: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4432: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4433: $cid = $env{'request.course.id'};
4434: $cdom = $env{'course.'.$cid.'.domain'};
4435: $cnum = $env{'course.'.$cid.'.num'};
4436: $chome = $env{'course.'.$cid.'.home'};
4437: }
4438: if ($needsrelease) {
4439: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4440: my $needsupdate;
4441: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4442: $needsupdate = 1;
4443: } else {
4444: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4445: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4446: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4447: $needsupdate = 1;
4448: }
4449: }
4450: if ($needsupdate) {
4451: my %needshash = (
4452: 'internal.releaserequired' => $needsrelease,
4453: );
4454: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4455: if ($putresult eq 'ok') {
4456: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4457: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4458: if (ref($crsinfo{$cid}) eq 'HASH') {
4459: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4460: &courseidput($cdom,\%crsinfo,$chome,'notime');
4461: }
4462: }
4463: }
4464: }
4465: return;
4466: }
4467:
1.461 www 4468: # -------------------------------------------------See if a user is privileged
4469:
4470: sub privileged {
4471: my ($username,$domain)=@_;
4472: my $rolesdump=&reply("dump:$domain:$username:roles",
4473: &homeserver($username,$domain));
1.1033 raeburn 4474: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
4475: ($rolesdump =~ /^error:/)) {
4476: return 0;
4477: }
1.461 www 4478: my $now=time;
4479: if ($rolesdump ne '') {
1.800 albertel 4480: foreach my $entry (split(/&/,$rolesdump)) {
4481: if ($entry!~/^rolesdef_/) {
4482: my ($area,$role)=split(/=/,$entry);
1.461 www 4483: $area=~s/\_\w\w$//;
4484: my ($trole,$tend,$tstart)=split(/_/,$role);
4485: if (($trole eq 'dc') || ($trole eq 'su')) {
4486: my $active=1;
4487: if ($tend) {
4488: if ($tend<$now) { $active=0; }
4489: }
4490: if ($tstart) {
4491: if ($tstart>$now) { $active=0; }
4492: }
4493: if ($active) { return 1; }
4494: }
4495: }
4496: }
4497: }
4498: return 0;
1.9 www 4499: }
1.1 albertel 4500:
1.103 harris41 4501: # -------------------------------------------------------- Get user privileges
1.11 www 4502:
4503: sub rolesinit {
4504: my ($domain,$username,$authhost)=@_;
1.1034 raeburn 4505: my $now=time;
4506: my %userroles = ('user.login.time' => $now);
1.1086 raeburn 4507: my $extra = &freeze_escape({'skipcheck' => 1});
1.1078 raeburn 4508: my $rolesdump=reply("dump:$domain:$username:roles:.::$extra",$authhost);
1.1033 raeburn 4509: if (($rolesdump eq 'con_lost') || ($rolesdump eq '') ||
1.1078 raeburn 4510: ($rolesdump =~ /^error:/)) {
1.1033 raeburn 4511: return \%userroles;
4512: }
1.11 www 4513: my %allroles=();
1.678 raeburn 4514: my %allgroups=();
1.11 www 4515:
4516: if ($rolesdump ne '') {
1.800 albertel 4517: foreach my $entry (split(/&/,$rolesdump)) {
4518: if ($entry!~/^rolesdef_/) {
4519: my ($area,$role)=split(/=/,$entry);
1.587 albertel 4520: $area=~s/\_\w\w$//;
1.678 raeburn 4521: my ($trole,$tend,$tstart,$group_privs);
1.587 albertel 4522: if ($role=~/^cr/) {
1.807 albertel 4523: if ($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4524: ($trole,my $trest)=($role=~m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|);
1.655 albertel 4525: ($tend,$tstart)=split('_',$trest);
4526: } else {
4527: $trole=$role;
4528: }
1.678 raeburn 4529: } elsif ($role =~ m|^gr/|) {
4530: ($trole,$tend,$tstart) = split(/_/,$role);
1.1104 raeburn 4531: next if ($tstart eq '-1');
1.678 raeburn 4532: ($trole,$group_privs) = split(/\//,$trole);
4533: $group_privs = &unescape($group_privs);
1.587 albertel 4534: } else {
4535: ($trole,$tend,$tstart)=split(/_/,$role);
4536: }
1.743 albertel 4537: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4538: $username);
4539: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
1.567 raeburn 4540: if (($tend!=0) && ($tend<$now)) { $trole=''; }
4541: if (($tstart!=0) && ($tstart>$now)) { $trole=''; }
1.11 www 4542: if (($area ne '') && ($trole ne '')) {
1.347 albertel 4543: my $spec=$trole.'.'.$area;
4544: my ($tdummy,$tdomain,$trest)=split(/\//,$area);
4545: if ($trole =~ /^cr\//) {
1.567 raeburn 4546: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
1.678 raeburn 4547: } elsif ($trole eq 'gr') {
4548: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
1.347 albertel 4549: } else {
1.567 raeburn 4550: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
1.347 albertel 4551: }
1.12 www 4552: }
1.662 raeburn 4553: }
1.191 harris41 4554: }
1.743 albertel 4555: my ($author,$adv) = &set_userprivs(\%userroles,\%allroles,\%allgroups);
4556: $userroles{'user.adv'} = $adv;
4557: $userroles{'user.author'} = $author;
1.620 albertel 4558: $env{'user.adv'}=$adv;
1.11 www 4559: }
1.743 albertel 4560: return \%userroles;
1.11 www 4561: }
4562:
1.567 raeburn 4563: sub set_arearole {
4564: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4565: # log the associated role with the area
4566: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4567: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4568: }
4569:
4570: sub custom_roleprivs {
4571: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4572: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4573: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4574: if (&hostname($homsvr) ne '') {
1.567 raeburn 4575: my ($rdummy,$roledef)=
4576: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4577: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4578: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4579: if (defined($syspriv)) {
1.1043 raeburn 4580: if ($trest =~ /^$match_community$/) {
4581: $syspriv =~ s/bre\&S//;
4582: }
1.567 raeburn 4583: $$allroles{'cm./'}.=':'.$syspriv;
4584: $$allroles{$spec.'./'}.=':'.$syspriv;
4585: }
4586: if ($tdomain ne '') {
4587: if (defined($dompriv)) {
4588: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4589: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4590: }
4591: if (($trest ne '') && (defined($coursepriv))) {
4592: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4593: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4594: }
4595: }
4596: }
4597: }
4598: }
4599:
1.678 raeburn 4600: sub group_roleprivs {
4601: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4602: my $access = 1;
4603: my $now = time;
4604: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4605: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4606: if ($access) {
1.811 albertel 4607: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4608: $$allgroups{$course}{$group} .=':'.$group_privs;
4609: }
4610: }
1.567 raeburn 4611:
4612: sub standard_roleprivs {
4613: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4614: if (defined($pr{$trole.':s'})) {
4615: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4616: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4617: }
4618: if ($tdomain ne '') {
4619: if (defined($pr{$trole.':d'})) {
4620: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4621: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4622: }
4623: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4624: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4625: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4626: }
4627: }
4628: }
4629:
4630: sub set_userprivs {
1.1064 raeburn 4631: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4632: my $author=0;
4633: my $adv=0;
1.678 raeburn 4634: my %grouproles = ();
4635: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4636: my @groupkeys;
1.1000 raeburn 4637: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4638: push(@groupkeys,$role);
4639: }
4640: if (ref($groups_roles) eq 'HASH') {
4641: foreach my $key (keys(%{$groups_roles})) {
4642: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4643: push(@groupkeys,$key);
4644: }
4645: }
4646: }
4647: if (@groupkeys > 0) {
4648: foreach my $role (@groupkeys) {
4649: my ($trole,$area,$sec,$extendedarea);
4650: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4651: $trole = $1;
4652: $area = $2;
4653: $sec = $3;
4654: $extendedarea = $area.$sec;
4655: if (exists($$allgroups{$area})) {
4656: foreach my $group (keys(%{$$allgroups{$area}})) {
4657: my $spec = $trole.'.'.$extendedarea;
4658: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4659: $$allgroups{$area}{$group};
1.1064 raeburn 4660: }
1.678 raeburn 4661: }
4662: }
4663: }
4664: }
4665: }
1.800 albertel 4666: foreach my $group (keys(%grouproles)) {
4667: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4668: }
1.800 albertel 4669: foreach my $role (keys(%{$allroles})) {
4670: my %thesepriv;
1.941 raeburn 4671: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4672: foreach my $item (split(/:/,$$allroles{$role})) {
4673: if ($item ne '') {
4674: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4675: if ($restrictions eq '') {
4676: $thesepriv{$privilege}='F';
4677: } elsif ($thesepriv{$privilege} ne 'F') {
4678: $thesepriv{$privilege}.=$restrictions;
4679: }
4680: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4681: }
4682: }
4683: my $thesestr='';
1.1104 raeburn 4684: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4685: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4686: }
4687: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4688: }
4689: return ($author,$adv);
4690: }
4691:
1.994 raeburn 4692: sub role_status {
1.1104 raeburn 4693: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4694: my @pwhere = ();
4695: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4696: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4697: unless (!defined($$role) || $$role eq '') {
4698: $$where=join('.',@pwhere);
4699: $$trolecode=$$role.'.'.$$where;
4700: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4701: $$tstatus='is';
1.1104 raeburn 4702: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4703: $$tstatus='future';
1.1034 raeburn 4704: if ($$tstart<$now) {
4705: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4706: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4707: my (%allroles,%allgroups,$group_privs,
4708: %groups_roles,@rolecodes);
1.1002 raeburn 4709: my %userroles = (
4710: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4711: );
1.1064 raeburn 4712: @rolecodes = ('cm');
1.1002 raeburn 4713: my $spec=$$role.'.'.$$where;
4714: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4715: if ($$role =~ /^cr\//) {
4716: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4717: push(@rolecodes,'cr');
1.1002 raeburn 4718: } elsif ($$role eq 'gr') {
1.1064 raeburn 4719: push(@rolecodes,$$role);
1.1002 raeburn 4720: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4721: $env{'user.name'});
1.1064 raeburn 4722: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4723: (undef,my $group_privs) = split(/\//,$trole);
4724: $group_privs = &unescape($group_privs);
4725: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4726: my %course_roles = &get_my_roles($env{'user.name'},$env{'user.domain'},'userroles',['active'],['cc','co','in','ta','ep','ad','st','cr'],[$tdomain],1);
1.1104 raeburn 4727: &get_groups_roles($tdomain,$trest,
4728: \%course_roles,\@rolecodes,
4729: \%groups_roles);
1.1002 raeburn 4730: } else {
1.1064 raeburn 4731: push(@rolecodes,$$role);
1.1002 raeburn 4732: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4733: }
1.1064 raeburn 4734: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4735: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4736: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4737: }
4738: }
1.1034 raeburn 4739: $$tstatus = 'is';
1.1002 raeburn 4740: }
1.994 raeburn 4741: }
4742: if ($$tend) {
1.1104 raeburn 4743: if ($$tend<$update) {
1.994 raeburn 4744: $$tstatus='expired';
4745: } elsif ($$tend<$now) {
4746: $$tstatus='will_not';
4747: }
4748: }
4749: }
4750: }
4751: }
4752:
1.1104 raeburn 4753: sub get_groups_roles {
4754: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4755: return unless((ref($cdom_courseroles) eq 'HASH') &&
4756: (ref($rolecodes) eq 'ARRAY') &&
4757: (ref($groups_roles) eq 'HASH'));
4758: if (keys(%{$cdom_courseroles}) > 0) {
4759: my ($cnum) = ($rest =~ /^($match_courseid)/);
4760: if ($cdom ne '' && $cnum ne '') {
4761: foreach my $key (keys(%{$cdom_courseroles})) {
4762: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4763: my $crsrole = $1;
4764: my $crssec = $2;
4765: if ($crsrole =~ /^cr/) {
4766: unless (grep(/^cr$/,@{$rolecodes})) {
4767: push(@{$rolecodes},'cr');
4768: }
4769: } else {
4770: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4771: push(@{$rolecodes},$crsrole);
4772: }
4773: }
4774: my $rolekey = "$crsrole./$cdom/$cnum";
4775: if ($crssec ne '') {
4776: $rolekey .= "/$crssec";
4777: }
4778: $rolekey .= './';
4779: $groups_roles->{$rolekey} = $rolecodes;
4780: }
4781: }
4782: }
4783: }
4784: return;
4785: }
4786:
4787: sub delete_env_groupprivs {
4788: my ($where,$courseroles,$possroles) = @_;
4789: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4790: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4791: unless (ref($courseroles->{$udom}) eq 'HASH') {
4792: %{$courseroles->{$udom}} =
4793: &get_my_roles('','','userroles',['active'],
4794: $possroles,[$udom],1);
4795: }
4796: if (ref($courseroles->{$udom}) eq 'HASH') {
4797: foreach my $item (keys(%{$courseroles->{$udom}})) {
4798: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
4799: my $area = '/'.$cdom.'/'.$cnum;
4800: my $privkey = "user.priv.$crsrole.$area";
4801: if ($crssec ne '') {
4802: $privkey .= '/'.$crssec;
4803: }
4804: $privkey .= ".$area/$group";
4805: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
4806: }
4807: }
4808: return;
4809: }
4810:
1.994 raeburn 4811: sub check_adhoc_privs {
1.1104 raeburn 4812: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 4813: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
4814: if ($env{$cckey}) {
4815: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 4816: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 4817: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 4818: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4819: }
4820: } else {
1.1088 raeburn 4821: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 4822: }
4823: }
4824:
4825: sub set_adhoc_privileges {
4826: # role can be cc or ca
1.1088 raeburn 4827: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 4828: my $area = '/'.$dcdom.'/'.$pickedcourse;
4829: my $spec = $role.'.'.$area;
4830: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
4831: $env{'user.name'});
4832: my %ccrole = ();
4833: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
4834: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
4835: &appenv(\%userroles,[$role,'cm']);
4836: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 4837: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
4838: &appenv( {'request.role' => $spec,
4839: 'request.role.domain' => $dcdom,
4840: 'request.course.sec' => ''
4841: }
4842: );
4843: my $tadv=0;
4844: if (&allowed('adv') eq 'F') { $tadv=1; }
4845: &appenv({'request.role.adv' => $tadv});
4846: }
1.994 raeburn 4847: }
4848:
1.12 www 4849: # --------------------------------------------------------------- get interface
4850:
4851: sub get {
1.131 albertel 4852: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 4853: my $items='';
1.800 albertel 4854: foreach my $item (@$storearr) {
4855: $items.=&escape($item).'&';
1.191 harris41 4856: }
1.12 www 4857: $items=~s/\&$//;
1.620 albertel 4858: if (!$udomain) { $udomain=$env{'user.domain'}; }
4859: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 4860: my $uhome=&homeserver($uname,$udomain);
4861:
1.133 albertel 4862: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4863: my @pairs=split(/\&/,$rep);
1.273 albertel 4864: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
4865: return @pairs;
4866: }
1.15 www 4867: my %returnhash=();
1.42 www 4868: my $i=0;
1.800 albertel 4869: foreach my $item (@$storearr) {
4870: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 4871: $i++;
1.191 harris41 4872: }
1.15 www 4873: return %returnhash;
1.27 www 4874: }
4875:
4876: # --------------------------------------------------------------- del interface
4877:
4878: sub del {
1.133 albertel 4879: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 4880: my $items='';
1.800 albertel 4881: foreach my $item (@$storearr) {
4882: $items.=&escape($item).'&';
1.191 harris41 4883: }
1.984 neumanie 4884:
1.27 www 4885: $items=~s/\&$//;
1.620 albertel 4886: if (!$udomain) { $udomain=$env{'user.domain'}; }
4887: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 4888: my $uhome=&homeserver($uname,$udomain);
4889: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 4890: }
4891:
4892: # -------------------------------------------------------------- dump interface
4893:
4894: sub dump {
1.1086 raeburn 4895: my ($namespace,$udomain,$uname,$regexp,$range,$extra)=@_;
1.755 albertel 4896: if (!$udomain) { $udomain=$env{'user.domain'}; }
4897: if (!$uname) { $uname=$env{'user.name'}; }
4898: my $uhome=&homeserver($uname,$udomain);
4899: if ($regexp) {
4900: $regexp=&escape($regexp);
4901: } else {
4902: $regexp='.';
4903: }
1.1086 raeburn 4904: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range:$extra",$uhome);
1.755 albertel 4905: my @pairs=split(/\&/,$rep);
4906: my %returnhash=();
1.1098 foxr 4907: if (!($rep =~ /^error/ )) {
4908: foreach my $item (@pairs) {
4909: my ($key,$value)=split(/=/,$item,2);
4910: $key = &unescape($key);
4911: next if ($key =~ /^error: 2 /);
4912: $returnhash{$key}=&thaw_unescape($value);
4913: }
1.755 albertel 4914: }
4915: return %returnhash;
1.407 www 4916: }
4917:
1.1098 foxr 4918:
1.717 albertel 4919: # --------------------------------------------------------- dumpstore interface
4920:
4921: sub dumpstore {
4922: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.822 albertel 4923: if (!$udomain) { $udomain=$env{'user.domain'}; }
4924: if (!$uname) { $uname=$env{'user.name'}; }
4925: my $uhome=&homeserver($uname,$udomain);
4926: if ($regexp) {
4927: $regexp=&escape($regexp);
4928: } else {
4929: $regexp='.';
4930: }
4931: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
4932: my @pairs=split(/\&/,$rep);
4933: my %returnhash=();
4934: foreach my $item (@pairs) {
4935: my ($key,$value)=split(/=/,$item,2);
4936: next if ($key =~ /^error: 2 /);
4937: $returnhash{$key}=&thaw_unescape($value);
4938: }
4939: return %returnhash;
1.717 albertel 4940: }
4941:
1.407 www 4942: # -------------------------------------------------------------- keys interface
4943:
4944: sub getkeys {
4945: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 4946: if (!$udomain) { $udomain=$env{'user.domain'}; }
4947: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 4948: my $uhome=&homeserver($uname,$udomain);
4949: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
4950: my @keyarray=();
1.800 albertel 4951: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 4952: next if ($key =~ /^error: 2 /);
1.800 albertel 4953: push(@keyarray,&unescape($key));
1.407 www 4954: }
4955: return @keyarray;
1.318 matthew 4956: }
4957:
1.319 matthew 4958: # --------------------------------------------------------------- currentdump
4959: sub currentdump {
1.328 matthew 4960: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 4961: $courseid = $env{'request.course.id'} if (! defined($courseid));
4962: $sdom = $env{'user.domain'} if (! defined($sdom));
4963: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 4964: my $uhome = &homeserver($sname,$sdom);
4965: my $rep=reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
1.318 matthew 4966: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 4967: #
1.318 matthew 4968: my %returnhash=();
1.319 matthew 4969: #
4970: if ($rep eq "unknown_cmd") {
4971: # an old lond will not know currentdump
4972: # Do a dump and make it look like a currentdump
1.822 albertel 4973: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 4974: return if ($tmp[0] =~ /^(error:|no_such_host)/);
4975: my %hash = @tmp;
4976: @tmp=();
1.424 matthew 4977: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 4978: } else {
4979: my @pairs=split(/\&/,$rep);
1.800 albertel 4980: foreach my $pair (@pairs) {
4981: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 4982: my ($symb,$param) = split(/:/,$key);
4983: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 4984: &thaw_unescape($value);
1.319 matthew 4985: }
1.191 harris41 4986: }
1.12 www 4987: return %returnhash;
1.424 matthew 4988: }
4989:
4990: sub convert_dump_to_currentdump{
4991: my %hash = %{shift()};
4992: my %returnhash;
4993: # Code ripped from lond, essentially. The only difference
4994: # here is the unescaping done by lonnet::dump(). Conceivably
4995: # we might run in to problems with parameter names =~ /^v\./
4996: while (my ($key,$value) = each(%hash)) {
4997: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 4998: $symb = &unescape($symb);
4999: $param = &unescape($param);
1.424 matthew 5000: next if ($v eq 'version' || $symb eq 'keys');
5001: next if (exists($returnhash{$symb}) &&
5002: exists($returnhash{$symb}->{$param}) &&
5003: $returnhash{$symb}->{'v.'.$param} > $v);
5004: $returnhash{$symb}->{$param}=$value;
5005: $returnhash{$symb}->{'v.'.$param}=$v;
5006: }
5007: #
5008: # Remove all of the keys in the hashes which keep track of
5009: # the version of the parameter.
5010: while (my ($symb,$param_hash) = each(%returnhash)) {
5011: # use a foreach because we are going to delete from the hash.
5012: foreach my $key (keys(%$param_hash)) {
5013: delete($param_hash->{$key}) if ($key =~ /^v\./);
5014: }
5015: }
5016: return \%returnhash;
1.12 www 5017: }
5018:
1.627 albertel 5019: # ------------------------------------------------------ critical inc interface
5020:
5021: sub cinc {
5022: return &inc(@_,'critical');
5023: }
5024:
1.449 matthew 5025: # --------------------------------------------------------------- inc interface
5026:
5027: sub inc {
1.627 albertel 5028: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5029: if (!$udomain) { $udomain=$env{'user.domain'}; }
5030: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5031: my $uhome=&homeserver($uname,$udomain);
5032: my $items='';
5033: if (! ref($store)) {
5034: # got a single value, so use that instead
5035: $items = &escape($store).'=&';
5036: } elsif (ref($store) eq 'SCALAR') {
5037: $items = &escape($$store).'=&';
5038: } elsif (ref($store) eq 'ARRAY') {
5039: $items = join('=&',map {&escape($_);} @{$store});
5040: } elsif (ref($store) eq 'HASH') {
5041: while (my($key,$value) = each(%{$store})) {
5042: $items.= &escape($key).'='.&escape($value).'&';
5043: }
5044: }
5045: $items=~s/\&$//;
1.627 albertel 5046: if ($critical) {
5047: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5048: } else {
5049: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5050: }
1.449 matthew 5051: }
5052:
1.12 www 5053: # --------------------------------------------------------------- put interface
5054:
5055: sub put {
1.134 albertel 5056: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5057: if (!$udomain) { $udomain=$env{'user.domain'}; }
5058: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5059: my $uhome=&homeserver($uname,$udomain);
1.12 www 5060: my $items='';
1.800 albertel 5061: foreach my $item (keys(%$storehash)) {
5062: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5063: }
1.12 www 5064: $items=~s/\&$//;
1.134 albertel 5065: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5066: }
5067:
1.631 albertel 5068: # ------------------------------------------------------------ newput interface
5069:
5070: sub newput {
5071: my ($namespace,$storehash,$udomain,$uname)=@_;
5072: if (!$udomain) { $udomain=$env{'user.domain'}; }
5073: if (!$uname) { $uname=$env{'user.name'}; }
5074: my $uhome=&homeserver($uname,$udomain);
5075: my $items='';
5076: foreach my $key (keys(%$storehash)) {
5077: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5078: }
5079: $items=~s/\&$//;
5080: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5081: }
5082:
5083: # --------------------------------------------------------- putstore interface
5084:
1.524 raeburn 5085: sub putstore {
1.715 albertel 5086: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5087: if (!$udomain) { $udomain=$env{'user.domain'}; }
5088: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5089: my $uhome=&homeserver($uname,$udomain);
5090: my $items='';
1.715 albertel 5091: foreach my $key (keys(%$storehash)) {
5092: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5093: }
1.715 albertel 5094: $items=~s/\&$//;
1.716 albertel 5095: my $esc_symb=&escape($symb);
5096: my $esc_v=&escape($version);
1.715 albertel 5097: my $reply =
1.716 albertel 5098: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5099: $uhome);
5100: if ($reply eq 'unknown_cmd') {
1.716 albertel 5101: # gfall back to way things use to be done
1.715 albertel 5102: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5103: $uname);
1.524 raeburn 5104: }
1.715 albertel 5105: return $reply;
5106: }
5107:
5108: sub old_putstore {
1.716 albertel 5109: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5110: if (!$udomain) { $udomain=$env{'user.domain'}; }
5111: if (!$uname) { $uname=$env{'user.name'}; }
5112: my $uhome=&homeserver($uname,$udomain);
5113: my %newstorehash;
1.800 albertel 5114: foreach my $item (keys(%$storehash)) {
5115: my $key = $version.':'.&escape($symb).':'.$item;
5116: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5117: }
5118: my $items='';
5119: my %allitems = ();
1.800 albertel 5120: foreach my $item (keys(%newstorehash)) {
5121: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5122: my $key = $1.':keys:'.$2;
5123: $allitems{$key} .= $3.':';
5124: }
1.800 albertel 5125: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5126: }
1.800 albertel 5127: foreach my $item (keys(%allitems)) {
5128: $allitems{$item} =~ s/\:$//;
5129: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5130: }
5131: $items=~s/\&$//;
5132: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5133: }
5134:
1.47 www 5135: # ------------------------------------------------------ critical put interface
5136:
5137: sub cput {
1.134 albertel 5138: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5139: if (!$udomain) { $udomain=$env{'user.domain'}; }
5140: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5141: my $uhome=&homeserver($uname,$udomain);
1.47 www 5142: my $items='';
1.800 albertel 5143: foreach my $item (keys(%$storehash)) {
5144: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5145: }
1.47 www 5146: $items=~s/\&$//;
1.134 albertel 5147: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5148: }
5149:
5150: # -------------------------------------------------------------- eget interface
5151:
5152: sub eget {
1.133 albertel 5153: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5154: my $items='';
1.800 albertel 5155: foreach my $item (@$storearr) {
5156: $items.=&escape($item).'&';
1.191 harris41 5157: }
1.12 www 5158: $items=~s/\&$//;
1.620 albertel 5159: if (!$udomain) { $udomain=$env{'user.domain'}; }
5160: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5161: my $uhome=&homeserver($uname,$udomain);
5162: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5163: my @pairs=split(/\&/,$rep);
5164: my %returnhash=();
1.42 www 5165: my $i=0;
1.800 albertel 5166: foreach my $item (@$storearr) {
5167: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5168: $i++;
1.191 harris41 5169: }
1.12 www 5170: return %returnhash;
5171: }
5172:
1.667 albertel 5173: # ------------------------------------------------------------ tmpput interface
5174: sub tmpput {
1.802 raeburn 5175: my ($storehash,$server,$context)=@_;
1.667 albertel 5176: my $items='';
1.800 albertel 5177: foreach my $item (keys(%$storehash)) {
5178: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5179: }
5180: $items=~s/\&$//;
1.802 raeburn 5181: if (defined($context)) {
5182: $items .= ':'.&escape($context);
5183: }
1.667 albertel 5184: return &reply("tmpput:$items",$server);
5185: }
5186:
5187: # ------------------------------------------------------------ tmpget interface
5188: sub tmpget {
1.688 albertel 5189: my ($token,$server)=@_;
5190: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5191: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5192: my %returnhash;
5193: foreach my $item (split(/\&/,$rep)) {
5194: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5195: next if ($key =~ /^error: 2 /);
1.667 albertel 5196: $returnhash{&unescape($key)}=&thaw_unescape($value);
5197: }
5198: return %returnhash;
5199: }
5200:
1.1113 raeburn 5201: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5202: sub tmpdel {
5203: my ($token,$server)=@_;
5204: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5205: return &reply("tmpdel:$token",$server);
5206: }
5207:
1.765 albertel 5208: # -------------------------------------------------- portfolio access checking
5209:
5210: sub portfolio_access {
1.766 albertel 5211: my ($requrl) = @_;
1.765 albertel 5212: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5213: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5214: if ($result) {
5215: my %setters;
5216: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5217: my ($startblock,$endblock) =
5218: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5219: if ($startblock && $endblock) {
5220: return 'B';
5221: }
5222: } else {
5223: my ($startblock,$endblock) =
5224: &Apache::loncommon::blockcheck(\%setters,'port');
5225: if ($startblock && $endblock) {
5226: return 'B';
5227: }
5228: }
5229: }
1.765 albertel 5230: if ($result eq 'ok') {
1.766 albertel 5231: return 'F';
1.765 albertel 5232: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5233: return 'A';
1.765 albertel 5234: }
1.766 albertel 5235: return '';
1.765 albertel 5236: }
5237:
5238: sub get_portfolio_access {
1.767 albertel 5239: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5240:
5241: if (!ref($access_hash)) {
5242: my $current_perms = &get_portfile_permissions($udom,$unum);
5243: my %access_controls = &get_access_controls($current_perms,$group,
5244: $file_name);
5245: $access_hash = $access_controls{$file_name};
5246: }
5247:
1.765 albertel 5248: my ($public,$guest,@domains,@users,@courses,@groups);
5249: my $now = time;
5250: if (ref($access_hash) eq 'HASH') {
5251: foreach my $key (keys(%{$access_hash})) {
5252: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5253: if ($start > $now) {
5254: next;
5255: }
5256: if ($end && $end<$now) {
5257: next;
5258: }
5259: if ($scope eq 'public') {
5260: $public = $key;
5261: last;
5262: } elsif ($scope eq 'guest') {
5263: $guest = $key;
5264: } elsif ($scope eq 'domains') {
5265: push(@domains,$key);
5266: } elsif ($scope eq 'users') {
5267: push(@users,$key);
5268: } elsif ($scope eq 'course') {
5269: push(@courses,$key);
5270: } elsif ($scope eq 'group') {
5271: push(@groups,$key);
5272: }
5273: }
5274: if ($public) {
5275: return 'ok';
5276: }
5277: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5278: if ($guest) {
5279: return $guest;
5280: }
5281: } else {
5282: if (@domains > 0) {
5283: foreach my $domkey (@domains) {
5284: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5285: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5286: return 'ok';
5287: }
5288: }
5289: }
5290: }
5291: if (@users > 0) {
5292: foreach my $userkey (@users) {
1.865 raeburn 5293: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5294: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5295: if (ref($item) eq 'HASH') {
5296: if (($item->{'uname'} eq $env{'user.name'}) &&
5297: ($item->{'udom'} eq $env{'user.domain'})) {
5298: return 'ok';
5299: }
5300: }
5301: }
5302: }
1.765 albertel 5303: }
5304: }
5305: my %roleshash;
5306: my @courses_and_groups = @courses;
5307: push(@courses_and_groups,@groups);
5308: if (@courses_and_groups > 0) {
5309: my (%allgroups,%allroles);
5310: my ($start,$end,$role,$sec,$group);
5311: foreach my $envkey (%env) {
1.1060 raeburn 5312: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5313: my $cid = $2.'_'.$3;
5314: if ($1 eq 'gr') {
5315: $group = $4;
5316: $allgroups{$cid}{$group} = $env{$envkey};
5317: } else {
5318: if ($4 eq '') {
5319: $sec = 'none';
5320: } else {
5321: $sec = $4;
5322: }
5323: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5324: }
1.811 albertel 5325: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5326: my $cid = $2.'_'.$3;
5327: if ($4 eq '') {
5328: $sec = 'none';
5329: } else {
5330: $sec = $4;
5331: }
5332: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5333: }
5334: }
5335: if (keys(%allroles) == 0) {
5336: return;
5337: }
5338: foreach my $key (@courses_and_groups) {
5339: my %content = %{$$access_hash{$key}};
5340: my $cnum = $content{'number'};
5341: my $cdom = $content{'domain'};
5342: my $cid = $cdom.'_'.$cnum;
5343: if (!exists($allroles{$cid})) {
5344: next;
5345: }
5346: foreach my $role_id (keys(%{$content{'roles'}})) {
5347: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5348: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5349: my @status = @{$content{'roles'}{$role_id}{'access'}};
5350: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5351: foreach my $role (keys(%{$allroles{$cid}})) {
5352: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5353: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5354: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5355: if (grep/^all$/,@sections) {
5356: return 'ok';
5357: } else {
5358: if (grep/^$sec$/,@sections) {
5359: return 'ok';
5360: }
5361: }
5362: }
5363: }
5364: if (keys(%{$allgroups{$cid}}) == 0) {
5365: if (grep/^none$/,@groups) {
5366: return 'ok';
5367: }
5368: } else {
5369: if (grep/^all$/,@groups) {
5370: return 'ok';
5371: }
5372: foreach my $group (keys(%{$allgroups{$cid}})) {
5373: if (grep/^$group$/,@groups) {
5374: return 'ok';
5375: }
5376: }
5377: }
5378: }
5379: }
5380: }
5381: }
5382: }
5383: if ($guest) {
5384: return $guest;
5385: }
5386: }
5387: }
5388: return;
5389: }
5390:
5391: sub course_group_datechecker {
5392: my ($dates,$now,$status) = @_;
5393: my ($start,$end) = split(/\./,$dates);
5394: if (!$start && !$end) {
5395: return 'ok';
5396: }
5397: if (grep/^active$/,@{$status}) {
5398: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5399: return 'ok';
5400: }
5401: }
5402: if (grep/^previous$/,@{$status}) {
5403: if ($end > $now ) {
5404: return 'ok';
5405: }
5406: }
5407: if (grep/^future$/,@{$status}) {
5408: if ($start > $now) {
5409: return 'ok';
5410: }
5411: }
5412: return;
5413: }
5414:
5415: sub parse_portfolio_url {
5416: my ($url) = @_;
5417:
5418: my ($type,$udom,$unum,$group,$file_name);
5419:
1.823 albertel 5420: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5421: $type = 1;
5422: $udom = $1;
5423: $unum = $2;
5424: $file_name = $3;
1.823 albertel 5425: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5426: $type = 2;
5427: $udom = $1;
5428: $unum = $2;
5429: $group = $3;
5430: $file_name = $3.'/'.$4;
5431: }
5432: if (wantarray) {
5433: return ($type,$udom,$unum,$file_name,$group);
5434: }
5435: return $type;
5436: }
5437:
5438: sub is_portfolio_url {
5439: my ($url) = @_;
5440: return scalar(&parse_portfolio_url($url));
5441: }
5442:
1.798 raeburn 5443: sub is_portfolio_file {
5444: my ($file) = @_;
1.820 raeburn 5445: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5446: return 1;
5447: }
5448: return;
5449: }
5450:
1.976 raeburn 5451: sub usertools_access {
1.1084 raeburn 5452: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5453: my ($access,%tools);
5454: if ($context eq '') {
5455: $context = 'tools';
5456: }
5457: if ($context eq 'requestcourses') {
5458: %tools = (
5459: official => 1,
5460: unofficial => 1,
1.1006 raeburn 5461: community => 1,
1.985 raeburn 5462: );
5463: } else {
5464: %tools = (
5465: aboutme => 1,
5466: blog => 1,
5467: portfolio => 1,
5468: );
5469: }
1.976 raeburn 5470: return if (!defined($tools{$tool}));
5471:
5472: if ((!defined($udom)) || (!defined($uname))) {
5473: $udom = $env{'user.domain'};
5474: $uname = $env{'user.name'};
5475: }
5476:
1.978 raeburn 5477: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5478: if ($action ne 'reload') {
1.985 raeburn 5479: if ($context eq 'requestcourses') {
5480: return $env{'environment.canrequest.'.$tool};
5481: } else {
5482: return $env{'environment.availabletools.'.$tool};
5483: }
5484: }
1.976 raeburn 5485: }
5486:
5487: my ($toolstatus,$inststatus);
5488:
1.985 raeburn 5489: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5490: ($action ne 'reload')) {
5491: $toolstatus = $env{'environment.'.$context.'.'.$tool};
1.976 raeburn 5492: $inststatus = $env{'environment.inststatus'};
5493: } else {
1.1084 raeburn 5494: if (ref($userenvref) eq 'HASH') {
5495: $toolstatus = $userenvref->{$context.'.'.$tool};
5496: $inststatus = $userenvref->{'inststatus'};
5497: } else {
5498: my %userenv = &userenvironment($udom,$uname,$context.'.'.$tool,'inststatus');
5499: $toolstatus = $userenv{$context.'.'.$tool};
5500: $inststatus = $userenv{'inststatus'};
5501: }
1.976 raeburn 5502: }
5503:
5504: if ($toolstatus ne '') {
5505: if ($toolstatus) {
5506: $access = 1;
5507: } else {
5508: $access = 0;
5509: }
5510: return $access;
5511: }
5512:
1.1084 raeburn 5513: my ($is_adv,%domdef);
5514: if (ref($is_advref) eq 'HASH') {
5515: $is_adv = $is_advref->{'is_adv'};
5516: } else {
5517: $is_adv = &is_advanced_user($udom,$uname);
5518: }
5519: if (ref($domdefref) eq 'HASH') {
5520: %domdef = %{$domdefref};
5521: } else {
5522: %domdef = &get_domain_defaults($udom);
5523: }
1.976 raeburn 5524: if (ref($domdef{$tool}) eq 'HASH') {
5525: if ($is_adv) {
5526: if ($domdef{$tool}{'_LC_adv'} ne '') {
5527: if ($domdef{$tool}{'_LC_adv'}) {
5528: $access = 1;
5529: } else {
5530: $access = 0;
5531: }
5532: return $access;
5533: }
5534: }
5535: if ($inststatus ne '') {
5536: my ($hasaccess,$hasnoaccess);
5537: foreach my $affiliation (split(/:/,$inststatus)) {
5538: if ($domdef{$tool}{$affiliation} ne '') {
5539: if ($domdef{$tool}{$affiliation}) {
5540: $hasaccess = 1;
5541: } else {
5542: $hasnoaccess = 1;
5543: }
5544: }
5545: }
5546: if ($hasaccess || $hasnoaccess) {
5547: if ($hasaccess) {
5548: $access = 1;
5549: } elsif ($hasnoaccess) {
5550: $access = 0;
5551: }
5552: return $access;
5553: }
5554: } else {
5555: if ($domdef{$tool}{'default'} ne '') {
5556: if ($domdef{$tool}{'default'}) {
5557: $access = 1;
5558: } elsif ($domdef{$tool}{'default'} == 0) {
5559: $access = 0;
5560: }
5561: return $access;
5562: }
5563: }
5564: } else {
1.985 raeburn 5565: if ($context eq 'tools') {
5566: $access = 1;
5567: } else {
5568: $access = 0;
5569: }
1.976 raeburn 5570: return $access;
5571: }
5572: }
5573:
1.1050 raeburn 5574: sub is_course_owner {
5575: my ($cdom,$cnum,$udom,$uname) = @_;
5576: if (($udom eq '') || ($uname eq '')) {
5577: $udom = $env{'user.domain'};
5578: $uname = $env{'user.name'};
5579: }
5580: unless (($udom eq '') || ($uname eq '')) {
5581: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5582: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5583: return 1;
5584: } else {
5585: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5586: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5587: return 1;
5588: }
5589: }
5590: }
5591: }
5592: return;
5593: }
5594:
1.976 raeburn 5595: sub is_advanced_user {
5596: my ($udom,$uname) = @_;
1.1085 raeburn 5597: if ($udom ne '' && $uname ne '') {
5598: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5599: if (wantarray) {
5600: return ($env{'user.adv'},$env{'user.author'});
5601: } else {
5602: return $env{'user.adv'};
5603: }
1.1085 raeburn 5604: }
5605: }
1.976 raeburn 5606: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5607: my %allroles;
1.1128 raeburn 5608: my ($is_adv,$is_author);
1.976 raeburn 5609: foreach my $role (keys(%roleshash)) {
5610: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5611: my $area = '/'.$tdomain.'/'.$trest;
5612: if ($sec ne '') {
5613: $area .= '/'.$sec;
5614: }
5615: if (($area ne '') && ($trole ne '')) {
5616: my $spec=$trole.'.'.$area;
5617: if ($trole =~ /^cr\//) {
5618: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5619: } elsif ($trole ne 'gr') {
5620: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5621: }
1.1128 raeburn 5622: if ($trole eq 'au') {
5623: $is_author = 1;
5624: }
1.976 raeburn 5625: }
5626: }
5627: foreach my $role (keys(%allroles)) {
5628: last if ($is_adv);
5629: foreach my $item (split(/:/,$allroles{$role})) {
5630: if ($item ne '') {
5631: my ($privilege,$restrictions)=split(/&/,$item);
5632: if ($privilege eq 'adv') {
5633: $is_adv = 1;
5634: last;
5635: }
5636: }
5637: }
5638: }
1.1128 raeburn 5639: if (wantarray) {
5640: return ($is_adv,$is_author);
5641: }
1.976 raeburn 5642: return $is_adv;
5643: }
1.798 raeburn 5644:
1.1035 raeburn 5645: sub check_can_request {
1.1036 raeburn 5646: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5647: my $canreq = 0;
5648: my ($types,$typename) = &Apache::loncommon::course_types();
5649: my @options = ('approval','validate','autolimit');
5650: my $optregex = join('|',@options);
5651: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5652: foreach my $type (@{$types}) {
5653: if (&usertools_access($env{'user.name'},
5654: $env{'user.domain'},
5655: $type,undef,'requestcourses')) {
5656: $canreq ++;
1.1036 raeburn 5657: if (ref($request_domains) eq 'HASH') {
5658: push(@{$request_domains->{$type}},$env{'user.domain'});
5659: }
1.1035 raeburn 5660: if ($dom eq $env{'user.domain'}) {
5661: $can_request->{$type} = 1;
5662: }
5663: }
5664: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5665: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5666: if (@curr > 0) {
1.1036 raeburn 5667: foreach my $item (@curr) {
5668: if (ref($request_domains) eq 'HASH') {
5669: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5670: if ($otherdom ne '') {
5671: if (ref($request_domains->{$type}) eq 'ARRAY') {
5672: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5673: push(@{$request_domains->{$type}},$otherdom);
5674: }
5675: } else {
5676: push(@{$request_domains->{$type}},$otherdom);
5677: }
5678: }
5679: }
5680: }
5681: unless($dom eq $env{'user.domain'}) {
5682: $canreq ++;
1.1035 raeburn 5683: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5684: $can_request->{$type} = 1;
5685: }
5686: }
5687: }
5688: }
5689: }
5690: }
5691: return $canreq;
5692: }
5693:
1.341 www 5694: # ---------------------------------------------- Custom access rule evaluation
5695:
5696: sub customaccess {
5697: my ($priv,$uri)=@_;
1.807 albertel 5698: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5699: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5700: $udom = &LONCAPA::clean_domain($udom);
5701: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5702: my $access=0;
1.800 albertel 5703: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5704: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5705: if ($type eq 'user') {
5706: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5707: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5708: if ($tdom) {
5709: if ($tdom ne $env{'user.domain'}) { next; }
5710: }
1.896 albertel 5711: if ($tuname) {
5712: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5713: }
5714: $access=($effect eq 'allow');
5715: last;
5716: }
5717: } else {
5718: if ($role) {
5719: if ($role ne $urole) { next; }
5720: }
5721: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5722: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5723: if ($tdom) {
5724: if ($tdom ne $udom) { next; }
5725: }
5726: if ($tcrs) {
5727: if ($tcrs ne $ucrs) { next; }
5728: }
5729: if ($tsec) {
5730: if ($tsec ne $usec) { next; }
5731: }
5732: $access=($effect eq 'allow');
5733: last;
5734: }
5735: if ($realm eq '' && $role eq '') {
5736: $access=($effect eq 'allow');
5737: }
1.402 bowersj2 5738: }
1.341 www 5739: }
5740: return $access;
5741: }
5742:
1.103 harris41 5743: # ------------------------------------------------- Check for a user privilege
1.12 www 5744:
5745: sub allowed {
1.810 raeburn 5746: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5747: my $ver_orguri=$uri;
1.439 www 5748: $uri=&deversion($uri);
1.152 www 5749: my $orguri=$uri;
1.52 www 5750: $uri=&declutter($uri);
1.809 raeburn 5751:
1.810 raeburn 5752: if ($priv eq 'evb') {
5753: # Evade communication block restrictions for specified role in a course
5754: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5755: return $1;
5756: } else {
5757: return;
5758: }
5759: }
5760:
1.620 albertel 5761: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5762: # Free bre access to adm and meta resources
1.775 albertel 5763: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 5764: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
5765: && ($priv eq 'bre')) {
1.14 www 5766: return 'F';
1.159 www 5767: }
5768:
1.545 banghart 5769: # Free bre access to user's own portfolio contents
1.714 raeburn 5770: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 5771: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 5772: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 5773: my %setters;
5774: my ($startblock,$endblock) =
5775: &Apache::loncommon::blockcheck(\%setters,'port');
5776: if ($startblock && $endblock) {
5777: return 'B';
5778: } else {
5779: return 'F';
5780: }
1.545 banghart 5781: }
5782:
1.762 raeburn 5783: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 5784: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
5785: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
5786: if (exists($env{'request.course.id'})) {
5787: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
5788: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
5789: if (($domain eq $cdom) && ($name eq $cnum)) {
5790: my $courseprivid=$env{'request.course.id'};
5791: $courseprivid=~s/\_/\//;
5792: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
5793: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
5794: return $1;
1.762 raeburn 5795: } else {
5796: if ($env{'request.course.sec'}) {
5797: $courseprivid.='/'.$env{'request.course.sec'};
5798: }
5799: if ($env{'user.priv.'.$env{'request.role'}.'./'.
5800: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
5801: return $2;
5802: }
1.714 raeburn 5803: }
5804: }
5805: }
5806: }
5807:
1.159 www 5808: # Free bre to public access
5809:
5810: if ($priv eq 'bre') {
1.238 www 5811: my $copyright=&metadata($uri,'copyright');
1.620 albertel 5812: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 5813: return 'F';
5814: }
1.238 www 5815: if ($copyright eq 'priv') {
5816: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5817: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 5818: return '';
5819: }
5820: }
5821: if ($copyright eq 'domain') {
5822: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 5823: unless (($env{'user.domain'} eq $1) ||
5824: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 5825: return '';
5826: }
1.262 matthew 5827: }
1.620 albertel 5828: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 5829: # Library role, so allow browsing of resources in this domain.
5830: return 'F';
1.238 www 5831: }
1.341 www 5832: if ($copyright eq 'custom') {
5833: unless (&customaccess($priv,$uri)) { return ''; }
5834: }
1.14 www 5835: }
1.264 matthew 5836: # Domain coordinator is trying to create a course
1.620 albertel 5837: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 5838: # uri is the requested domain in this case.
5839: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 5840: # a role of dc for the domain in question.
1.620 albertel 5841: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 5842: }
1.29 www 5843:
1.52 www 5844: my $thisallowed='';
5845: my $statecond=0;
5846: my $courseprivid='';
5847:
1.1039 raeburn 5848: my $ownaccess;
1.1043 raeburn 5849: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 5850: if (($priv eq 'bro') && ($env{'user.author'})) {
5851: if ($uri eq '') {
5852: $ownaccess = 1;
5853: } else {
5854: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
5855: my $udom = $env{'user.domain'};
5856: my $uname = $env{'user.name'};
5857: if ($uri =~ m{^\Q$udom\E/?$}) {
5858: $ownaccess = 1;
1.1040 raeburn 5859: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 5860: unless ($uri =~ m{\.\./}) {
5861: $ownaccess = 1;
5862: }
5863: } elsif (($udom ne 'public') && ($uname ne 'public')) {
5864: my $now = time;
5865: if ($uri =~ m{^([^/]+)/?$}) {
5866: my $adom = $1;
5867: foreach my $key (keys(%env)) {
1.1042 raeburn 5868: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 5869: my ($start,$end) = split('.',$env{$key});
5870: if (($now >= $start) && (!$end || $end < $now)) {
5871: $ownaccess = 1;
5872: last;
5873: }
5874: }
5875: }
5876: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
5877: my $adom = $1;
5878: my $aname = $2;
1.1042 raeburn 5879: foreach my $role ('ca','aa') {
5880: if ($env{"user.role.$role./$adom/$aname"}) {
5881: my ($start,$end) =
5882: split('.',$env{"user.role.$role./$adom/$aname"});
5883: if (($now >= $start) && (!$end || $end < $now)) {
5884: $ownaccess = 1;
5885: last;
5886: }
1.1039 raeburn 5887: }
5888: }
5889: }
5890: }
5891: }
5892: }
5893: }
5894:
1.52 www 5895: # Course
5896:
1.620 albertel 5897: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5898: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5899: $thisallowed.=$1;
5900: }
1.52 www 5901: }
1.29 www 5902:
1.52 www 5903: # Domain
5904:
1.620 albertel 5905: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 5906: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5907: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5908: $thisallowed.=$1;
5909: }
1.12 www 5910: }
1.52 www 5911:
5912: # Course: uri itself is a course
1.66 www 5913: my $courseuri=$uri;
5914: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 5915: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 5916:
1.620 albertel 5917: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 5918: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 5919: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 5920: $thisallowed.=$1;
5921: }
1.12 www 5922: }
1.29 www 5923:
1.665 albertel 5924: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 5925: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 5926: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 5927: $thisallowed='';
1.671 raeburn 5928: my ($match)=&is_on_map($uri);
5929: if ($match) {
5930: if ($env{'user.priv.'.$env{'request.role'}.'./'}
5931: =~/\Q$priv\E\&([^\:]*)/) {
5932: $thisallowed.=$1;
5933: }
5934: } else {
1.705 albertel 5935: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 5936: if ($refuri) {
5937: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 5938: $thisallowed='F';
1.671 raeburn 5939: } else {
5940: $refuri=&declutter($refuri);
5941: my ($match) = &is_on_map($refuri);
5942: if ($match) {
5943: $thisallowed='F';
5944: }
1.669 raeburn 5945: }
1.671 raeburn 5946: }
5947: }
1.314 www 5948: }
1.492 albertel 5949:
1.766 albertel 5950: if ($priv eq 'bre'
5951: && $thisallowed ne 'F'
5952: && $thisallowed ne '2'
5953: && &is_portfolio_url($uri)) {
5954: $thisallowed = &portfolio_access($uri);
5955: }
5956:
1.52 www 5957: # Full access at system, domain or course-wide level? Exit.
1.29 www 5958: if ($thisallowed=~/F/) {
5959: return 'F';
5960: }
5961:
1.52 www 5962: # If this is generating or modifying users, exit with special codes
1.29 www 5963:
1.643 www 5964: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
5965: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 5966: my ($audom,$auname)=split('/',$uri);
1.643 www 5967: # no author name given, so this just checks on the general right to make a co-author in this domain
5968: unless ($auname) { return $thisallowed; }
5969: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 5970: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
5971: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
5972: ($audom ne $env{'request.role.domain'}))) { return ''; }
5973: }
1.52 www 5974: return $thisallowed;
5975: }
5976: #
1.103 harris41 5977: # Gathered so far: system, domain and course wide privileges
1.52 www 5978: #
5979: # Course: See if uri or referer is an individual resource that is part of
5980: # the course
5981:
1.620 albertel 5982: if ($env{'request.course.id'}) {
1.232 www 5983:
1.620 albertel 5984: $courseprivid=$env{'request.course.id'};
5985: if ($env{'request.course.sec'}) {
5986: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 5987: }
5988: $courseprivid=~s/\_/\//;
5989: my $checkreferer=1;
1.232 www 5990: my ($match,$cond)=&is_on_map($uri);
5991: if ($match) {
5992: $statecond=$cond;
1.620 albertel 5993: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 5994: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 5995: $thisallowed.=$1;
5996: $checkreferer=0;
5997: }
1.29 www 5998: }
1.83 www 5999:
1.148 www 6000: if ($checkreferer) {
1.620 albertel 6001: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6002: unless ($refuri) {
1.800 albertel 6003: foreach my $key (keys(%env)) {
6004: if ($key=~/^httpref\..*\*/) {
6005: my $pattern=$key;
1.156 www 6006: $pattern=~s/^httpref\.\/res\///;
1.148 www 6007: $pattern=~s/\*/\[\^\/\]\+/g;
6008: $pattern=~s/\//\\\//g;
1.152 www 6009: if ($orguri=~/$pattern/) {
1.800 albertel 6010: $refuri=$env{$key};
1.148 www 6011: }
6012: }
1.191 harris41 6013: }
1.148 www 6014: }
1.232 www 6015:
1.148 www 6016: if ($refuri) {
1.152 www 6017: $refuri=&declutter($refuri);
1.232 www 6018: my ($match,$cond)=&is_on_map($refuri);
6019: if ($match) {
6020: my $refstatecond=$cond;
1.620 albertel 6021: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6022: =~/\Q$priv\E\&([^\:]*)/) {
1.52 www 6023: $thisallowed.=$1;
1.53 www 6024: $uri=$refuri;
6025: $statecond=$refstatecond;
1.52 www 6026: }
6027: }
1.148 www 6028: }
1.29 www 6029: }
1.52 www 6030: }
1.29 www 6031:
1.52 www 6032: #
1.103 harris41 6033: # Gathered now: all privileges that could apply, and condition number
1.52 www 6034: #
6035: #
6036: # Full or no access?
6037: #
1.29 www 6038:
1.52 www 6039: if ($thisallowed=~/F/) {
6040: return 'F';
6041: }
1.29 www 6042:
1.52 www 6043: unless ($thisallowed) {
6044: return '';
6045: }
1.29 www 6046:
1.52 www 6047: # Restrictions exist, deal with them
6048: #
6049: # C:according to course preferences
6050: # R:according to resource settings
6051: # L:unless locked
6052: # X:according to user session state
6053: #
6054:
6055: # Possibly locked functionality, check all courses
1.54 www 6056: # Locks might take effect only after 10 minutes cache expiration for other
6057: # courses, and 2 minutes for current course
1.52 www 6058:
6059: my $envkey;
6060: if ($thisallowed=~/L/) {
1.1000 raeburn 6061: foreach $envkey (keys(%env)) {
1.54 www 6062: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6063: my $courseid=$2;
6064: my $roleid=$1.'.'.$2;
1.92 www 6065: $courseid=~s/^\///;
1.54 www 6066: my $expiretime=600;
1.620 albertel 6067: if ($env{'request.role'} eq $roleid) {
1.54 www 6068: $expiretime=120;
6069: }
6070: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6071: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6072: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6073: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6074: }
1.620 albertel 6075: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6076: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6077: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6078: &log($env{'user.domain'},$env{'user.name'},
6079: $env{'user.home'},
1.57 www 6080: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6081: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6082: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6083: return '';
6084: }
6085: }
1.620 albertel 6086: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6087: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6088: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6089: &log($env{'user.domain'},$env{'user.name'},
6090: $env{'user.home'},
1.57 www 6091: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6092: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6093: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6094: return '';
6095: }
6096: }
6097: }
1.29 www 6098: }
1.52 www 6099: }
6100:
6101: #
6102: # Rest of the restrictions depend on selected course
6103: #
6104:
1.620 albertel 6105: unless ($env{'request.course.id'}) {
1.766 albertel 6106: if ($thisallowed eq 'A') {
6107: return 'A';
1.814 raeburn 6108: } elsif ($thisallowed eq 'B') {
6109: return 'B';
1.766 albertel 6110: } else {
6111: return '1';
6112: }
1.52 www 6113: }
1.29 www 6114:
1.52 www 6115: #
6116: # Now user is definitely in a course
6117: #
1.53 www 6118:
6119:
6120: # Course preferences
6121:
6122: if ($thisallowed=~/C/) {
1.620 albertel 6123: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6124: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6125: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6126: =~/\Q$rolecode\E/) {
1.1103 raeburn 6127: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6128: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6129: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6130: $env{'request.course.id'});
6131: }
1.237 www 6132: return '';
6133: }
6134:
1.620 albertel 6135: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6136: =~/\Q$unamedom\E/) {
1.1103 raeburn 6137: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6138: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6139: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6140: $env{'request.course.id'});
6141: }
1.54 www 6142: return '';
6143: }
1.53 www 6144: }
6145:
6146: # Resource preferences
6147:
6148: if ($thisallowed=~/R/) {
1.620 albertel 6149: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6150: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6151: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6152: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6153: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6154: }
6155: return '';
1.54 www 6156: }
1.53 www 6157: }
1.30 www 6158:
1.246 www 6159: # Restricted by state or randomout?
1.30 www 6160:
1.52 www 6161: if ($thisallowed=~/X/) {
1.620 albertel 6162: if ($env{'acc.randomout'}) {
1.579 albertel 6163: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6164: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6165: return '';
6166: }
1.247 www 6167: }
6168: if (&condval($statecond)) {
1.52 www 6169: return '2';
6170: } else {
6171: return '';
6172: }
6173: }
1.30 www 6174:
1.766 albertel 6175: if ($thisallowed eq 'A') {
6176: return 'A';
1.814 raeburn 6177: } elsif ($thisallowed eq 'B') {
6178: return 'B';
1.766 albertel 6179: }
1.52 www 6180: return 'F';
1.232 www 6181: }
1.1133 ! foxr 6182: #
! 6183: # Removes the versino from a URI and
! 6184: # splits it in to its filename and path to the filename.
! 6185: # Seems like File::Basename could have done this more clearly.
! 6186: # Parameters:
! 6187: # $uri - input URI
! 6188: # Returns:
! 6189: # Two element list consisting of
! 6190: # $pathname - the URI up to and excluding the trailing /
! 6191: # $filename - The part of the URI following the last /
! 6192: # NOTE:
! 6193: # Another realization of this is simply:
! 6194: # use File::Basename;
! 6195: # ...
! 6196: # $uri = shift;
! 6197: # $filename = basename($uri);
! 6198: # $path = dirname($uri);
! 6199: # return ($filename, $path);
! 6200: #
! 6201: # The implementation below is probably faster however.
! 6202: #
1.710 albertel 6203: sub split_uri_for_cond {
6204: my $uri=&deversion(&declutter(shift));
6205: my @uriparts=split(/\//,$uri);
6206: my $filename=pop(@uriparts);
6207: my $pathname=join('/',@uriparts);
6208: return ($pathname,$filename);
6209: }
1.232 www 6210: # --------------------------------------------------- Is a resource on the map?
6211:
6212: sub is_on_map {
1.710 albertel 6213: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6214: #Trying to find the conditional for the file
1.620 albertel 6215: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6216: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6217: if ($match) {
1.289 bowersj2 6218: return (1,$1);
6219: } else {
1.434 www 6220: return (0,0);
1.289 bowersj2 6221: }
1.12 www 6222: }
6223:
1.427 www 6224: # --------------------------------------------------------- Get symb from alias
6225:
6226: sub get_symb_from_alias {
6227: my $symb=shift;
6228: my ($map,$resid,$url)=&decode_symb($symb);
6229: # Already is a symb
6230: if ($url) { return $symb; }
6231: # Must be an alias
6232: my $aliassymb='';
6233: my %bighash;
1.620 albertel 6234: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6235: &GDBM_READER(),0640)) {
6236: my $rid=$bighash{'mapalias_'.$symb};
6237: if ($rid) {
6238: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6239: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6240: $resid,$bighash{'src_'.$rid});
1.427 www 6241: }
6242: untie %bighash;
6243: }
6244: return $aliassymb;
6245: }
6246:
1.12 www 6247: # ----------------------------------------------------------------- Define Role
6248:
6249: sub definerole {
6250: if (allowed('mcr','/')) {
6251: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6252: foreach my $role (split(':',$sysrole)) {
6253: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6254: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6255: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6256: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6257: return "refused:s:$crole&$cqual";
6258: }
6259: }
1.191 harris41 6260: }
1.800 albertel 6261: foreach my $role (split(':',$domrole)) {
6262: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6263: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6264: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6265: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6266: return "refused:d:$crole&$cqual";
6267: }
6268: }
1.191 harris41 6269: }
1.800 albertel 6270: foreach my $role (split(':',$courole)) {
6271: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6272: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6273: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6274: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6275: return "refused:c:$crole&$cqual";
6276: }
6277: }
1.191 harris41 6278: }
1.620 albertel 6279: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6280: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6281: "rolesdef_$rolename=".
6282: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6283: return reply($command,$env{'user.home'});
1.12 www 6284: } else {
6285: return 'refused';
6286: }
1.105 harris41 6287: }
6288:
6289: # ---------------- Make a metadata query against the network of library servers
6290:
6291: sub metadata_query {
1.244 matthew 6292: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6293: my %rhash;
1.845 albertel 6294: my %libserv = &all_library();
1.244 matthew 6295: my @server_list = (defined($server_array) ? @$server_array
6296: : keys(%libserv) );
6297: for my $server (@server_list) {
1.118 harris41 6298: unless ($custom or $customshow) {
6299: my $reply=&reply("querysend:".&escape($query),$server);
6300: $rhash{$server}=$reply;
6301: }
6302: else {
6303: my $reply=&reply("querysend:".&escape($query).':'.
6304: &escape($custom).':'.&escape($customshow),
6305: $server);
6306: $rhash{$server}=$reply;
6307: }
1.112 harris41 6308: }
1.118 harris41 6309: return \%rhash;
1.240 www 6310: }
6311:
6312: # ----------------------------------------- Send log queries and wait for reply
6313:
6314: sub log_query {
6315: my ($uname,$udom,$query,%filters)=@_;
6316: my $uhome=&homeserver($uname,$udom);
6317: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6318: my $uhost=&hostname($uhome);
1.800 albertel 6319: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6320: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6321: $uhome);
1.479 albertel 6322: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6323: return get_query_reply($queryid);
6324: }
6325:
1.818 raeburn 6326: # -------------------------- Update MySQL table for portfolio file
6327:
6328: sub update_portfolio_table {
1.821 raeburn 6329: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6330: if ($group ne '') {
6331: $file_name =~s /^\Q$group\E//;
6332: }
1.818 raeburn 6333: my $homeserver = &homeserver($uname,$udom);
6334: my $queryid=
1.821 raeburn 6335: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6336: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6337: my $reply = &get_query_reply($queryid);
6338: return $reply;
6339: }
6340:
1.899 raeburn 6341: # -------------------------- Update MySQL allusers table
6342:
6343: sub update_allusers_table {
6344: my ($uname,$udom,$names) = @_;
6345: my $homeserver = &homeserver($uname,$udom);
6346: my $queryid=
6347: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6348: 'lastname='.&escape($names->{'lastname'}).'%%'.
6349: 'firstname='.&escape($names->{'firstname'}).'%%'.
6350: 'middlename='.&escape($names->{'middlename'}).'%%'.
6351: 'generation='.&escape($names->{'generation'}).'%%'.
6352: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6353: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6354: return;
1.899 raeburn 6355: }
6356:
1.508 raeburn 6357: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6358:
6359: sub fetch_enrollment_query {
1.511 raeburn 6360: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6361: my $homeserver;
1.547 raeburn 6362: my $maxtries = 1;
1.508 raeburn 6363: if ($context eq 'automated') {
6364: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6365: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6366: } else {
6367: $homeserver = &homeserver($cnum,$dom);
6368: }
1.838 albertel 6369: my $host=&hostname($homeserver);
1.506 raeburn 6370: my $cmd = '';
1.1000 raeburn 6371: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6372: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6373: }
6374: $cmd =~ s/%%$//;
6375: $cmd = &escape($cmd);
6376: my $query = 'fetchenrollment';
1.620 albertel 6377: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6378: unless ($queryid=~/^\Q$host\E\_/) {
6379: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6380: return 'error: '.$queryid;
6381: }
1.506 raeburn 6382: my $reply = &get_query_reply($queryid);
1.547 raeburn 6383: my $tries = 1;
6384: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6385: $reply = &get_query_reply($queryid);
6386: $tries ++;
6387: }
1.526 raeburn 6388: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6389: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6390: } else {
1.901 albertel 6391: my @responses = split(/:/,$reply);
1.515 raeburn 6392: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6393: foreach my $line (@responses) {
6394: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6395: $$replyref{$key} = $value;
6396: }
6397: } else {
1.1117 foxr 6398: my $pathname = LONCAPA::tempdir();
1.800 albertel 6399: foreach my $line (@responses) {
6400: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6401: $$replyref{$key} = $value;
6402: if ($value > 0) {
1.800 albertel 6403: foreach my $item (@{$$affiliatesref{$key}}) {
6404: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6405: my $destname = $pathname.'/'.$filename;
6406: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6407: if ($xml_classlist =~ /^error/) {
6408: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6409: } else {
1.506 raeburn 6410: if ( open(FILE,">$destname") ) {
6411: print FILE &unescape($xml_classlist);
6412: close(FILE);
1.526 raeburn 6413: } else {
6414: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6415: }
6416: }
6417: }
6418: }
6419: }
6420: }
6421: return 'ok';
6422: }
6423: return 'error';
6424: }
6425:
1.242 www 6426: sub get_query_reply {
6427: my $queryid=shift;
1.1117 foxr 6428: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6429: my $reply='';
6430: for (1..100) {
6431: sleep 2;
6432: if (-e $replyfile.'.end') {
1.448 albertel 6433: if (open(my $fh,$replyfile)) {
1.904 albertel 6434: $reply = join('',<$fh>);
6435: close($fh);
1.240 www 6436: } else { return 'error: reply_file_error'; }
1.242 www 6437: return &unescape($reply);
6438: }
1.240 www 6439: }
1.242 www 6440: return 'timeout:'.$queryid;
1.240 www 6441: }
6442:
6443: sub courselog_query {
1.241 www 6444: #
6445: # possible filters:
6446: # url: url or symb
6447: # username
6448: # domain
6449: # action: view, submit, grade
6450: # start: timestamp
6451: # end: timestamp
6452: #
1.240 www 6453: my (%filters)=@_;
1.620 albertel 6454: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6455: if ($filters{'url'}) {
6456: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6457: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6458: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6459: }
1.620 albertel 6460: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6461: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6462: return &log_query($cname,$cdom,'courselog',%filters);
6463: }
6464:
6465: sub userlog_query {
1.858 raeburn 6466: #
6467: # possible filters:
6468: # action: log check role
6469: # start: timestamp
6470: # end: timestamp
6471: #
1.240 www 6472: my ($uname,$udom,%filters)=@_;
6473: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6474: }
6475:
1.506 raeburn 6476: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6477:
6478: sub auto_run {
1.508 raeburn 6479: my ($cnum,$cdom) = @_;
1.876 raeburn 6480: my $response = 0;
6481: my $settings;
6482: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6483: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6484: $settings = $domconfig{'autoenroll'};
6485: if ($settings->{'run'} eq '1') {
6486: $response = 1;
6487: }
6488: } else {
1.934 raeburn 6489: my $homeserver;
6490: if (&is_course($cdom,$cnum)) {
6491: $homeserver = &homeserver($cnum,$cdom);
6492: } else {
6493: $homeserver = &domain($cdom,'primary');
6494: }
6495: if ($homeserver ne 'no_host') {
6496: $response = &reply('autorun:'.$cdom,$homeserver);
6497: }
1.876 raeburn 6498: }
1.506 raeburn 6499: return $response;
6500: }
1.776 albertel 6501:
1.506 raeburn 6502: sub auto_get_sections {
1.508 raeburn 6503: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6504: my $homeserver;
6505: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6506: $homeserver = &homeserver($cnum,$cdom);
6507: }
6508: if (!defined($homeserver)) {
6509: if ($cdom =~ /^$match_domain$/) {
6510: $homeserver = &domain($cdom,'primary');
6511: }
6512: }
6513: my @secs;
6514: if (defined($homeserver)) {
6515: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6516: unless ($response eq 'refused') {
6517: @secs = split(/:/,$response);
6518: }
1.506 raeburn 6519: }
6520: return @secs;
6521: }
1.776 albertel 6522:
1.506 raeburn 6523: sub auto_new_course {
1.1099 raeburn 6524: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6525: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6526: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6527: return $response;
6528: }
1.776 albertel 6529:
1.506 raeburn 6530: sub auto_validate_courseID {
1.508 raeburn 6531: my ($cnum,$cdom,$inst_course_id) = @_;
6532: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6533: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6534: return $response;
6535: }
1.776 albertel 6536:
1.1007 raeburn 6537: sub auto_validate_instcode {
1.1020 raeburn 6538: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6539: my ($homeserver,$response);
6540: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6541: $homeserver = &homeserver($cnum,$cdom);
6542: }
6543: if (!defined($homeserver)) {
6544: if ($cdom =~ /^$match_domain$/) {
6545: $homeserver = &domain($cdom,'primary');
6546: }
6547: }
1.1065 raeburn 6548: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6549: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6550: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6551: return ($outcome,$description);
1.1007 raeburn 6552: }
6553:
1.506 raeburn 6554: sub auto_create_password {
1.873 raeburn 6555: my ($cnum,$cdom,$authparam,$udom) = @_;
6556: my ($homeserver,$response);
1.506 raeburn 6557: my $create_passwd = 0;
6558: my $authchk = '';
1.873 raeburn 6559: if ($udom =~ /^$match_domain$/) {
6560: $homeserver = &domain($udom,'primary');
6561: }
6562: if ($homeserver eq '') {
6563: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6564: $homeserver = &homeserver($cnum,$cdom);
6565: }
6566: }
6567: if ($homeserver eq '') {
6568: $authchk = 'nodomain';
1.506 raeburn 6569: } else {
1.873 raeburn 6570: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
6571: if ($response eq 'refused') {
6572: $authchk = 'refused';
6573: } else {
1.901 albertel 6574: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 6575: }
1.506 raeburn 6576: }
6577: return ($authparam,$create_passwd,$authchk);
6578: }
6579:
1.706 raeburn 6580: sub auto_photo_permission {
6581: my ($cnum,$cdom,$students) = @_;
6582: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 6583: my ($outcome,$perm_reqd,$conditions) =
6584: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 6585: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6586: return (undef,undef);
6587: }
1.706 raeburn 6588: return ($outcome,$perm_reqd,$conditions);
6589: }
6590:
6591: sub auto_checkphotos {
6592: my ($uname,$udom,$pid) = @_;
6593: my $homeserver = &homeserver($uname,$udom);
6594: my ($result,$resulttype);
6595: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 6596: &escape($uname).':'.&escape($pid),
6597: $homeserver));
1.709 albertel 6598: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6599: return (undef,undef);
6600: }
1.706 raeburn 6601: if ($outcome) {
6602: ($result,$resulttype) = split(/:/,$outcome);
6603: }
6604: return ($result,$resulttype);
6605: }
6606:
6607: sub auto_photochoice {
6608: my ($cnum,$cdom) = @_;
6609: my $homeserver = &homeserver($cnum,$cdom);
6610: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 6611: &escape($cdom),
6612: $homeserver)));
1.709 albertel 6613: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
6614: return (undef,undef);
6615: }
1.706 raeburn 6616: return ($update,$comment);
6617: }
6618:
6619: sub auto_photoupdate {
6620: my ($affiliatesref,$dom,$cnum,$photo) = @_;
6621: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 6622: my $host=&hostname($homeserver);
1.706 raeburn 6623: my $cmd = '';
6624: my $maxtries = 1;
1.800 albertel 6625: foreach my $affiliate (keys(%{$affiliatesref})) {
6626: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 6627: }
6628: $cmd =~ s/%%$//;
6629: $cmd = &escape($cmd);
6630: my $query = 'institutionalphotos';
6631: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
6632: unless ($queryid=~/^\Q$host\E\_/) {
6633: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
6634: return 'error: '.$queryid;
6635: }
6636: my $reply = &get_query_reply($queryid);
6637: my $tries = 1;
6638: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6639: $reply = &get_query_reply($queryid);
6640: $tries ++;
6641: }
6642: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
6643: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
6644: } else {
6645: my @responses = split(/:/,$reply);
6646: my $outcome = shift(@responses);
6647: foreach my $item (@responses) {
6648: my ($key,$value) = split(/=/,$item);
6649: $$photo{$key} = $value;
6650: }
6651: return $outcome;
6652: }
6653: return 'error';
6654: }
6655:
1.521 raeburn 6656: sub auto_instcode_format {
1.793 albertel 6657: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
6658: $cat_order) = @_;
1.521 raeburn 6659: my $courses = '';
1.772 raeburn 6660: my @homeservers;
1.521 raeburn 6661: if ($caller eq 'global') {
1.841 albertel 6662: my %servers = &get_servers($codedom,'library');
6663: foreach my $tryserver (keys(%servers)) {
6664: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6665: push(@homeservers,$tryserver);
6666: }
1.584 raeburn 6667: }
1.1022 raeburn 6668: } elsif ($caller eq 'requests') {
6669: if ($codedom =~ /^$match_domain$/) {
6670: my $chome = &domain($codedom,'primary');
6671: unless ($chome eq 'no_host') {
6672: push(@homeservers,$chome);
6673: }
6674: }
1.521 raeburn 6675: } else {
1.772 raeburn 6676: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 6677: }
1.793 albertel 6678: foreach my $code (keys(%{$instcodes})) {
6679: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 6680: }
6681: chop($courses);
1.772 raeburn 6682: my $ok_response = 0;
6683: my $response;
6684: while (@homeservers > 0 && $ok_response == 0) {
6685: my $server = shift(@homeservers);
6686: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
6687: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
6688: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 6689: split(/:/,$response);
1.772 raeburn 6690: %{$codes} = (%{$codes},&str2hash($codes_str));
6691: push(@{$codetitles},&str2array($codetitles_str));
6692: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
6693: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
6694: $ok_response = 1;
6695: }
6696: }
6697: if ($ok_response) {
1.521 raeburn 6698: return 'ok';
1.772 raeburn 6699: } else {
6700: return $response;
1.521 raeburn 6701: }
6702: }
6703:
1.792 raeburn 6704: sub auto_instcode_defaults {
6705: my ($domain,$returnhash,$code_order) = @_;
6706: my @homeservers;
1.841 albertel 6707:
6708: my %servers = &get_servers($domain,'library');
6709: foreach my $tryserver (keys(%servers)) {
6710: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6711: push(@homeservers,$tryserver);
6712: }
1.792 raeburn 6713: }
1.841 albertel 6714:
1.792 raeburn 6715: my $response;
1.841 albertel 6716: foreach my $server (@homeservers) {
1.792 raeburn 6717: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 6718: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
6719:
6720: foreach my $pair (split(/\&/,$response)) {
6721: my ($name,$value)=split(/\=/,$pair);
6722: if ($name eq 'code_order') {
6723: @{$code_order} = split(/\&/,&unescape($value));
6724: } else {
6725: $returnhash->{&unescape($name)}=&unescape($value);
6726: }
6727: }
6728: return 'ok';
1.792 raeburn 6729: }
1.841 albertel 6730:
6731: return $response;
1.1003 raeburn 6732: }
6733:
6734: sub auto_possible_instcodes {
1.1007 raeburn 6735: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
6736: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
6737: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
6738: return;
6739: }
1.1003 raeburn 6740: my (@homeservers,$uhome);
6741: if (defined(&domain($domain,'primary'))) {
6742: $uhome=&domain($domain,'primary');
6743: push(@homeservers,&domain($domain,'primary'));
6744: } else {
6745: my %servers = &get_servers($domain,'library');
6746: foreach my $tryserver (keys(%servers)) {
6747: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
6748: push(@homeservers,$tryserver);
6749: }
6750: }
6751: }
6752: my $response;
6753: foreach my $server (@homeservers) {
6754: $response=&reply('autopossibleinstcodes:'.$domain,$server);
6755: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 6756: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
6757: split(':',$response);
6758: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
6759: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 6760: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 6761: my ($name,$value)=split('=',$item);
6762: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6763: }
6764: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 6765: my ($name,$value)=split('=',$item);
6766: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 6767: }
6768: return 'ok';
6769: }
6770: return $response;
6771: }
1.792 raeburn 6772:
1.1010 raeburn 6773: sub auto_courserequest_checks {
6774: my ($dom) = @_;
1.1020 raeburn 6775: my ($homeserver,%validations);
6776: if ($dom =~ /^$match_domain$/) {
6777: $homeserver = &domain($dom,'primary');
6778: }
6779: unless ($homeserver eq 'no_host') {
6780: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
6781: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
6782: my @items = split(/&/,$response);
6783: foreach my $item (@items) {
6784: my ($key,$value) = split('=',$item);
6785: $validations{&unescape($key)} = &thaw_unescape($value);
6786: }
6787: }
6788: }
1.1010 raeburn 6789: return %validations;
6790: }
6791:
1.1020 raeburn 6792: sub auto_courserequest_validation {
6793: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
6794: my ($homeserver,$response);
6795: if ($dom =~ /^$match_domain$/) {
6796: $homeserver = &domain($dom,'primary');
6797: }
6798: unless ($homeserver eq 'no_host') {
1.1021 raeburn 6799:
1.1020 raeburn 6800: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 6801: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 6802: ':'.&escape($instcode).':'.&escape($instseclist),
6803: $homeserver));
6804: }
6805: return $response;
6806: }
6807:
1.777 albertel 6808: sub auto_validate_class_sec {
1.918 raeburn 6809: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 6810: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 6811: my $ownerlist;
6812: if (ref($owners) eq 'ARRAY') {
6813: $ownerlist = join(',',@{$owners});
6814: } else {
6815: $ownerlist = $owners;
6816: }
1.773 raeburn 6817: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 6818: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 6819: return $response;
6820: }
6821:
1.679 raeburn 6822: # ------------------------------------------------------- Course Group routines
6823:
6824: sub get_coursegroups {
1.809 raeburn 6825: my ($cdom,$cnum,$group,$namespace) = @_;
6826: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 6827: }
6828:
1.679 raeburn 6829: sub modify_coursegroup {
6830: my ($cdom,$cnum,$groupsettings) = @_;
6831: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
6832: }
6833:
1.809 raeburn 6834: sub toggle_coursegroup_status {
6835: my ($cdom,$cnum,$group,$action) = @_;
6836: my ($from_namespace,$to_namespace);
6837: if ($action eq 'delete') {
6838: $from_namespace = 'coursegroups';
6839: $to_namespace = 'deleted_groups';
6840: } else {
6841: $from_namespace = 'deleted_groups';
6842: $to_namespace = 'coursegroups';
6843: }
6844: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 6845: if (my $tmp = &error(%curr_group)) {
6846: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
6847: return ('read error',$tmp);
6848: } else {
6849: my %savedsettings = %curr_group;
1.809 raeburn 6850: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 6851: my $deloutcome;
6852: if ($result eq 'ok') {
1.809 raeburn 6853: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 6854: } else {
6855: return ('write error',$result);
6856: }
6857: if ($deloutcome eq 'ok') {
6858: return 'ok';
6859: } else {
6860: return ('delete error',$deloutcome);
6861: }
6862: }
6863: }
6864:
1.679 raeburn 6865: sub modify_group_roles {
1.957 raeburn 6866: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 6867: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
6868: my $role = 'gr/'.&escape($userprivs);
6869: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 6870: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 6871: if ($result eq 'ok') {
6872: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
6873: }
1.679 raeburn 6874: return $result;
6875: }
6876:
6877: sub modify_coursegroup_membership {
6878: my ($cdom,$cnum,$membership) = @_;
6879: my $result = &put('groupmembership',$membership,$cdom,$cnum);
6880: return $result;
6881: }
6882:
1.682 raeburn 6883: sub get_active_groups {
6884: my ($udom,$uname,$cdom,$cnum) = @_;
6885: my $now = time;
6886: my %groups = ();
6887: foreach my $key (keys(%env)) {
1.811 albertel 6888: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 6889: my ($start,$end) = split(/\./,$env{$key});
6890: if (($end!=0) && ($end<$now)) { next; }
6891: if (($start!=0) && ($start>$now)) { next; }
6892: if ($1 eq $cdom && $2 eq $cnum) {
6893: $groups{$3} = $env{$key} ;
6894: }
6895: }
6896: }
6897: return %groups;
6898: }
6899:
1.683 raeburn 6900: sub get_group_membership {
6901: my ($cdom,$cnum,$group) = @_;
6902: return(&dump('groupmembership',$cdom,$cnum,$group));
6903: }
6904:
6905: sub get_users_groups {
6906: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 6907: my @usersgroups;
1.683 raeburn 6908: my $cachetime=1800;
6909:
6910: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 6911: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
6912: if (defined($cached)) {
1.734 albertel 6913: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 6914: } else {
6915: $grouplist = '';
1.816 raeburn 6916: my $courseurl = &courseid_to_courseurl($courseid);
1.1086 raeburn 6917: my $extra = &freeze_escape({'skipcheck' => 1});
6918: my %roleshash = &dump('roles',$udom,$uname,$courseurl,undef,$extra);
1.817 raeburn 6919: my $access_end = $env{'course.'.$courseid.
6920: '.default_enrollment_end_date'};
6921: my $now = time;
6922: foreach my $key (keys(%roleshash)) {
6923: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
6924: my $group = $1;
6925: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
6926: my $start = $2;
6927: my $end = $1;
6928: if ($start == -1) { next; } # deleted from group
6929: if (($start!=0) && ($start>$now)) { next; }
6930: if (($end!=0) && ($end<$now)) {
6931: if ($access_end && $access_end < $now) {
6932: if ($access_end - $end < 86400) {
6933: push(@usersgroups,$group);
1.733 raeburn 6934: }
6935: }
1.817 raeburn 6936: next;
1.733 raeburn 6937: }
1.817 raeburn 6938: push(@usersgroups,$group);
1.683 raeburn 6939: }
6940: }
6941: }
1.817 raeburn 6942: @usersgroups = &sort_course_groups($courseid,@usersgroups);
6943: $grouplist = join(':',@usersgroups);
6944: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 6945: }
1.733 raeburn 6946: return @usersgroups;
1.683 raeburn 6947: }
6948:
6949: sub devalidate_getgroups_cache {
6950: my ($udom,$uname,$cdom,$cnum)=@_;
6951: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 6952:
1.683 raeburn 6953: my $hashid="$udom:$uname:$courseid";
6954: &devalidate_cache_new('getgroups',$hashid);
6955: }
6956:
1.12 www 6957: # ------------------------------------------------------------------ Plain Text
6958:
6959: sub plaintext {
1.988 raeburn 6960: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 6961: if ($short =~ m{^cr/}) {
1.758 albertel 6962: return (split('/',$short))[-1];
6963: }
1.742 raeburn 6964: if (!defined($cid)) {
6965: $cid = $env{'request.course.id'};
6966: }
6967: my %rolenames = (
1.1008 raeburn 6968: Course => 'std',
6969: Community => 'alt1',
1.742 raeburn 6970: );
1.1037 raeburn 6971: if ($cid ne '') {
6972: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
6973: unless ($forcedefault) {
6974: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
6975: &Apache::lonlocal::mt_escape(\$roletext);
6976: return &Apache::lonlocal::mt($roletext);
6977: }
6978: }
6979: }
6980: if ((defined($type)) && (defined($rolenames{$type})) &&
6981: (defined($rolenames{$type})) &&
6982: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 6983: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 6984: } elsif ($cid ne '') {
6985: my $crstype = $env{'course.'.$cid.'.type'};
6986: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
6987: (defined($prp{$short}{$rolenames{$crstype}}))) {
6988: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
6989: }
1.742 raeburn 6990: }
1.1037 raeburn 6991: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 6992: }
6993:
6994: # ----------------------------------------------------------------- Assign Role
6995:
6996: sub assignrole {
1.957 raeburn 6997: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
6998: $context)=@_;
1.21 www 6999: my $mrole;
7000: if ($role =~ /^cr\//) {
1.393 www 7001: my $cwosec=$url;
1.811 albertel 7002: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7003: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7004: my $refused = 1;
7005: if ($context eq 'requestcourses') {
7006: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7007: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7008: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7009: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7010: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7011: if ($crsenv{'internal.courseowner'} eq
7012: $env{'user.name'}.':'.$env{'user.domain'}) {
7013: $refused = '';
7014: }
7015: }
7016: }
7017: }
7018: }
7019: if ($refused) {
7020: &logthis('Refused custom assignrole: '.
7021: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7022: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7023: return 'refused';
7024: }
1.104 www 7025: }
1.21 www 7026: $mrole='cr';
1.678 raeburn 7027: } elsif ($role =~ /^gr\//) {
7028: my $cwogrp=$url;
1.811 albertel 7029: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7030: unless (&allowed('mdg',$cwogrp)) {
7031: &logthis('Refused group assignrole: '.
7032: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7033: $env{'user.name'}.' at '.$env{'user.domain'});
7034: return 'refused';
7035: }
7036: $mrole='gr';
1.21 www 7037: } else {
1.82 www 7038: my $cwosec=$url;
1.811 albertel 7039: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7040: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7041: my $refused;
7042: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7043: if (!(&allowed('c'.$role,$url))) {
7044: $refused = 1;
7045: }
7046: } else {
7047: $refused = 1;
7048: }
1.947 raeburn 7049: if ($refused) {
1.1045 raeburn 7050: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7051: if (!$selfenroll && $context eq 'course') {
7052: my %crsenv;
7053: if ($role eq 'cc' || $role eq 'co') {
7054: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7055: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7056: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7057: if ($crsenv{'internal.courseowner'} eq
7058: $env{'user.name'}.':'.$env{'user.domain'}) {
7059: $refused = '';
7060: }
7061: }
7062: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7063: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7064: if ($crsenv{'internal.courseowner'} eq
7065: $env{'user.name'}.':'.$env{'user.domain'}) {
7066: $refused = '';
7067: }
7068: }
7069: }
7070: }
7071: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7072: $refused = '';
1.1017 raeburn 7073: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7074: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7075: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7076: my $wrongcc;
7077: if ($cnum =~ /^$match_community$/) {
7078: $wrongcc = 1 if ($role eq 'cc');
7079: } else {
7080: $wrongcc = 1 if ($role eq 'co');
7081: }
7082: unless ($wrongcc) {
7083: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7084: if ($crsenv{'internal.courseowner'} eq
7085: $env{'user.name'}.':'.$env{'user.domain'}) {
7086: $refused = '';
7087: }
1.1017 raeburn 7088: }
7089: }
7090: }
7091: if ($refused) {
1.947 raeburn 7092: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7093: ' '.$role.' '.$end.' '.$start.' by '.
7094: $env{'user.name'}.' at '.$env{'user.domain'});
7095: return 'refused';
7096: }
1.932 raeburn 7097: }
1.1131 raeburn 7098: } elsif ($role eq 'au') {
7099: if ($url ne '/'.$udom.'/') {
7100: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7101: ' to assign author role for '.$uname.':'.$udom.
7102: ' in domain: '.$url.' refused (wrong domain).');
7103: return 'refused';
7104: }
1.104 www 7105: }
1.21 www 7106: $mrole=$role;
7107: }
1.620 albertel 7108: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7109: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7110: if ($end) { $command.='_'.$end; }
1.21 www 7111: if ($start) {
7112: if ($end) {
1.81 www 7113: $command.='_'.$start;
1.21 www 7114: } else {
1.81 www 7115: $command.='_0_'.$start;
1.21 www 7116: }
7117: }
1.739 raeburn 7118: my $origstart = $start;
7119: my $origend = $end;
1.957 raeburn 7120: my $delflag;
1.357 www 7121: # actually delete
7122: if ($deleteflag) {
1.373 www 7123: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7124: # modify command to delete the role
1.620 albertel 7125: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7126: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7127: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7128: # set start and finish to negative values for userrolelog
7129: $start=-1;
7130: $end=-1;
1.957 raeburn 7131: $delflag = 1;
1.357 www 7132: }
7133: }
7134: # send command
1.349 www 7135: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7136: # log new user role if status is ok
1.349 www 7137: if ($answer eq 'ok') {
1.663 raeburn 7138: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7139: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7140: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7141: unless ($role =~ /^gr/) {
7142: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7143: $origstart,$selfenroll,$context);
1.739 raeburn 7144: }
1.1053 raeburn 7145: if ($role eq 'cc') {
7146: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7147: }
1.349 www 7148: }
7149: return $answer;
1.169 harris41 7150: }
7151:
1.1053 raeburn 7152: sub autoupdate_coowners {
7153: my ($url,$end,$start,$uname,$udom) = @_;
7154: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7155: if (($cdom ne '') && ($cnum ne '')) {
7156: my $now = time;
7157: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7158: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7159: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7160: my $instcode = $coursehash{'internal.coursecode'};
7161: if ($instcode ne '') {
1.1056 raeburn 7162: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7163: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7164: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7165: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7166: if ($result eq 'valid') {
7167: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7168: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7169: push(@newcoowners,$coowner);
7170: }
7171: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7172: push(@newcoowners,$uname.':'.$udom);
7173: }
7174: @newcoowners = sort(@newcoowners);
7175: } else {
7176: push(@newcoowners,$uname.':'.$udom);
7177: }
7178: } else {
7179: if ($coursehash{'internal.co-owners'}) {
7180: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7181: unless ($coowner eq $uname.':'.$udom) {
7182: push(@newcoowners,$coowner);
7183: }
7184: }
7185: unless (@newcoowners > 0) {
7186: $delcoowners = 1;
7187: $coowners = '';
7188: }
7189: }
7190: }
7191: if (@newcoowners || $delcoowners) {
7192: &store_coowners($cdom,$cnum,$coursehash{'home'},
7193: $delcoowners,@newcoowners);
7194: }
7195: }
7196: }
7197: }
7198: }
7199: }
7200: }
7201:
7202: sub store_coowners {
7203: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7204: my $cid = $cdom.'_'.$cnum;
7205: my ($coowners,$delresult,$putresult);
7206: if (@newcoowners) {
7207: $coowners = join(',',@newcoowners);
7208: my %coownershash = (
7209: 'internal.co-owners' => $coowners,
7210: );
7211: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7212: if ($putresult eq 'ok') {
7213: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7214: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7215: }
7216: }
7217: }
7218: if ($delcoowners) {
7219: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7220: if ($delresult eq 'ok') {
7221: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7222: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7223: }
7224: }
7225: }
7226: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7227: my %crsinfo =
7228: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7229: if (ref($crsinfo{$cid}) eq 'HASH') {
7230: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7231: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7232: }
7233: }
7234: }
7235:
1.169 harris41 7236: # -------------------------------------------------- Modify user authentication
1.197 www 7237: # Overrides without validation
7238:
1.169 harris41 7239: sub modifyuserauth {
7240: my ($udom,$uname,$umode,$upass)=@_;
7241: my $uhome=&homeserver($uname,$udom);
1.197 www 7242: unless (&allowed('mau',$udom)) { return 'refused'; }
7243: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7244: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7245: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7246: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7247: &escape($upass),$uhome);
1.620 albertel 7248: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7249: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7250: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7251: &log($udom,,$uname,$uhome,
1.620 albertel 7252: 'Authentication changed by '.$env{'user.domain'}.', '.
7253: $env{'user.name'}.', '.$umode.
1.197 www 7254: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7255: unless ($reply eq 'ok') {
1.197 www 7256: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7257: return 'error: '.$reply;
7258: }
1.170 harris41 7259: return 'ok';
1.80 www 7260: }
7261:
1.81 www 7262: # --------------------------------------------------------------- Modify a user
1.80 www 7263:
1.81 www 7264: sub modifyuser {
1.206 matthew 7265: my ($udom, $uname, $uid,
7266: $umode, $upass, $first,
7267: $middle, $last, $gene,
1.1058 raeburn 7268: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7269: $udom= &LONCAPA::clean_domain($udom);
7270: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7271: my $showcandelete = 'none';
7272: if (ref($candelete) eq 'ARRAY') {
7273: if (@{$candelete} > 0) {
7274: $showcandelete = join(', ',@{$candelete});
7275: }
7276: }
1.81 www 7277: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7278: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7279: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7280: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7281: ' desiredhome not specified').
1.620 albertel 7282: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7283: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7284: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7285: my $newuser;
7286: if ($uhome eq 'no_host') {
7287: $newuser = 1;
7288: }
1.80 www 7289: # ----------------------------------------------------------------- Create User
1.406 albertel 7290: if (($uhome eq 'no_host') &&
7291: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7292: my $unhome='';
1.844 albertel 7293: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7294: $unhome = $desiredhome;
1.620 albertel 7295: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7296: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7297: } else { # load balancing routine for determining $unhome
1.81 www 7298: my $loadm=10000000;
1.841 albertel 7299: my %servers = &get_servers($udom,'library');
7300: foreach my $tryserver (keys(%servers)) {
7301: my $answer=reply('load',$tryserver);
7302: if (($answer=~/\d+/) && ($answer<$loadm)) {
7303: $loadm=$answer;
7304: $unhome=$tryserver;
7305: }
1.80 www 7306: }
7307: }
7308: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7309: return 'error: unable to find a home server for '.$uname.
7310: ' in domain '.$udom;
1.80 www 7311: }
7312: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7313: &escape($upass),$unhome);
7314: unless ($reply eq 'ok') {
7315: return 'error: '.$reply;
7316: }
1.230 stredwic 7317: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7318: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7319: return 'error: unable verify users home machine.';
1.80 www 7320: }
1.209 matthew 7321: } # End of creation of new user
1.80 www 7322: # ---------------------------------------------------------------------- Add ID
7323: if ($uid) {
7324: $uid=~tr/A-Z/a-z/;
7325: my %uidhash=&idrget($udom,$uname);
1.196 www 7326: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7327: && (!$forceid)) {
1.80 www 7328: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7329: return 'error: user id "'.$uid.'" does not match '.
7330: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7331: }
7332: } else {
7333: &idput($udom,($uname => $uid));
7334: }
7335: }
7336: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7337: my @tmp=&get('environment',
1.899 raeburn 7338: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7339: 'permanentemail','inststatus'],
1.134 albertel 7340: $udom,$uname);
1.1075 raeburn 7341: my (%names,%oldnames);
1.313 matthew 7342: if ($tmp[0] =~ m/^error:.*/) {
7343: %names=();
7344: } else {
7345: %names = @tmp;
1.1075 raeburn 7346: %oldnames = %names;
1.313 matthew 7347: }
1.388 www 7348: #
1.1058 raeburn 7349: # If name, email and/or uid are blank (e.g., because an uploaded file
7350: # of users did not contain them), do not overwrite existing values
7351: # unless field is in $candelete array ref.
7352: #
7353:
7354: my @fields = ('firstname','middlename','lastname','generation',
7355: 'permanentemail','id');
7356: my %newvalues;
7357: if (ref($candelete) eq 'ARRAY') {
7358: foreach my $field (@fields) {
7359: if (grep(/^\Q$field\E$/,@{$candelete})) {
7360: if ($field eq 'firstname') {
7361: $names{$field} = $first;
7362: } elsif ($field eq 'middlename') {
7363: $names{$field} = $middle;
7364: } elsif ($field eq 'lastname') {
7365: $names{$field} = $last;
7366: } elsif ($field eq 'generation') {
7367: $names{$field} = $gene;
7368: } elsif ($field eq 'permanentemail') {
7369: $names{$field} = $email;
7370: } elsif ($field eq 'id') {
7371: $names{$field} = $uid;
7372: }
7373: }
7374: }
7375: }
1.388 www 7376: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7377: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7378: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7379: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7380: if ($email) {
7381: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7382: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7383: }
1.899 raeburn 7384: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7385: if (defined($inststatus)) {
7386: $names{'inststatus'} = '';
7387: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7388: if (ref($usertypes) eq 'HASH') {
7389: my @okstatuses;
7390: foreach my $item (split(/:/,$inststatus)) {
7391: if (defined($usertypes->{$item})) {
7392: push(@okstatuses,$item);
7393: }
7394: }
7395: if (@okstatuses) {
7396: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7397: }
7398: }
7399: }
1.1075 raeburn 7400: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7401: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7402: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7403: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7404: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7405: } else {
7406: $logmsg .= ' during self creation';
7407: }
1.1075 raeburn 7408: my $changed;
7409: if ($newuser) {
7410: $changed = 1;
7411: } else {
7412: foreach my $field (@fields) {
7413: if ($names{$field} ne $oldnames{$field}) {
7414: $changed = 1;
7415: last;
7416: }
7417: }
7418: }
7419: unless ($changed) {
7420: $logmsg = 'No changes in user information needed for: '.$logmsg;
7421: &logthis($logmsg);
7422: return 'ok';
7423: }
7424: my $reply = &put('environment', \%names, $udom,$uname);
7425: if ($reply ne 'ok') {
7426: return 'error: '.$reply;
7427: }
1.1087 raeburn 7428: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7429: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7430: }
1.1075 raeburn 7431: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7432: &devalidate_cache_new('namescache',$uname.':'.$udom);
7433: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7434: &logthis($logmsg);
1.134 albertel 7435: return 'ok';
1.80 www 7436: }
7437:
1.81 www 7438: # -------------------------------------------------------------- Modify student
1.80 www 7439:
1.81 www 7440: sub modifystudent {
7441: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7442: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7443: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7444: if (!$cid) {
1.620 albertel 7445: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7446: return 'not_in_class';
7447: }
1.80 www 7448: }
7449: # --------------------------------------------------------------- Make the user
1.81 www 7450: my $reply=&modifyuser
1.209 matthew 7451: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7452: $desiredhome,$email,$inststatus);
1.80 www 7453: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7454: # This will cause &modify_student_enrollment to get the uid from the
7455: # students environment
7456: $uid = undef if (!$forceid);
1.455 albertel 7457: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7458: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7459: return $reply;
7460: }
7461:
7462: sub modify_student_enrollment {
1.957 raeburn 7463: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7464: my ($cdom,$cnum,$chome);
7465: if (!$cid) {
1.620 albertel 7466: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7467: return 'not_in_class';
7468: }
1.620 albertel 7469: $cdom=$env{'course.'.$cid.'.domain'};
7470: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7471: } else {
7472: ($cdom,$cnum)=split(/_/,$cid);
7473: }
1.620 albertel 7474: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7475: if (!$chome) {
1.457 raeburn 7476: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7477: }
1.455 albertel 7478: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7479: # Make sure the user exists
1.81 www 7480: my $uhome=&homeserver($uname,$udom);
7481: if (($uhome eq '') || ($uhome eq 'no_host')) {
7482: return 'error: no such user';
7483: }
1.297 matthew 7484: # Get student data if we were not given enough information
7485: if (!defined($first) || $first eq '' ||
7486: !defined($last) || $last eq '' ||
7487: !defined($uid) || $uid eq '' ||
7488: !defined($middle) || $middle eq '' ||
7489: !defined($gene) || $gene eq '') {
1.294 matthew 7490: # They did not supply us with enough data to enroll the student, so
7491: # we need to pick up more information.
1.297 matthew 7492: my %tmp = &get('environment',
1.294 matthew 7493: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7494: ,$udom,$uname);
7495:
1.800 albertel 7496: #foreach my $key (keys(%tmp)) {
7497: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7498: #}
1.294 matthew 7499: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7500: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7501: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7502: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7503: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7504: }
1.556 albertel 7505: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.487 albertel 7506: my $reply=cput('classlist',
7507: {"$uname:$udom" =>
1.515 raeburn 7508: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7509: $cdom,$cnum);
1.81 www 7510: unless (($reply eq 'ok') || ($reply eq 'delayed')) {
7511: return 'error: '.$reply;
1.652 albertel 7512: } else {
7513: &devalidate_getsection_cache($udom,$uname,$cid);
1.81 www 7514: }
1.297 matthew 7515: # Add student role to user
1.83 www 7516: my $uurl='/'.$cid;
1.81 www 7517: $uurl=~s/\_/\//g;
7518: if ($usec) {
7519: $uurl.='/'.$usec;
7520: }
1.957 raeburn 7521: return &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,$selfenroll,$context);
1.21 www 7522: }
7523:
1.556 albertel 7524: sub format_name {
7525: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
7526: my $name;
7527: if ($first ne 'lastname') {
7528: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
7529: } else {
7530: if ($lastname=~/\S/) {
7531: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
7532: $name=~s/\s+,/,/;
7533: } else {
7534: $name.= $firstname.' '.$middlename.' '.$generation;
7535: }
7536: }
7537: $name=~s/^\s+//;
7538: $name=~s/\s+$//;
7539: $name=~s/\s+/ /g;
7540: return $name;
7541: }
7542:
1.84 www 7543: # ------------------------------------------------- Write to course preferences
7544:
7545: sub writecoursepref {
7546: my ($courseid,%prefs)=@_;
7547: $courseid=~s/^\///;
7548: $courseid=~s/\_/\//g;
7549: my ($cdomain,$cnum)=split(/\//,$courseid);
7550: my $chome=homeserver($cnum,$cdomain);
7551: if (($chome eq '') || ($chome eq 'no_host')) {
7552: return 'error: no such course';
7553: }
7554: my $cstring='';
1.800 albertel 7555: foreach my $pref (keys(%prefs)) {
7556: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 7557: }
1.84 www 7558: $cstring=~s/\&$//;
7559: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
7560: }
7561:
7562: # ---------------------------------------------------------- Make/modify course
7563:
7564: sub createcourse {
1.741 raeburn 7565: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 7566: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 7567: $url=&declutter($url);
7568: my $cid='';
1.1028 raeburn 7569: if ($context eq 'requestcourses') {
7570: my $can_create = 0;
7571: my ($ownername,$ownerdom) = split(':',$course_owner);
7572: if ($udom eq $ownerdom) {
7573: if (&usertools_access($ownername,$ownerdom,$category,undef,
7574: $context)) {
7575: $can_create = 1;
7576: }
7577: } else {
7578: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
7579: $category);
7580: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
7581: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
7582: if (@curr > 0) {
7583: my @options = qw(approval validate autolimit);
7584: my $optregex = join('|',@options);
7585: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
7586: $can_create = 1;
7587: }
7588: }
7589: }
7590: }
7591: if ($can_create) {
7592: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
7593: unless (&allowed('ccc',$udom)) {
7594: return 'refused';
7595: }
1.1017 raeburn 7596: }
7597: } else {
7598: return 'refused';
7599: }
1.1028 raeburn 7600: } elsif (!&allowed('ccc',$udom)) {
7601: return 'refused';
1.84 www 7602: }
1.1011 raeburn 7603: # --------------------------------------------------------------- Get Unique ID
7604: my $uname;
7605: if ($cnum =~ /^$match_courseid$/) {
7606: my $chome=&homeserver($cnum,$udom,'true');
7607: if (($chome eq '') || ($chome eq 'no_host')) {
7608: $uname = $cnum;
7609: } else {
1.1038 raeburn 7610: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7611: }
7612: } else {
1.1038 raeburn 7613: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 7614: }
7615: return $uname if ($uname =~ /^error/);
7616: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 7617: if (!defined($course_server)) {
7618: if (defined(&domain($udom,'primary'))) {
7619: $course_server = &domain($udom,'primary');
7620: } else {
7621: $course_server = $env{'user.home'};
7622: }
7623: }
7624: my %host_servers =
7625: &Apache::lonnet::get_servers($udom,'library');
7626: unless ($host_servers{$course_server}) {
7627: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 7628: }
1.84 www 7629: # ------------------------------------------------------------- Make the course
7630: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 7631: $course_server);
1.84 www 7632: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 7633: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 7634: if (($uhome eq '') || ($uhome eq 'no_host')) {
7635: return 'error: no such course';
7636: }
1.271 www 7637: # ----------------------------------------------------------------- Course made
1.516 raeburn 7638: # log existence
1.1029 raeburn 7639: my $now = time;
1.918 raeburn 7640: my $newcourse = {
7641: $udom.'_'.$uname => {
1.921 raeburn 7642: description => $description,
7643: inst_code => $inst_code,
7644: owner => $course_owner,
7645: type => $crstype,
1.1029 raeburn 7646: creator => $env{'user.name'}.':'.
7647: $env{'user.domain'},
7648: created => $now,
7649: context => $context,
1.918 raeburn 7650: },
7651: };
1.921 raeburn 7652: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 7653: # set toplevel url
1.271 www 7654: my $topurl=$url;
7655: unless ($nonstandard) {
7656: # ------------------------------------------ For standard courses, make top url
7657: my $mapurl=&clutter($url);
1.278 www 7658: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 7659: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 7660: <map>
7661: <resource id="1" type="start"></resource>
7662: <resource id="2" src="$mapurl"></resource>
7663: <resource id="3" type="finish"></resource>
7664: <link index="1" from="1" to="2"></link>
7665: <link index="2" from="2" to="3"></link>
7666: </map>
7667: ENDINITMAP
7668: $topurl=&declutter(
1.638 albertel 7669: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 7670: );
7671: }
7672: # ----------------------------------------------------------- Write preferences
1.84 www 7673: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 7674: ('description' => $description,
7675: 'url' => $topurl,
7676: 'internal.creator' => $env{'user.name'}.':'.
7677: $env{'user.domain'},
7678: 'internal.created' => $now,
7679: 'internal.creationcontext' => $context)
7680: );
1.84 www 7681: return '/'.$udom.'/'.$uname;
7682: }
7683:
1.1011 raeburn 7684: # ------------------------------------------------------------------- Create ID
7685: sub generate_coursenum {
1.1038 raeburn 7686: my ($udom,$crstype) = @_;
1.1011 raeburn 7687: my $domdesc = &domain($udom);
7688: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 7689: my $first;
7690: if ($crstype eq 'Community') {
7691: $first = '0';
7692: } else {
7693: $first = int(1+rand(9));
7694: }
7695: my $uname=$first.
1.1011 raeburn 7696: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7697: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7698: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7699: # ----------------------------------------------- Make sure that does not exist
7700: my $uhome=&homeserver($uname,$udom,'true');
7701: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 7702: if ($crstype eq 'Community') {
7703: $first = '0';
7704: } else {
7705: $first = int(1+rand(9));
7706: }
7707: $uname=$first.
1.1011 raeburn 7708: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
7709: substr($$.time,0,5).unpack("H8",pack("I32",time)).
7710: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
7711: $uhome=&homeserver($uname,$udom,'true');
7712: unless (($uhome eq '') || ($uhome eq 'no_host')) {
7713: return 'error: unable to generate unique course-ID';
7714: }
7715: }
7716: return $uname;
7717: }
7718:
1.813 albertel 7719: sub is_course {
7720: my ($cdom,$cnum) = @_;
7721: my %courses = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,
1.946 raeburn 7722: undef,'.');
1.813 albertel 7723: if (exists($courses{$cdom.'_'.$cnum})) {
7724: return 1;
7725: }
7726: return 0;
7727: }
7728:
1.1015 raeburn 7729: sub store_userdata {
7730: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 7731: my $result;
1.1016 raeburn 7732: if ($datakey ne '') {
1.1013 raeburn 7733: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 7734: if ($udom eq '' || $uname eq '') {
7735: $udom = $env{'user.domain'};
7736: $uname = $env{'user.name'};
7737: }
7738: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 7739: if (($uhome eq '') || ($uhome eq 'no_host')) {
7740: $result = 'error: no_host';
7741: } else {
7742: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
7743: $storehash->{'host'} = $perlvar{'lonHostID'};
7744:
7745: my $namevalue='';
7746: foreach my $key (keys(%{$storehash})) {
7747: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
7748: }
7749: $namevalue=~s/\&$//;
1.1105 raeburn 7750: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
7751: $namevalue,$uhome);
1.1013 raeburn 7752: }
7753: } else {
7754: $result = 'error: data to store was not a hash reference';
7755: }
7756: } else {
7757: $result= 'error: invalid requestkey';
7758: }
7759: return $result;
7760: }
7761:
1.21 www 7762: # ---------------------------------------------------------- Assign Custom Role
7763:
7764: sub assigncustomrole {
1.957 raeburn 7765: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7766: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 7767: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 7768: }
7769:
7770: # ----------------------------------------------------------------- Revoke Role
7771:
7772: sub revokerole {
1.957 raeburn 7773: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7774: my $now=time;
1.965 raeburn 7775: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 7776: }
7777:
7778: # ---------------------------------------------------------- Revoke Custom Role
7779:
7780: sub revokecustomrole {
1.957 raeburn 7781: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 7782: my $now=time;
1.357 www 7783: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 7784: $deleteflag,$selfenroll,$context);
1.17 www 7785: }
7786:
1.533 banghart 7787: # ------------------------------------------------------------ Disk usage
1.535 albertel 7788: sub diskusage {
1.955 raeburn 7789: my ($udom,$uname,$directorypath,$getpropath)=@_;
7790: $directorypath =~ s/\/$//;
7791: my $listing=&reply('du2:'.&escape($directorypath).':'
7792: .&escape($getpropath).':'.&escape($uname).':'
7793: .&escape($udom),homeserver($uname,$udom));
7794: if ($listing eq 'unknown_cmd') {
7795: if ($getpropath) {
7796: $directorypath = &propath($udom,$uname).'/'.$directorypath;
7797: }
7798: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
7799: }
1.514 albertel 7800: return $listing;
1.512 banghart 7801: }
7802:
1.566 banghart 7803: sub is_locked {
1.1096 raeburn 7804: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 7805: my @check;
7806: my $is_locked;
1.1093 raeburn 7807: push (@check,$file_name);
1.613 albertel 7808: my %locked = &get('file_permissions',\@check,
1.620 albertel 7809: $env{'user.domain'},$env{'user.name'});
1.615 albertel 7810: my ($tmp)=keys(%locked);
7811: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 7812:
1.566 banghart 7813: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 7814: $is_locked = 'false';
7815: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 7816: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 7817: $is_locked = 'true';
1.1096 raeburn 7818: if (ref($which) eq 'ARRAY') {
7819: push(@{$which},$entry);
7820: } else {
7821: last;
7822: }
1.745 raeburn 7823: }
7824: }
1.566 banghart 7825: } else {
7826: $is_locked = 'false';
7827: }
1.1093 raeburn 7828: return $is_locked;
1.566 banghart 7829: }
7830:
1.759 albertel 7831: sub declutter_portfile {
7832: my ($file) = @_;
1.833 albertel 7833: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 7834: return $file;
7835: }
7836:
1.559 banghart 7837: # ------------------------------------------------------------- Mark as Read Only
7838:
7839: sub mark_as_readonly {
7840: my ($domain,$user,$files,$what) = @_;
1.613 albertel 7841: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7842: my ($tmp)=keys(%current_permissions);
7843: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 7844: foreach my $file (@{$files}) {
1.759 albertel 7845: $file = &declutter_portfile($file);
1.561 banghart 7846: push(@{$current_permissions{$file}},$what);
1.559 banghart 7847: }
1.613 albertel 7848: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 7849: return;
7850: }
7851:
1.572 banghart 7852: # ------------------------------------------------------------Save Selected Files
7853:
7854: sub save_selected_files {
7855: my ($user, $path, @files) = @_;
7856: my $filename = $user."savedfiles";
1.573 banghart 7857: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 7858: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 7859: foreach my $file (@files) {
1.620 albertel 7860: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 7861: }
7862: foreach my $file (@other_files) {
1.574 banghart 7863: print (OUT $file."\n");
1.572 banghart 7864: }
1.574 banghart 7865: close (OUT);
1.572 banghart 7866: return 'ok';
7867: }
7868:
1.574 banghart 7869: sub clear_selected_files {
7870: my ($user) = @_;
7871: my $filename = $user."savedfiles";
1.1117 foxr 7872: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 7873: print (OUT undef);
7874: close (OUT);
7875: return ("ok");
7876: }
7877:
1.572 banghart 7878: sub files_in_path {
7879: my ($user, $path) = @_;
7880: my $filename = $user."savedfiles";
7881: my %return_files;
1.1117 foxr 7882: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 7883: while (my $line_in = <IN>) {
1.574 banghart 7884: chomp ($line_in);
7885: my @paths_and_file = split (m!/!, $line_in);
7886: my $file_part = pop (@paths_and_file);
7887: my $path_part = join ('/', @paths_and_file);
1.573 banghart 7888: $path_part.='/';
7889: my $path_and_file = $path_part.$file_part;
7890: if ($path_part eq $path) {
7891: $return_files{$file_part}= 'selected';
7892: }
7893: }
1.574 banghart 7894: close (IN);
7895: return (\%return_files);
1.572 banghart 7896: }
7897:
7898: # called in portfolio select mode, to show files selected NOT in current directory
7899: sub files_not_in_path {
7900: my ($user, $path) = @_;
7901: my $filename = $user."savedfiles";
7902: my @return_files;
7903: my $path_part;
1.1117 foxr 7904: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 7905: while (my $line = <IN>) {
1.572 banghart 7906: #ok, I know it's clunky, but I want it to work
1.800 albertel 7907: my @paths_and_file = split(m|/|, $line);
7908: my $file_part = pop(@paths_and_file);
7909: chomp($file_part);
7910: my $path_part = join('/', @paths_and_file);
1.572 banghart 7911: $path_part .= '/';
7912: my $path_and_file = $path_part.$file_part;
7913: if ($path_part ne $path) {
1.800 albertel 7914: push(@return_files, ($path_and_file));
1.572 banghart 7915: }
7916: }
1.800 albertel 7917: close(OUT);
1.574 banghart 7918: return (@return_files);
1.572 banghart 7919: }
7920:
1.745 raeburn 7921: #----------------------------------------------Get portfolio file permissions
1.629 banghart 7922:
1.745 raeburn 7923: sub get_portfile_permissions {
7924: my ($domain,$user) = @_;
1.613 albertel 7925: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 7926: my ($tmp)=keys(%current_permissions);
7927: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 7928: return \%current_permissions;
7929: }
7930:
7931: #---------------------------------------------Get portfolio file access controls
7932:
1.749 raeburn 7933: sub get_access_controls {
1.745 raeburn 7934: my ($current_permissions,$group,$file) = @_;
1.769 albertel 7935: my %access;
7936: my $real_file = $file;
7937: $file =~ s/\.meta$//;
1.745 raeburn 7938: if (defined($file)) {
1.749 raeburn 7939: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
7940: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 7941: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 7942: }
7943: }
1.745 raeburn 7944: } else {
1.749 raeburn 7945: foreach my $key (keys(%{$current_permissions})) {
7946: if ($key =~ /\0accesscontrol$/) {
7947: if (defined($group)) {
7948: if ($key !~ m-^\Q$group\E/-) {
7949: next;
7950: }
7951: }
7952: my ($fullpath) = split(/\0/,$key);
7953: if (ref($$current_permissions{$key}) eq 'HASH') {
7954: foreach my $control (keys(%{$$current_permissions{$key}})) {
7955: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
7956: }
7957: }
7958: }
7959: }
7960: }
7961: return %access;
7962: }
7963:
7964: sub modify_access_controls {
7965: my ($file_name,$changes,$domain,$user)=@_;
7966: my ($outcome,$deloutcome);
7967: my %store_permissions;
7968: my %new_values;
7969: my %new_control;
7970: my %translation;
7971: my @deletions = ();
7972: my $now = time;
7973: if (exists($$changes{'activate'})) {
7974: if (ref($$changes{'activate'}) eq 'HASH') {
7975: my @newitems = sort(keys(%{$$changes{'activate'}}));
7976: my $numnew = scalar(@newitems);
7977: for (my $i=0; $i<$numnew; $i++) {
7978: my $newkey = $newitems[$i];
7979: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 7980: if ($newkey =~ /^\d+:/) {
7981: $newkey =~ s/^(\d+)/$newid/;
7982: $translation{$1} = $newid;
7983: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
7984: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
7985: $translation{$1} = $newid;
7986: }
1.749 raeburn 7987: $new_values{$file_name."\0".$newkey} =
7988: $$changes{'activate'}{$newitems[$i]};
7989: $new_control{$newkey} = $now;
7990: }
7991: }
7992: }
7993: my %todelete;
7994: my %changed_items;
7995: foreach my $action ('delete','update') {
7996: if (exists($$changes{$action})) {
7997: if (ref($$changes{$action}) eq 'HASH') {
7998: foreach my $key (keys(%{$$changes{$action}})) {
7999: my ($itemnum) = ($key =~ /^([^:]+):/);
8000: if ($action eq 'delete') {
8001: $todelete{$itemnum} = 1;
8002: } else {
8003: $changed_items{$itemnum} = $key;
8004: }
8005: }
1.745 raeburn 8006: }
8007: }
1.749 raeburn 8008: }
8009: # get lock on access controls for file.
8010: my $lockhash = {
8011: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8012: ':'.$env{'user.domain'},
8013: };
8014: my $tries = 0;
8015: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8016:
8017: while (($gotlock ne 'ok') && $tries <3) {
8018: $tries ++;
8019: sleep 1;
8020: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8021: }
8022: if ($gotlock eq 'ok') {
8023: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8024: my ($tmp)=keys(%curr_permissions);
8025: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8026: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8027: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8028: if (ref($curr_controls) eq 'HASH') {
8029: foreach my $control_item (keys(%{$curr_controls})) {
8030: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8031: if (defined($todelete{$itemnum})) {
8032: push(@deletions,$file_name."\0".$control_item);
8033: } else {
8034: if (defined($changed_items{$itemnum})) {
8035: $new_control{$changed_items{$itemnum}} = $now;
8036: push(@deletions,$file_name."\0".$control_item);
8037: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8038: } else {
8039: $new_control{$control_item} = $$curr_controls{$control_item};
8040: }
8041: }
1.745 raeburn 8042: }
8043: }
8044: }
1.970 raeburn 8045: my ($group);
8046: if (&is_course($domain,$user)) {
8047: ($group,my $file) = split(/\//,$file_name,2);
8048: }
1.749 raeburn 8049: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8050: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8051: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8052: # remove lock
8053: my @del_lock = ($file_name."\0".'locked_access_records');
8054: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8055: my $sqlresult =
1.970 raeburn 8056: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8057: $group);
1.749 raeburn 8058: } else {
8059: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8060: }
1.749 raeburn 8061: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8062: }
8063:
1.827 raeburn 8064: sub make_public_indefinitely {
8065: my ($requrl) = @_;
8066: my $now = time;
8067: my $action = 'activate';
8068: my $aclnum = 0;
8069: if (&is_portfolio_url($requrl)) {
8070: my (undef,$udom,$unum,$file_name,$group) =
8071: &parse_portfolio_url($requrl);
8072: my $current_perms = &get_portfile_permissions($udom,$unum);
8073: my %access_controls = &get_access_controls($current_perms,
8074: $group,$file_name);
8075: foreach my $key (keys(%{$access_controls{$file_name}})) {
8076: my ($num,$scope,$end,$start) =
8077: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8078: if ($scope eq 'public') {
8079: if ($start <= $now && $end == 0) {
8080: $action = 'none';
8081: } else {
8082: $action = 'update';
8083: $aclnum = $num;
8084: }
8085: last;
8086: }
8087: }
8088: if ($action eq 'none') {
8089: return 'ok';
8090: } else {
8091: my %changes;
8092: my $newend = 0;
8093: my $newstart = $now;
8094: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8095: $changes{$action}{$newkey} = {
8096: type => 'public',
8097: time => {
8098: start => $newstart,
8099: end => $newend,
8100: },
8101: };
8102: my ($outcome,$deloutcome,$new_values,$translation) =
8103: &modify_access_controls($file_name,\%changes,$udom,$unum);
8104: return $outcome;
8105: }
8106: } else {
8107: return 'invalid';
8108: }
8109: }
8110:
1.745 raeburn 8111: #------------------------------------------------------Get Marked as Read Only
8112:
8113: sub get_marked_as_readonly {
8114: my ($domain,$user,$what,$group) = @_;
8115: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8116: my @readonly_files;
1.629 banghart 8117: my $cmp1=$what;
8118: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8119: while (my ($file_name,$value) = each(%{$current_permissions})) {
8120: if (defined($group)) {
8121: if ($file_name !~ m-^\Q$group\E/-) {
8122: next;
8123: }
8124: }
1.561 banghart 8125: if (ref($value) eq "ARRAY"){
8126: foreach my $stored_what (@{$value}) {
1.629 banghart 8127: my $cmp2=$stored_what;
1.759 albertel 8128: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8129: $cmp2=join('',@{$stored_what});
1.745 raeburn 8130: }
1.629 banghart 8131: if ($cmp1 eq $cmp2) {
1.561 banghart 8132: push(@readonly_files, $file_name);
1.745 raeburn 8133: last;
1.563 banghart 8134: } elsif (!defined($what)) {
8135: push(@readonly_files, $file_name);
1.745 raeburn 8136: last;
1.561 banghart 8137: }
8138: }
1.745 raeburn 8139: }
1.561 banghart 8140: }
8141: return @readonly_files;
8142: }
1.577 banghart 8143: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8144:
1.577 banghart 8145: sub get_marked_as_readonly_hash {
1.745 raeburn 8146: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8147: my %readonly_files;
1.745 raeburn 8148: while (my ($file_name,$value) = each(%{$current_permissions})) {
8149: if (defined($group)) {
8150: if ($file_name !~ m-^\Q$group\E/-) {
8151: next;
8152: }
8153: }
1.577 banghart 8154: if (ref($value) eq "ARRAY"){
8155: foreach my $stored_what (@{$value}) {
1.745 raeburn 8156: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8157: foreach my $lock_descriptor(@{$stored_what}) {
8158: if ($lock_descriptor eq 'graded') {
8159: $readonly_files{$file_name} = 'graded';
8160: } elsif ($lock_descriptor eq 'handback') {
8161: $readonly_files{$file_name} = 'handback';
8162: } else {
8163: if (!exists($readonly_files{$file_name})) {
8164: $readonly_files{$file_name} = 'locked';
8165: }
8166: }
1.745 raeburn 8167: }
1.750 banghart 8168: }
1.577 banghart 8169: }
8170: }
8171: }
8172: return %readonly_files;
8173: }
1.559 banghart 8174: # ------------------------------------------------------------ Unmark as Read Only
8175:
8176: sub unmark_as_readonly {
1.629 banghart 8177: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8178: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8179: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8180: $file_name = &declutter_portfile($file_name);
1.634 albertel 8181: my $symb_crs = $what;
8182: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8183: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8184: my ($tmp)=keys(%current_permissions);
8185: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8186: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8187: foreach my $file (@readonly_files) {
1.759 albertel 8188: my $clean_file = &declutter_portfile($file);
8189: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8190: my $current_locks = $current_permissions{$file};
1.563 banghart 8191: my @new_locks;
8192: my @del_keys;
8193: if (ref($current_locks) eq "ARRAY"){
8194: foreach my $locker (@{$current_locks}) {
1.632 albertel 8195: my $compare=$locker;
1.749 raeburn 8196: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8197: $compare=join('',@{$locker});
1.746 raeburn 8198: if ($compare ne $symb_crs) {
8199: push(@new_locks, $locker);
8200: }
1.563 banghart 8201: }
8202: }
1.650 albertel 8203: if (scalar(@new_locks) > 0) {
1.563 banghart 8204: $current_permissions{$file} = \@new_locks;
8205: } else {
8206: push(@del_keys, $file);
1.613 albertel 8207: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8208: delete($current_permissions{$file});
1.563 banghart 8209: }
8210: }
1.561 banghart 8211: }
1.613 albertel 8212: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8213: return;
8214: }
1.512 banghart 8215:
1.17 www 8216: # ------------------------------------------------------------ Directory lister
8217:
8218: sub dirlist {
1.955 raeburn 8219: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8220: $uri=~s/^\///;
8221: $uri=~s/\/$//;
1.253 stredwic 8222: my ($udom, $uname);
1.955 raeburn 8223: if ($getuserdir) {
1.253 stredwic 8224: $udom = $userdomain;
8225: $uname = $username;
1.955 raeburn 8226: } else {
8227: (undef,$udom,$uname)=split(/\//,$uri);
8228: if(defined($userdomain)) {
8229: $udom = $userdomain;
8230: }
8231: if(defined($username)) {
8232: $uname = $username;
8233: }
1.253 stredwic 8234: }
1.955 raeburn 8235: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8236:
1.955 raeburn 8237: $dirRoot = $perlvar{'lonDocRoot'};
8238: if (defined($getpropath)) {
8239: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8240: $dirRoot =~ s/\/$//;
1.955 raeburn 8241: } elsif (defined($getuserdir)) {
8242: my $subdir=$uname.'__';
8243: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8244: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8245: ."/$udom/$subdir/$uname";
8246: } elsif (defined($alternateRoot)) {
8247: $dirRoot = $alternateRoot;
1.751 banghart 8248: }
1.253 stredwic 8249:
8250: if($udom) {
8251: if($uname) {
1.955 raeburn 8252: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8253: .$getuserdir.':'.&escape($dirRoot)
1.955 raeburn 8254: .':'.&escape($uname).':'.&escape($udom),
8255: &homeserver($uname,$udom));
8256: if ($listing eq 'unknown_cmd') {
8257: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,
8258: &homeserver($uname,$udom));
8259: } else {
8260: @listing_results = map { &unescape($_); } split(/:/,$listing);
8261: }
1.605 matthew 8262: if ($listing eq 'unknown_cmd') {
1.800 albertel 8263: $listing = &reply('ls:'.$dirRoot.'/'.$uri,
8264: &homeserver($uname,$udom));
1.605 matthew 8265: @listing_results = split(/:/,$listing);
8266: } else {
8267: @listing_results = map { &unescape($_); } split(/:/,$listing);
8268: }
8269: return @listing_results;
1.955 raeburn 8270: } elsif(!$alternateRoot) {
1.800 albertel 8271: my %allusers;
1.841 albertel 8272: my %servers = &get_servers($udom,'library');
1.955 raeburn 8273: foreach my $tryserver (keys(%servers)) {
8274: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8275: &escape($udom),$tryserver);
8276: if ($listing eq 'unknown_cmd') {
8277: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8278: $udom, $tryserver);
8279: } else {
8280: @listing_results = map { &unescape($_); } split(/:/,$listing);
8281: }
1.841 albertel 8282: if ($listing eq 'unknown_cmd') {
8283: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8284: $udom, $tryserver);
8285: @listing_results = split(/:/,$listing);
8286: } else {
8287: @listing_results =
8288: map { &unescape($_); } split(/:/,$listing);
8289: }
8290: if ($listing_results[0] ne 'no_such_dir' &&
8291: $listing_results[0] ne 'empty' &&
8292: $listing_results[0] ne 'con_lost') {
8293: foreach my $line (@listing_results) {
8294: my ($entry) = split(/&/,$line,2);
8295: $allusers{$entry} = 1;
8296: }
8297: }
1.253 stredwic 8298: }
8299: my $alluserstr='';
1.800 albertel 8300: foreach my $user (sort(keys(%allusers))) {
8301: $alluserstr.=$user.'&user:';
1.253 stredwic 8302: }
8303: $alluserstr=~s/:$//;
8304: return split(/:/,$alluserstr);
8305: } else {
1.800 albertel 8306: return ('missing user name');
1.253 stredwic 8307: }
1.955 raeburn 8308: } elsif(!defined($getpropath)) {
1.841 albertel 8309: my @all_domains = sort(&all_domains());
1.955 raeburn 8310: foreach my $domain (@all_domains) {
8311: $domain = $perlvar{'lonDocRoot'}.'/res/'.$domain.'/&domain';
8312: }
8313: return @all_domains;
8314: } else {
1.800 albertel 8315: return ('missing domain');
1.275 stredwic 8316: }
8317: }
8318:
8319: # --------------------------------------------- GetFileTimestamp
8320: # This function utilizes dirlist and returns the date stamp for
8321: # when it was last modified. It will also return an error of -1
8322: # if an error occurs
8323:
8324: sub GetFileTimestamp {
1.955 raeburn 8325: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8326: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8327: $studentName = &LONCAPA::clean_username($studentName);
1.955 raeburn 8328: my ($fileStat) =
8329: &Apache::lonnet::dirlist($filename,$studentDomain,$studentName,
8330: undef,$getuserdir);
1.275 stredwic 8331: my @stats = split('&', $fileStat);
8332: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
1.375 matthew 8333: # @stats contains first the filename, then the stat output
8334: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8335: } else {
8336: return -1;
1.253 stredwic 8337: }
1.26 www 8338: }
8339:
1.712 albertel 8340: sub stat_file {
8341: my ($uri) = @_;
1.787 albertel 8342: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8343:
1.955 raeburn 8344: my ($udom,$uname,$file);
1.712 albertel 8345: if ($uri =~ m-^/(uploaded|editupload)/-) {
8346: ($udom,$uname,$file) =
1.811 albertel 8347: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8348: $file = 'userfiles/'.$file;
8349: }
8350: if ($uri =~ m-^/res/-) {
8351: ($udom,$uname) =
1.807 albertel 8352: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8353: $file = $uri;
8354: }
8355:
8356: if (!$udom || !$uname || !$file) {
8357: # unable to handle the uri
8358: return ();
8359: }
1.956 raeburn 8360: my $getpropath;
8361: if ($file =~ /^userfiles\//) {
8362: $getpropath = 1;
8363: }
1.955 raeburn 8364: my ($result) = &dirlist($file,$udom,$uname,$getpropath);
1.712 albertel 8365: my @stats = split('&', $result);
1.721 banghart 8366:
1.712 albertel 8367: if($stats[0] ne 'empty' && $stats[0] ne 'no_such_dir') {
8368: shift(@stats); #filename is first
8369: return @stats;
8370: }
8371: return ();
8372: }
8373:
1.26 www 8374: # -------------------------------------------------------- Value of a Condition
8375:
1.713 albertel 8376: # gets the value of a specific preevaluated condition
8377: # stored in the string $env{user.state.<cid>}
8378: # or looks up a condition reference in the bighash and if if hasn't
8379: # already been evaluated recurses into docondval to get the value of
8380: # the condition, then memoizing it to
8381: # $env{user.state.<cid>.<condition>}
1.40 www 8382: sub directcondval {
8383: my $number=shift;
1.620 albertel 8384: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8385: &Apache::lonuserstate::evalstate();
8386: }
1.713 albertel 8387: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8388: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8389: } elsif ($number =~ /^_/) {
8390: my $sub_condition;
8391: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8392: &GDBM_READER(),0640)) {
8393: $sub_condition=$bighash{'conditions'.$number};
8394: untie(%bighash);
8395: }
8396: my $value = &docondval($sub_condition);
1.949 raeburn 8397: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8398: return $value;
8399: }
1.620 albertel 8400: if ($env{'user.state.'.$env{'request.course.id'}}) {
8401: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8402: } else {
8403: return 2;
8404: }
8405: }
8406:
1.713 albertel 8407: # get the collection of conditions for this resource
1.26 www 8408: sub condval {
8409: my $condidx=shift;
1.54 www 8410: my $allpathcond='';
1.713 albertel 8411: foreach my $cond (split(/\|/,$condidx)) {
8412: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8413: $allpathcond.=
8414: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8415: }
1.191 harris41 8416: }
1.54 www 8417: $allpathcond=~s/\|$//;
1.713 albertel 8418: return &docondval($allpathcond);
8419: }
8420:
8421: #evaluates an expression of conditions
8422: sub docondval {
8423: my ($allpathcond) = @_;
8424: my $result=0;
8425: if ($env{'request.course.id'}
8426: && defined($allpathcond)) {
8427: my $operand='|';
8428: my @stack;
8429: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8430: if ($chunk eq '(') {
8431: push @stack,($operand,$result);
8432: } elsif ($chunk eq ')') {
8433: my $before=pop @stack;
8434: if (pop @stack eq '&') {
8435: $result=$result>$before?$before:$result;
8436: } else {
8437: $result=$result>$before?$result:$before;
8438: }
8439: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8440: $operand=$chunk;
8441: } else {
8442: my $new=directcondval($chunk);
8443: if ($operand eq '&') {
8444: $result=$result>$new?$new:$result;
8445: } else {
8446: $result=$result>$new?$result:$new;
8447: }
8448: }
8449: }
1.26 www 8450: }
8451: return $result;
1.421 albertel 8452: }
8453:
8454: # ---------------------------------------------------- Devalidate courseresdata
8455:
8456: sub devalidatecourseresdata {
8457: my ($coursenum,$coursedomain)=@_;
8458: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8459: &devalidate_cache_new('courseres',$hashid);
1.28 www 8460: }
8461:
1.763 www 8462:
1.200 www 8463: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8464: #
8465: # Parameters:
8466: # $coursenum - Number of the course.
8467: # $coursedomain - Domain at which the course was created.
8468: # Returns:
8469: # A hash of the course parameters along (I think) with timestamps
8470: # and version info.
1.877 foxr 8471:
1.624 albertel 8472: sub get_courseresdata {
8473: my ($coursenum,$coursedomain)=@_;
1.200 www 8474: my $coursehom=&homeserver($coursenum,$coursedomain);
8475: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8476: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8477: my %dumpreply;
1.417 albertel 8478: unless (defined($cached)) {
1.624 albertel 8479: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8480: $result=\%dumpreply;
1.251 albertel 8481: my ($tmp) = keys(%dumpreply);
8482: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8483: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8484: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8485: return $tmp;
1.416 albertel 8486: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8487: $result=undef;
1.599 albertel 8488: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8489: }
8490: }
1.624 albertel 8491: return $result;
8492: }
8493:
1.633 albertel 8494: sub devalidateuserresdata {
8495: my ($uname,$udom)=@_;
8496: my $hashid="$udom:$uname";
8497: &devalidate_cache_new('userres',$hashid);
8498: }
8499:
1.624 albertel 8500: sub get_userresdata {
8501: my ($uname,$udom)=@_;
8502: #most student don\'t have any data set, check if there is some data
8503: if (&EXT_cache_status($udom,$uname)) { return undef; }
8504:
8505: my $hashid="$udom:$uname";
8506: my ($result,$cached)=&is_cached_new('userres',$hashid);
8507: if (!defined($cached)) {
8508: my %resourcedata=&dump('resourcedata',$udom,$uname);
8509: $result=\%resourcedata;
8510: &do_cache_new('userres',$hashid,$result,600);
8511: }
8512: my ($tmp)=keys(%$result);
8513: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
8514: return $result;
8515: }
8516: #error 2 occurs when the .db doesn't exist
8517: if ($tmp!~/error: 2 /) {
1.672 albertel 8518: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 8519: " Trying to get resource data for ".
8520: $uname." at ".$udom.": ".
8521: $tmp."</font>");
8522: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 8523: #&EXT_cache_set($udom,$uname);
8524: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 8525: undef($tmp); # not really an error so don't send it back
1.624 albertel 8526: }
8527: return $tmp;
8528: }
1.879 foxr 8529: #----------------------------------------------- resdata - return resource data
8530: # Purpose:
8531: # Return resource data for either users or for a course.
8532: # Parameters:
8533: # $name - Course/user name.
8534: # $domain - Name of the domain the user/course is registered on.
8535: # $type - Type of thing $name is (must be 'course' or 'user'
8536: # @which - Array of names of resources desired.
8537: # Returns:
8538: # The value of the first reasource in @which that is found in the
8539: # resource hash.
8540: # Exceptional Conditions:
8541: # If the $type passed in is not valid (not the string 'course' or
8542: # 'user', an undefined reference is returned.
8543: # If none of the resources are found, an undef is returned
1.624 albertel 8544: sub resdata {
8545: my ($name,$domain,$type,@which)=@_;
8546: my $result;
8547: if ($type eq 'course') {
8548: $result=&get_courseresdata($name,$domain);
8549: } elsif ($type eq 'user') {
8550: $result=&get_userresdata($name,$domain);
8551: }
8552: if (!ref($result)) { return $result; }
1.251 albertel 8553: foreach my $item (@which) {
1.927 albertel 8554: if (defined($result->{$item->[0]})) {
8555: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 8556: }
1.250 albertel 8557: }
1.291 albertel 8558: return undef;
1.200 www 8559: }
8560:
1.379 matthew 8561: #
8562: # EXT resource caching routines
8563: #
8564:
8565: sub clear_EXT_cache_status {
1.383 albertel 8566: &delenv('cache.EXT.');
1.379 matthew 8567: }
8568:
8569: sub EXT_cache_status {
8570: my ($target_domain,$target_user) = @_;
1.383 albertel 8571: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 8572: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 8573: # We know already the user has no data
8574: return 1;
8575: } else {
8576: return 0;
8577: }
8578: }
8579:
8580: sub EXT_cache_set {
8581: my ($target_domain,$target_user) = @_;
1.383 albertel 8582: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 8583: #&appenv({$cachename => time});
1.379 matthew 8584: }
8585:
1.28 www 8586: # --------------------------------------------------------- Value of a Variable
1.58 www 8587: sub EXT {
1.715 albertel 8588:
1.395 albertel 8589: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 8590: unless ($varname) { return ''; }
1.218 albertel 8591: #get real user name/domain, courseid and symb
8592: my $courseid;
1.359 albertel 8593: my $publicuser;
1.427 www 8594: if ($symbparm) {
8595: $symbparm=&get_symb_from_alias($symbparm);
8596: }
1.218 albertel 8597: if (!($uname && $udom)) {
1.790 albertel 8598: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 8599: if (!$symbparm) { $symbparm=$cursymb; }
8600: } else {
1.620 albertel 8601: $courseid=$env{'request.course.id'};
1.218 albertel 8602: }
1.48 www 8603: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
8604: my $rest;
1.320 albertel 8605: if (defined($therest[0])) {
1.48 www 8606: $rest=join('.',@therest);
8607: } else {
8608: $rest='';
8609: }
1.320 albertel 8610:
1.57 www 8611: my $qualifierrest=$qualifier;
8612: if ($rest) { $qualifierrest.='.'.$rest; }
8613: my $spacequalifierrest=$space;
8614: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 8615: if ($realm eq 'user') {
1.48 www 8616: # --------------------------------------------------------------- user.resource
8617: if ($space eq 'resource') {
1.651 albertel 8618: if ( (defined($Apache::lonhomework::parsing_a_problem)
8619: || defined($Apache::lonhomework::parsing_a_task))
8620: &&
1.744 albertel 8621: ($symbparm eq &symbread()) ) {
8622: # if we are in the middle of processing the resource the
8623: # get the value we are planning on committing
8624: if (defined($Apache::lonhomework::results{$qualifierrest})) {
8625: return $Apache::lonhomework::results{$qualifierrest};
8626: } else {
8627: return $Apache::lonhomework::history{$qualifierrest};
8628: }
1.335 albertel 8629: } else {
1.359 albertel 8630: my %restored;
1.620 albertel 8631: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 8632: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
8633: } else {
8634: %restored=&restore($symbparm,$courseid,$udom,$uname);
8635: }
1.335 albertel 8636: return $restored{$qualifierrest};
8637: }
1.48 www 8638: # ----------------------------------------------------------------- user.access
8639: } elsif ($space eq 'access') {
1.218 albertel 8640: # FIXME - not supporting calls for a specific user
1.48 www 8641: return &allowed($qualifier,$rest);
8642: # ------------------------------------------ user.preferences, user.environment
8643: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 8644: if (($uname eq $env{'user.name'}) &&
8645: ($udom eq $env{'user.domain'})) {
8646: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 8647: } else {
1.359 albertel 8648: my %returnhash;
8649: if (!$publicuser) {
8650: %returnhash=&userenvironment($udom,$uname,
8651: $qualifierrest);
8652: }
1.218 albertel 8653: return $returnhash{$qualifierrest};
8654: }
1.48 www 8655: # ----------------------------------------------------------------- user.course
8656: } elsif ($space eq 'course') {
1.218 albertel 8657: # FIXME - not supporting calls for a specific user
1.620 albertel 8658: return $env{join('.',('request.course',$qualifier))};
1.48 www 8659: # ------------------------------------------------------------------- user.role
8660: } elsif ($space eq 'role') {
1.218 albertel 8661: # FIXME - not supporting calls for a specific user
1.620 albertel 8662: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 8663: if ($qualifier eq 'value') {
8664: return $role;
8665: } elsif ($qualifier eq 'extent') {
8666: return $where;
8667: }
8668: # ----------------------------------------------------------------- user.domain
8669: } elsif ($space eq 'domain') {
1.218 albertel 8670: return $udom;
1.48 www 8671: # ------------------------------------------------------------------- user.name
8672: } elsif ($space eq 'name') {
1.218 albertel 8673: return $uname;
1.48 www 8674: # ---------------------------------------------------- Any other user namespace
1.29 www 8675: } else {
1.359 albertel 8676: my %reply;
8677: if (!$publicuser) {
8678: %reply=&get($space,[$qualifierrest],$udom,$uname);
8679: }
8680: return $reply{$qualifierrest};
1.48 www 8681: }
1.236 www 8682: } elsif ($realm eq 'query') {
8683: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 8684: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
8685: [$spacequalifierrest]);
1.620 albertel 8686: return $env{'form.'.$spacequalifierrest};
1.236 www 8687: } elsif ($realm eq 'request') {
1.48 www 8688: # ------------------------------------------------------------- request.browser
8689: if ($space eq 'browser') {
1.430 www 8690: if ($qualifier eq 'textremote') {
1.676 albertel 8691: if (&Apache::lonlocal::mt('textual_remote_display') eq 'on') {
1.430 www 8692: return 1;
8693: } else {
8694: return 0;
8695: }
8696: } else {
1.620 albertel 8697: return $env{'browser.'.$qualifier};
1.430 www 8698: }
1.57 www 8699: # ------------------------------------------------------------ request.filename
8700: } else {
1.620 albertel 8701: return $env{'request.'.$spacequalifierrest};
1.29 www 8702: }
1.28 www 8703: } elsif ($realm eq 'course') {
1.48 www 8704: # ---------------------------------------------------------- course.description
1.620 albertel 8705: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 8706: } elsif ($realm eq 'resource') {
1.165 www 8707:
1.620 albertel 8708: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 8709: if (!$symbparm) { $symbparm=&symbread(); }
8710: }
1.693 albertel 8711:
8712: if ($space eq 'title') {
8713: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
8714: return &gettitle($symbparm);
8715: }
8716:
8717: if ($space eq 'map') {
8718: my ($map) = &decode_symb($symbparm);
8719: return &symbread($map);
8720: }
1.905 albertel 8721: if ($space eq 'filename') {
8722: if ($symbparm) {
8723: return &clutter((&decode_symb($symbparm))[2]);
8724: }
8725: return &hreflocation('',$env{'request.filename'});
8726: }
1.693 albertel 8727:
8728: my ($section, $group, @groups);
1.593 albertel 8729: my ($courselevelm,$courselevel);
1.539 albertel 8730: if ($symbparm && defined($courseid) &&
1.620 albertel 8731: $courseid eq $env{'request.course.id'}) {
1.165 www 8732:
1.218 albertel 8733: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 8734:
1.60 www 8735: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 8736: my $symbp=$symbparm;
1.735 albertel 8737: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 8738:
8739: my $symbparm=$symbp.'.'.$spacequalifierrest;
8740: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
8741:
1.620 albertel 8742: if (($env{'user.name'} eq $uname) &&
8743: ($env{'user.domain'} eq $udom)) {
8744: $section=$env{'request.course.sec'};
1.733 raeburn 8745: @groups = split(/:/,$env{'request.course.groups'});
8746: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 8747: } else {
1.539 albertel 8748: if (! defined($usection)) {
1.551 albertel 8749: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 8750: } else {
8751: $section = $usection;
8752: }
1.733 raeburn 8753: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 8754: }
8755:
8756: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
8757: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
8758: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
8759:
1.593 albertel 8760: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 8761: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 8762: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 8763:
1.60 www 8764: # ----------------------------------------------------------- first, check user
1.624 albertel 8765:
8766: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 8767: ([$courselevelr,'resource'],
8768: [$courselevelm,'map' ],
8769: [$courselevel, 'course' ]));
1.931 albertel 8770: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 8771:
1.594 albertel 8772: # ------------------------------------------------ second, check some of course
1.684 raeburn 8773: my $coursereply;
1.691 raeburn 8774: if (@groups > 0) {
8775: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
8776: $mapparm,$spacequalifierrest);
1.927 albertel 8777: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 8778: }
1.96 www 8779:
1.684 raeburn 8780: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 8781: $env{'course.'.$courseid.'.domain'},
8782: 'course',
8783: ([$seclevelr, 'resource'],
8784: [$seclevelm, 'map' ],
8785: [$seclevel, 'course' ],
8786: [$courselevelr,'resource']));
8787: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 8788:
1.60 www 8789: # ------------------------------------------------------ third, check map parms
1.218 albertel 8790: my %parmhash=();
8791: my $thisparm='';
8792: if (tie(%parmhash,'GDBM_File',
1.620 albertel 8793: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 8794: &GDBM_READER(),0640)) {
1.218 albertel 8795: $thisparm=$parmhash{$symbparm};
8796: untie(%parmhash);
8797: }
1.927 albertel 8798: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 8799: }
1.594 albertel 8800: # ------------------------------------------ fourth, look in resource metadata
1.71 www 8801:
1.218 albertel 8802: $spacequalifierrest=~s/\./\_/;
1.282 albertel 8803: my $filename;
8804: if (!$symbparm) { $symbparm=&symbread(); }
8805: if ($symbparm) {
1.409 www 8806: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 8807: } else {
1.620 albertel 8808: $filename=$env{'request.filename'};
1.282 albertel 8809: }
8810: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 8811: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 8812: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 8813: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 8814:
1.927 albertel 8815: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 8816: if ($symbparm && defined($courseid) &&
1.620 albertel 8817: $courseid eq $env{'request.course.id'}) {
1.624 albertel 8818: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
8819: $env{'course.'.$courseid.'.domain'},
8820: 'course',
1.927 albertel 8821: ([$courselevelm,'map' ],
8822: [$courselevel, 'course']));
8823: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 8824: }
1.145 www 8825: # ------------------------------------------------------------------ Cascade up
1.218 albertel 8826: unless ($space eq '0') {
1.336 albertel 8827: my @parts=split(/_/,$space);
8828: my $id=pop(@parts);
8829: my $part=join('_',@parts);
8830: if ($part eq '') { $part='0'; }
1.927 albertel 8831: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 8832: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 8833: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 8834: }
1.395 albertel 8835: if ($recurse) { return undef; }
8836: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 8837: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 8838: # ---------------------------------------------------- Any other user namespace
8839: } elsif ($realm eq 'environment') {
8840: # ----------------------------------------------------------------- environment
1.620 albertel 8841: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
8842: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 8843: } else {
1.770 albertel 8844: if ($uname eq 'anonymous' && $udom eq '') {
8845: return '';
8846: }
1.219 albertel 8847: my %returnhash=&userenvironment($udom,$uname,
8848: $spacequalifierrest);
8849: return $returnhash{$spacequalifierrest};
8850: }
1.28 www 8851: } elsif ($realm eq 'system') {
1.48 www 8852: # ----------------------------------------------------------------- system.time
8853: if ($space eq 'time') {
8854: return time;
8855: }
1.696 albertel 8856: } elsif ($realm eq 'server') {
8857: # ----------------------------------------------------------------- system.time
8858: if ($space eq 'name') {
8859: return $ENV{'SERVER_NAME'};
8860: }
1.28 www 8861: }
1.48 www 8862: return '';
1.61 www 8863: }
8864:
1.927 albertel 8865: sub get_reply {
8866: my ($reply_value) = @_;
1.940 raeburn 8867: if (ref($reply_value) eq 'ARRAY') {
8868: if (wantarray) {
8869: return @$reply_value;
8870: }
8871: return $reply_value->[0];
8872: } else {
8873: return $reply_value;
1.927 albertel 8874: }
8875: }
8876:
1.691 raeburn 8877: sub check_group_parms {
8878: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
8879: my @groupitems = ();
8880: my $resultitem;
1.927 albertel 8881: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 8882: foreach my $group (@{$groups}) {
8883: foreach my $level (@levels) {
1.927 albertel 8884: my $item = $courseid.'.['.$group.'].'.$level->[0];
8885: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 8886: }
8887: }
8888: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
8889: $env{'course.'.$courseid.'.domain'},
8890: 'course',@groupitems);
8891: return $coursereply;
8892: }
8893:
8894: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 8895: my ($courseid,@groups) = @_;
8896: @groups = sort(@groups);
1.691 raeburn 8897: return @groups;
8898: }
8899:
1.395 albertel 8900: sub packages_tab_default {
8901: my ($uri,$varname)=@_;
8902: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 8903:
8904: my (@extension,@specifics,$do_default);
8905: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 8906: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 8907: if ($pack_type eq 'default') {
8908: $do_default=1;
8909: } elsif ($pack_type eq 'extension') {
8910: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 8911: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 8912: # only look at packages defaults for packages that this id is
1.738 albertel 8913: push(@specifics,[$package,$pack_type,$pack_part]);
8914: }
8915: }
8916: # first look for a package that matches the requested part id
8917: foreach my $package (@specifics) {
8918: my (undef,$pack_type,$pack_part)=@{$package};
8919: next if ($pack_part ne $part);
8920: if (defined($packagetab{"$pack_type&$name&default"})) {
8921: return $packagetab{"$pack_type&$name&default"};
8922: }
8923: }
8924: # look for any possible matching non extension_ package
8925: foreach my $package (@specifics) {
8926: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 8927: if (defined($packagetab{"$pack_type&$name&default"})) {
8928: return $packagetab{"$pack_type&$name&default"};
8929: }
1.585 albertel 8930: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 8931: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
8932: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 8933: }
8934: }
1.738 albertel 8935: # look for any posible extension_ match
8936: foreach my $package (@extension) {
8937: my ($package,$pack_type)=@{$package};
8938: if (defined($packagetab{"$pack_type&$name&default"})) {
8939: return $packagetab{"$pack_type&$name&default"};
8940: }
8941: if (defined($packagetab{$package."&$name&default"})) {
8942: return $packagetab{$package."&$name&default"};
8943: }
8944: }
8945: # look for a global default setting
8946: if ($do_default && defined($packagetab{"default&$name&default"})) {
8947: return $packagetab{"default&$name&default"};
8948: }
1.395 albertel 8949: return undef;
8950: }
8951:
1.334 albertel 8952: sub add_prefix_and_part {
8953: my ($prefix,$part)=@_;
8954: my $keyroot;
8955: if (defined($prefix) && $prefix !~ /^__/) {
8956: # prefix that has a part already
8957: $keyroot=$prefix;
8958: } elsif (defined($prefix)) {
8959: # prefix that is missing a part
8960: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
8961: } else {
8962: # no prefix at all
8963: if (defined($part)) { $keyroot='_'.$part; }
8964: }
8965: return $keyroot;
8966: }
8967:
1.71 www 8968: # ---------------------------------------------------------------- Get metadata
8969:
1.599 albertel 8970: my %metaentry;
1.1070 www 8971: my %importedpartids;
1.71 www 8972: sub metadata {
1.176 www 8973: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 8974: $uri=&declutter($uri);
1.288 albertel 8975: # if it is a non metadata possible uri return quickly
1.529 albertel 8976: if (($uri eq '') ||
8977: (($uri =~ m|^/*adm/|) &&
1.698 albertel 8978: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 8979: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 8980: return undef;
8981: }
8982: if (($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/})
8983: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 8984: return undef;
1.288 albertel 8985: }
1.73 www 8986: my $filename=$uri;
8987: $uri=~s/\.meta$//;
1.172 www 8988: #
8989: # Is the metadata already cached?
1.177 www 8990: # Look at timestamp of caching
1.172 www 8991: # Everything is cached by the main uri, libraries are never directly cached
8992: #
1.428 albertel 8993: if (!defined($liburi)) {
1.599 albertel 8994: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 8995: if (defined($cached)) { return $result->{':'.$what}; }
8996: }
8997: {
1.1069 www 8998: # Imported parts would go here
1.1070 www 8999: my %importedids=();
9000: my @origfileimportpartids=();
1.1069 www 9001: my $importedparts=0;
1.172 www 9002: #
9003: # Is this a recursive call for a library?
9004: #
1.599 albertel 9005: # if (! exists($metacache{$uri})) {
9006: # $metacache{$uri}={};
9007: # }
1.924 albertel 9008: my $cachetime = 60*60;
1.171 www 9009: if ($liburi) {
9010: $liburi=&declutter($liburi);
9011: $filename=$liburi;
1.401 bowersj2 9012: } else {
1.599 albertel 9013: &devalidate_cache_new('meta',$uri);
9014: undef(%metaentry);
1.401 bowersj2 9015: }
1.140 www 9016: my %metathesekeys=();
1.73 www 9017: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9018: my $metastring;
1.924 albertel 9019: if ($uri =~ /^~/ || $uri =~ m{home/$match_username/public_html/}) {
1.929 albertel 9020: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9021: $metastring =
1.929 albertel 9022: &Apache::lonnet::ssi_body($which,
1.924 albertel 9023: ('grade_target' => 'meta'));
9024: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9025: } elsif (($uri !~ m -^(editupload)/-) &&
9026: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9027: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9028: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9029: $metastring=&getfile($file);
1.489 albertel 9030: }
1.208 albertel 9031: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9032: my $token;
1.140 www 9033: undef %metathesekeys;
1.71 www 9034: while ($token=$parser->get_token) {
1.339 albertel 9035: if ($token->[0] eq 'S') {
9036: if (defined($token->[2]->{'package'})) {
1.172 www 9037: #
9038: # This is a package - get package info
9039: #
1.339 albertel 9040: my $package=$token->[2]->{'package'};
9041: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9042: if (defined($token->[2]->{'id'})) {
9043: $keyroot.='_'.$token->[2]->{'id'};
9044: }
1.599 albertel 9045: if ($metaentry{':packages'}) {
9046: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9047: } else {
1.599 albertel 9048: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9049: }
1.736 albertel 9050: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9051: my $part=$keyroot;
9052: $part=~s/^\_//;
1.736 albertel 9053: if ($pack_entry=~/^\Q$package\E\&/ ||
9054: $pack_entry=~/^\Q$package\E_0\&/) {
9055: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9056: # ignore package.tab specified default values
9057: # here &package_tab_default() will fetch those
9058: if ($subp eq 'default') { next; }
1.736 albertel 9059: my $value=$packagetab{$pack_entry};
1.432 albertel 9060: my $unikey;
9061: if ($pack =~ /_0$/) {
9062: $unikey='parameter_0_'.$name;
9063: $part=0;
9064: } else {
9065: $unikey='parameter'.$keyroot.'_'.$name;
9066: }
1.339 albertel 9067: if ($subp eq 'display') {
9068: $value.=' [Part: '.$part.']';
9069: }
1.599 albertel 9070: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9071: $metathesekeys{$unikey}=1;
1.599 albertel 9072: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9073: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9074: }
1.599 albertel 9075: if (defined($metaentry{':'.$unikey.'.default'})) {
9076: $metaentry{':'.$unikey}=
9077: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9078: }
1.339 albertel 9079: }
9080: }
9081: } else {
1.172 www 9082: #
9083: # This is not a package - some other kind of start tag
1.339 albertel 9084: #
9085: my $entry=$token->[1];
1.1068 www 9086: my $unikey='';
1.175 www 9087:
1.339 albertel 9088: if ($entry eq 'import') {
1.175 www 9089: #
9090: # Importing a library here
1.339 albertel 9091: #
1.1067 www 9092: my $location=$parser->get_text('/import');
9093: my $dir=$filename;
9094: $dir=~s|[^/]*$||;
9095: $location=&filelocation($dir,$location);
1.1069 www 9096:
1.1068 www 9097: my $importmode=$token->[2]->{'importmode'};
9098: if ($importmode eq 'problem') {
1.1069 www 9099: # Import as problem/response
1.1068 www 9100: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9101: } elsif ($importmode eq 'part') {
9102: # Import as part(s)
1.1069 www 9103: $importedparts=1;
9104: # We need to get the original file and the imported file to get the part order correct
9105: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9106: # Load and inspect original file
1.1070 www 9107: if ($#origfileimportpartids<0) {
9108: undef(%importedpartids);
9109: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9110: my $origfile=&getfile($origfilelocation);
9111: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9112: }
9113:
1.1069 www 9114: # Load and inspect imported file
9115: my $impfile=&getfile($location);
9116: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9117: if ($#impfilepartids>=0) {
9118: # This problem had parts
1.1070 www 9119: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9120: } else {
9121: # Importing by turning a single problem into a problem part
9122: # It gets the import-tags ID as part-ID
9123: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9124: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9125: }
1.1068 www 9126: } else {
9127: # Normal import
9128: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9129: if (defined($token->[2]->{'id'})) {
9130: $unikey.='_'.$token->[2]->{'id'};
9131: }
1.1067 www 9132: }
9133:
1.339 albertel 9134: if ($depthcount<20) {
1.736 albertel 9135: my $metadata =
9136: &metadata($uri,'keys', $location,$unikey,
9137: $depthcount+1);
9138: foreach my $meta (split(',',$metadata)) {
9139: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9140: $metathesekeys{$meta}=1;
1.339 albertel 9141: }
1.1068 www 9142:
9143: }
1.1067 www 9144: } else {
9145: #
9146: # Not importing, some other kind of non-package, non-library start tag
9147: #
9148: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9149: if (defined($token->[2]->{'id'})) {
9150: $unikey.='_'.$token->[2]->{'id'};
9151: }
1.339 albertel 9152: if (defined($token->[2]->{'name'})) {
9153: $unikey.='_'.$token->[2]->{'name'};
9154: }
9155: $metathesekeys{$unikey}=1;
1.736 albertel 9156: foreach my $param (@{$token->[3]}) {
9157: $metaentry{':'.$unikey.'.'.$param} =
9158: $token->[2]->{$param};
1.339 albertel 9159: }
9160: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9161: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9162: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9163: # only ws inside the tag, and not in default, so use default
9164: # as value
1.599 albertel 9165: $metaentry{':'.$unikey}=$default;
1.908 albertel 9166: } elsif ( $internaltext =~ /\S/ ) {
9167: # something interesting inside the tag
9168: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9169: } else {
1.908 albertel 9170: # no interesting values, don't set a default
1.339 albertel 9171: }
1.172 www 9172: # end of not-a-package not-a-library import
1.339 albertel 9173: }
1.172 www 9174: # end of not-a-package start tag
1.339 albertel 9175: }
1.172 www 9176: # the next is the end of "start tag"
1.339 albertel 9177: }
9178: }
1.483 albertel 9179: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9180: $extension = lc($extension);
9181: if ($extension eq 'htm') { $extension='html'; }
9182:
1.737 albertel 9183: foreach my $key (keys(%packagetab)) {
1.483 albertel 9184: #no specific packages #how's our extension
9185: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9186: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9187: \%metathesekeys);
9188: }
1.883 albertel 9189:
9190: if (!exists($metaentry{':packages'})
9191: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9192: foreach my $key (keys(%packagetab)) {
1.483 albertel 9193: #no specific packages well let's get default then
9194: if ($key!~/^default&/) { next; }
1.488 albertel 9195: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9196: \%metathesekeys);
9197: }
9198: }
1.338 www 9199: # are there custom rights to evaluate
1.599 albertel 9200: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9201:
1.338 www 9202: #
9203: # Importing a rights file here
1.339 albertel 9204: #
9205: unless ($depthcount) {
1.599 albertel 9206: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9207: my $dir=$filename;
9208: $dir=~s|[^/]*$||;
9209: $location=&filelocation($dir,$location);
1.736 albertel 9210: my $rights_metadata =
9211: &metadata($uri,'keys',$location,'_rights',
9212: $depthcount+1);
9213: foreach my $rights (split(',',$rights_metadata)) {
9214: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9215: $metathesekeys{$rights}=1;
1.339 albertel 9216: }
9217: }
9218: }
1.737 albertel 9219: # uniqifiy package listing
9220: my %seen;
9221: my @uniq_packages =
9222: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9223: $metaentry{':packages'} = join(',',@uniq_packages);
9224:
1.1070 www 9225: if ($importedparts) {
9226: # We had imported parts and need to rebuild partorder
9227: $metaentry{':partorder'}='';
9228: $metathesekeys{'partorder'}=1;
9229: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9230: if ($origfileimportpartids[$index] eq 'part') {
9231: # original part, part of the problem
9232: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9233: } else {
9234: # we have imported parts at this position
9235: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9236: }
9237: }
9238: $metaentry{':partorder'}=~s/^\,//;
9239: }
9240:
1.737 albertel 9241: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9242: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9243: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9244: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9245: # this is the end of "was not already recently cached
1.71 www 9246: }
1.599 albertel 9247: return $metaentry{':'.$what};
1.261 albertel 9248: }
9249:
1.488 albertel 9250: sub metadata_create_package_def {
1.483 albertel 9251: my ($uri,$key,$package,$metathesekeys)=@_;
9252: my ($pack,$name,$subp)=split(/\&/,$key);
9253: if ($subp eq 'default') { next; }
9254:
1.599 albertel 9255: if (defined($metaentry{':packages'})) {
9256: $metaentry{':packages'}.=','.$package;
1.483 albertel 9257: } else {
1.599 albertel 9258: $metaentry{':packages'}=$package;
1.483 albertel 9259: }
9260: my $value=$packagetab{$key};
9261: my $unikey;
9262: $unikey='parameter_0_'.$name;
1.599 albertel 9263: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9264: $$metathesekeys{$unikey}=1;
1.599 albertel 9265: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9266: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9267: }
1.599 albertel 9268: if (defined($metaentry{':'.$unikey.'.default'})) {
9269: $metaentry{':'.$unikey}=
9270: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9271: }
9272: }
9273:
1.261 albertel 9274: sub metadata_generate_part0 {
9275: my ($metadata,$metacache,$uri) = @_;
9276: my %allnames;
1.737 albertel 9277: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9278: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9279: my $part=$$metacache{':'.$metakey.'.part'};
9280: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9281: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9282: $allnames{$name}=$part;
9283: }
9284: }
9285: }
9286: foreach my $name (keys(%allnames)) {
9287: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9288: my $key=":parameter_0_$name";
1.261 albertel 9289: $$metacache{"$key.part"}='0';
9290: $$metacache{"$key.name"}=$name;
1.428 albertel 9291: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9292: $allnames{$name}.'_'.$name.
9293: '.type'};
1.428 albertel 9294: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9295: '.display'};
1.644 www 9296: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9297: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9298: $$metacache{"$key.display"}=$olddis;
9299: }
1.71 www 9300: }
9301:
1.764 albertel 9302: # ------------------------------------------------------ Devalidate title cache
9303:
9304: sub devalidate_title_cache {
9305: my ($url)=@_;
9306: if (!$env{'request.course.id'}) { return; }
9307: my $symb=&symbread($url);
9308: if (!$symb) { return; }
9309: my $key=$env{'request.course.id'}."\0".$symb;
9310: &devalidate_cache_new('title',$key);
9311: }
9312:
1.1014 droeschl 9313: # ------------------------------------------------- Get the title of a course
9314:
9315: sub current_course_title {
9316: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9317: }
1.301 www 9318: # ------------------------------------------------- Get the title of a resource
9319:
9320: sub gettitle {
9321: my $urlsymb=shift;
9322: my $symb=&symbread($urlsymb);
1.534 albertel 9323: if ($symb) {
1.620 albertel 9324: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9325: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9326: if (defined($cached)) {
9327: return $result;
9328: }
1.534 albertel 9329: my ($map,$resid,$url)=&decode_symb($symb);
9330: my $title='';
1.907 albertel 9331: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9332: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9333: } else {
9334: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9335: &GDBM_READER(),0640)) {
9336: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9337: $title=$bighash{'title_'.$mapid.'.'.$resid};
9338: untie(%bighash);
9339: }
1.534 albertel 9340: }
9341: $title=~s/\&colon\;/\:/gs;
9342: if ($title) {
1.599 albertel 9343: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9344: }
9345: $urlsymb=$url;
9346: }
9347: my $title=&metadata($urlsymb,'title');
9348: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9349: return $title;
1.301 www 9350: }
1.613 albertel 9351:
1.614 albertel 9352: sub get_slot {
9353: my ($which,$cnum,$cdom)=@_;
9354: if (!$cnum || !$cdom) {
1.790 albertel 9355: (undef,my $courseid)=&whichuser();
1.620 albertel 9356: $cdom=$env{'course.'.$courseid.'.domain'};
9357: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9358: }
1.703 albertel 9359: my $key=join("\0",'slots',$cdom,$cnum,$which);
9360: my %slotinfo;
9361: if (exists($remembered{$key})) {
9362: $slotinfo{$which} = $remembered{$key};
9363: } else {
9364: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9365: &Apache::lonhomework::showhash(%slotinfo);
9366: my ($tmp)=keys(%slotinfo);
9367: if ($tmp=~/^error:/) { return (); }
9368: $remembered{$key} = $slotinfo{$which};
9369: }
1.616 albertel 9370: if (ref($slotinfo{$which}) eq 'HASH') {
9371: return %{$slotinfo{$which}};
9372: }
9373: return $slotinfo{$which};
1.614 albertel 9374: }
1.31 www 9375: # ------------------------------------------------- Update symbolic store links
9376:
9377: sub symblist {
9378: my ($mapname,%newhash)=@_;
1.438 www 9379: $mapname=&deversion(&declutter($mapname));
1.31 www 9380: my %hash;
1.620 albertel 9381: if (($env{'request.course.fn'}) && (%newhash)) {
9382: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9383: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9384: foreach my $url (keys(%newhash)) {
1.711 albertel 9385: next if ($url eq 'last_known'
9386: && $env{'form.no_update_last_known'});
9387: $hash{declutter($url)}=&encode_symb($mapname,
9388: $newhash{$url}->[1],
9389: $newhash{$url}->[0]);
1.191 harris41 9390: }
1.31 www 9391: if (untie(%hash)) {
9392: return 'ok';
9393: }
9394: }
9395: }
9396: return 'error';
1.212 www 9397: }
9398:
9399: # --------------------------------------------------------------- Verify a symb
9400:
9401: sub symbverify {
1.510 www 9402: my ($symb,$thisurl)=@_;
9403: my $thisfn=$thisurl;
1.439 www 9404: $thisfn=&declutter($thisfn);
1.215 www 9405: # direct jump to resource in page or to a sequence - will construct own symbs
9406: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9407: # check URL part
1.409 www 9408: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9409:
1.431 www 9410: unless ($url eq $thisfn) { return 0; }
1.213 www 9411:
1.216 www 9412: $symb=&symbclean($symb);
1.510 www 9413: $thisurl=&deversion($thisurl);
1.439 www 9414: $thisfn=&deversion($thisfn);
1.213 www 9415:
9416: my %bighash;
9417: my $okay=0;
1.431 www 9418:
1.620 albertel 9419: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9420: &GDBM_READER(),0640)) {
1.1032 raeburn 9421: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9422: $thisurl =~ s/\?.+$//;
9423: }
1.510 www 9424: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9425: unless ($ids) {
9426: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9427: $ids=$bighash{$idkey};
1.216 www 9428: }
9429: if ($ids) {
9430: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9431: foreach my $id (split(/\,/,$ids)) {
9432: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9433: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
9434: $symb =~ s/\?.+$//;
9435: }
1.216 www 9436: if (
9437: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
9438: eq $symb) {
1.620 albertel 9439: if (($env{'request.role.adv'}) ||
1.1101 raeburn 9440: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
9441: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 9442: $okay=1;
9443: }
9444: }
1.216 www 9445: }
9446: }
1.213 www 9447: untie(%bighash);
9448: }
9449: return $okay;
1.31 www 9450: }
9451:
1.210 www 9452: # --------------------------------------------------------------- Clean-up symb
9453:
9454: sub symbclean {
9455: my $symb=shift;
1.568 albertel 9456: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 9457: # remove version from map
9458: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 9459:
1.210 www 9460: # remove version from URL
9461: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 9462:
1.507 www 9463: # remove wrapper
9464:
1.510 www 9465: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 9466: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 9467: return $symb;
1.409 www 9468: }
9469:
9470: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 9471:
9472: sub encode_symb {
9473: my ($map,$resid,$url)=@_;
9474: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
9475: }
1.409 www 9476:
9477: sub decode_symb {
1.568 albertel 9478: my $symb=shift;
9479: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
9480: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 9481: return (&fixversion($map),$resid,&fixversion($url));
9482: }
9483:
9484: sub fixversion {
9485: my $fn=shift;
1.609 banghart 9486: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 9487: my %bighash;
9488: my $uri=&clutter($fn);
1.620 albertel 9489: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 9490: # is this cached?
1.599 albertel 9491: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 9492: if (defined($cached)) { return $result; }
9493: # unfortunately not cached, or expired
1.620 albertel 9494: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 9495: &GDBM_READER(),0640)) {
9496: if ($bighash{'version_'.$uri}) {
9497: my $version=$bighash{'version_'.$uri};
1.444 www 9498: unless (($version eq 'mostrecent') ||
9499: ($version==&getversion($uri))) {
1.440 www 9500: $uri=~s/\.(\w+)$/\.$version\.$1/;
9501: }
9502: }
9503: untie %bighash;
1.413 www 9504: }
1.599 albertel 9505: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 9506: }
9507:
9508: sub deversion {
9509: my $url=shift;
9510: $url=~s/\.\d+\.(\w+)$/\.$1/;
9511: return $url;
1.210 www 9512: }
9513:
1.31 www 9514: # ------------------------------------------------------ Return symb list entry
9515:
9516: sub symbread {
1.249 www 9517: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 9518: my $cache_str='request.symbread.cached.'.$thisfn;
1.620 albertel 9519: if (defined($env{$cache_str})) { return $env{$cache_str}; }
1.242 www 9520: # no filename provided? try from environment
1.44 www 9521: unless ($thisfn) {
1.620 albertel 9522: if ($env{'request.symb'}) {
9523: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 9524: }
1.620 albertel 9525: $thisfn=$env{'request.filename'};
1.44 www 9526: }
1.569 albertel 9527: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 9528: # is that filename actually a symb? Verify, clean, and return
9529: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 9530: if (&symbverify($thisfn,$1)) {
1.620 albertel 9531: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 9532: }
1.242 www 9533: }
1.44 www 9534: $thisfn=declutter($thisfn);
1.31 www 9535: my %hash;
1.37 www 9536: my %bighash;
9537: my $syval='';
1.620 albertel 9538: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 9539: my $targetfn = $thisfn;
1.609 banghart 9540: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 9541: $targetfn = 'adm/wrapper/'.$thisfn;
9542: }
1.687 albertel 9543: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
9544: $targetfn=$1;
9545: }
1.620 albertel 9546: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9547: &GDBM_READER(),0640)) {
1.481 raeburn 9548: $syval=$hash{$targetfn};
1.37 www 9549: untie(%hash);
9550: }
9551: # ---------------------------------------------------------- There was an entry
9552: if ($syval) {
1.601 albertel 9553: #unless ($syval=~/\_\d+$/) {
1.620 albertel 9554: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 9555: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9556: #return $env{$cache_str}='';
1.601 albertel 9557: #}
9558: #$syval.=$1;
9559: #}
1.37 www 9560: } else {
9561: # ------------------------------------------------------- Was not in symb table
1.620 albertel 9562: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9563: &GDBM_READER(),0640)) {
1.37 www 9564: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 9565: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 9566: unless ($ids) {
9567: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 9568: }
9569: unless ($ids) {
9570: # alias?
9571: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 9572: }
1.37 www 9573: if ($ids) {
9574: # ------------------------------------------------------------------- Has ID(s)
9575: my @possibilities=split(/\,/,$ids);
1.39 www 9576: if ($#possibilities==0) {
9577: # ----------------------------------------------- There is only one possibility
1.37 www 9578: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 9579: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9580: $resid,$thisfn);
1.249 www 9581: } elsif (!$donotrecurse) {
1.39 www 9582: # ------------------------------------------ There is more than one possibility
9583: my $realpossible=0;
1.800 albertel 9584: foreach my $id (@possibilities) {
9585: my $file=$bighash{'src_'.$id};
1.39 www 9586: if (&allowed('bre',$file)) {
1.800 albertel 9587: my ($mapid,$resid)=split(/\./,$id);
1.39 www 9588: if ($bighash{'map_type_'.$mapid} ne 'page') {
9589: $realpossible++;
1.626 albertel 9590: $syval=&encode_symb($bighash{'map_id_'.$mapid},
9591: $resid,$thisfn);
1.39 www 9592: }
9593: }
1.191 harris41 9594: }
1.39 www 9595: if ($realpossible!=1) { $syval=''; }
1.249 www 9596: } else {
9597: $syval='';
1.37 www 9598: }
9599: }
9600: untie(%bighash)
1.481 raeburn 9601: }
1.31 www 9602: }
1.62 www 9603: if ($syval) {
1.620 albertel 9604: return $env{$cache_str}=$syval;
1.62 www 9605: }
1.31 www 9606: }
1.949 raeburn 9607: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 9608: return $env{$cache_str}='';
1.31 www 9609: }
9610:
9611: # ---------------------------------------------------------- Return random seed
9612:
1.32 www 9613: sub numval {
9614: my $txt=shift;
9615: $txt=~tr/A-J/0-9/;
9616: $txt=~tr/a-j/0-9/;
9617: $txt=~tr/K-T/0-9/;
9618: $txt=~tr/k-t/0-9/;
9619: $txt=~tr/U-Z/0-5/;
9620: $txt=~tr/u-z/0-5/;
9621: $txt=~s/\D//g;
1.564 albertel 9622: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 9623: return int($txt);
1.368 albertel 9624: }
9625:
1.484 albertel 9626: sub numval2 {
9627: my $txt=shift;
9628: $txt=~tr/A-J/0-9/;
9629: $txt=~tr/a-j/0-9/;
9630: $txt=~tr/K-T/0-9/;
9631: $txt=~tr/k-t/0-9/;
9632: $txt=~tr/U-Z/0-5/;
9633: $txt=~tr/u-z/0-5/;
9634: $txt=~s/\D//g;
9635: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9636: my $total;
9637: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 9638: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 9639: return int($total);
9640: }
9641:
1.575 albertel 9642: sub numval3 {
9643: use integer;
9644: my $txt=shift;
9645: $txt=~tr/A-J/0-9/;
9646: $txt=~tr/a-j/0-9/;
9647: $txt=~tr/K-T/0-9/;
9648: $txt=~tr/k-t/0-9/;
9649: $txt=~tr/U-Z/0-5/;
9650: $txt=~tr/u-z/0-5/;
9651: $txt=~s/\D//g;
9652: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
9653: my $total;
9654: foreach my $val (@txts) { $total+=$val; }
9655: if ($_64bit) { $total=(($total<<32)>>32); }
9656: return $total;
9657: }
9658:
1.675 albertel 9659: sub digest {
9660: my ($data)=@_;
9661: my $digest=&Digest::MD5::md5($data);
9662: my ($a,$b,$c,$d)=unpack("iiii",$digest);
9663: my ($e,$f);
9664: {
9665: use integer;
9666: $e=($a+$b);
9667: $f=($c+$d);
9668: if ($_64bit) {
9669: $e=(($e<<32)>>32);
9670: $f=(($f<<32)>>32);
9671: }
9672: }
9673: if (wantarray) {
9674: return ($e,$f);
9675: } else {
9676: my $g;
9677: {
9678: use integer;
9679: $g=($e+$f);
9680: if ($_64bit) {
9681: $g=(($g<<32)>>32);
9682: }
9683: }
9684: return $g;
9685: }
9686: }
9687:
1.368 albertel 9688: sub latest_rnd_algorithm_id {
1.675 albertel 9689: return '64bit5';
1.366 albertel 9690: }
1.32 www 9691:
1.503 albertel 9692: sub get_rand_alg {
9693: my ($courseid)=@_;
1.790 albertel 9694: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 9695: if ($courseid) {
1.620 albertel 9696: return $env{"course.$courseid.rndseed"};
1.503 albertel 9697: }
9698: return &latest_rnd_algorithm_id();
9699: }
9700:
1.562 albertel 9701: sub validCODE {
9702: my ($CODE)=@_;
9703: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
9704: return 0;
9705: }
9706:
1.491 albertel 9707: sub getCODE {
1.620 albertel 9708: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 9709: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
9710: defined($Apache::lonhomework::parsing_a_task) ) &&
9711: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 9712: return $Apache::lonhomework::history{'resource.CODE'};
9713: }
9714: return undef;
9715: }
1.1133 ! foxr 9716: #
! 9717: # Determines the random seed for a specific context:
! 9718: #
! 9719: # parameters:
! 9720: # symb - in course context the symb for the seed.
! 9721: # course_id - The course id of the form domain_coursenum.
! 9722: # domain - Domain for the user.
! 9723: # course - Course for the user.
! 9724: # cenv - environment of the course.
! 9725: #
! 9726: # NOTE:
! 9727: # All parameters are picked out of the environment if missing
! 9728: # or not defined.
! 9729: # If a symb cannot be determined the current time is used instead.
! 9730: #
! 9731: # For a given well defined symb, courside, domain, username,
! 9732: # and course environment, the seed is reproducible.
! 9733: #
1.31 www 9734: sub rndseed {
1.1133 ! foxr 9735: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 9736: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 9737: if (!defined($symb)) {
1.366 albertel 9738: unless ($symb=$wsymb) { return time; }
9739: }
9740: if (!$courseid) { $courseid=$wcourseid; }
9741: if (!$domain) { $domain=$wdomain; }
9742: if (!$username) { $username=$wusername }
1.1133 ! foxr 9743:
! 9744: my $which;
! 9745: if (defined($cenv->{'rndseed'})) {
! 9746: $which = $cenv->{'rndseed'};
! 9747: } else {
! 9748: $which =&get_rand_alg($courseid);
! 9749: }
1.1110 www 9750:
1.491 albertel 9751: if (defined(&getCODE())) {
1.1133 ! foxr 9752:
1.675 albertel 9753: if ($which eq '64bit5') {
9754: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
9755: } elsif ($which eq '64bit4') {
1.575 albertel 9756: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
9757: } else {
9758: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
9759: }
1.675 albertel 9760: } elsif ($which eq '64bit5') {
9761: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 9762: } elsif ($which eq '64bit4') {
9763: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 9764: } elsif ($which eq '64bit3') {
9765: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 9766: } elsif ($which eq '64bit2') {
9767: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 9768: } elsif ($which eq '64bit') {
9769: return &rndseed_64bit($symb,$courseid,$domain,$username);
9770: }
9771: return &rndseed_32bit($symb,$courseid,$domain,$username);
9772: }
9773:
9774: sub rndseed_32bit {
9775: my ($symb,$courseid,$domain,$username)=@_;
9776: {
9777: use integer;
9778: my $symbchck=unpack("%32C*",$symb) << 27;
9779: my $symbseed=numval($symb) << 22;
9780: my $namechck=unpack("%32C*",$username) << 17;
9781: my $nameseed=numval($username) << 12;
9782: my $domainseed=unpack("%32C*",$domain) << 7;
9783: my $courseseed=unpack("%32C*",$courseid);
9784: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 9785: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9786: #&logthis("rndseed :$num:$symb");
1.564 albertel 9787: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 9788: return $num;
9789: }
9790: }
9791:
9792: sub rndseed_64bit {
9793: my ($symb,$courseid,$domain,$username)=@_;
9794: {
9795: use integer;
9796: my $symbchck=unpack("%32S*",$symb) << 21;
9797: my $symbseed=numval($symb) << 10;
9798: my $namechck=unpack("%32S*",$username);
9799:
9800: my $nameseed=numval($username) << 21;
9801: my $domainseed=unpack("%32S*",$domain) << 10;
9802: my $courseseed=unpack("%32S*",$courseid);
9803:
9804: my $num1=$symbchck+$symbseed+$namechck;
9805: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9806: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9807: #&logthis("rndseed :$num:$symb");
1.564 albertel 9808: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 9809: return "$num1,$num2";
1.155 albertel 9810: }
1.366 albertel 9811: }
9812:
1.443 albertel 9813: sub rndseed_64bit2 {
9814: my ($symb,$courseid,$domain,$username)=@_;
9815: {
9816: use integer;
9817: # strings need to be an even # of cahracters long, it it is odd the
9818: # last characters gets thrown away
9819: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9820: my $symbseed=numval($symb) << 10;
9821: my $namechck=unpack("%32S*",$username.' ');
9822:
9823: my $nameseed=numval($username) << 21;
1.501 albertel 9824: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9825: my $courseseed=unpack("%32S*",$courseid.' ');
9826:
9827: my $num1=$symbchck+$symbseed+$namechck;
9828: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9829: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9830: #&logthis("rndseed :$num:$symb");
1.803 albertel 9831: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 9832: return "$num1,$num2";
9833: }
9834: }
9835:
9836: sub rndseed_64bit3 {
9837: my ($symb,$courseid,$domain,$username)=@_;
9838: {
9839: use integer;
9840: # strings need to be an even # of cahracters long, it it is odd the
9841: # last characters gets thrown away
9842: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9843: my $symbseed=numval2($symb) << 10;
9844: my $namechck=unpack("%32S*",$username.' ');
9845:
9846: my $nameseed=numval2($username) << 21;
1.443 albertel 9847: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9848: my $courseseed=unpack("%32S*",$courseid.' ');
9849:
9850: my $num1=$symbchck+$symbseed+$namechck;
9851: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9852: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9853: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 9854: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9855:
1.503 albertel 9856: return "$num1:$num2";
1.443 albertel 9857: }
9858: }
9859:
1.575 albertel 9860: sub rndseed_64bit4 {
9861: my ($symb,$courseid,$domain,$username)=@_;
9862: {
9863: use integer;
9864: # strings need to be an even # of cahracters long, it it is odd the
9865: # last characters gets thrown away
9866: my $symbchck=unpack("%32S*",$symb.' ') << 21;
9867: my $symbseed=numval3($symb) << 10;
9868: my $namechck=unpack("%32S*",$username.' ');
9869:
9870: my $nameseed=numval3($username) << 21;
9871: my $domainseed=unpack("%32S*",$domain.' ') << 10;
9872: my $courseseed=unpack("%32S*",$courseid.' ');
9873:
9874: my $num1=$symbchck+$symbseed+$namechck;
9875: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 9876: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
9877: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 9878: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 9879:
1.575 albertel 9880: return "$num1:$num2";
9881: }
9882: }
9883:
1.675 albertel 9884: sub rndseed_64bit5 {
9885: my ($symb,$courseid,$domain,$username)=@_;
9886: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
9887: return "$num1:$num2";
9888: }
9889:
1.366 albertel 9890: sub rndseed_CODE_64bit {
9891: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 9892: {
1.366 albertel 9893: use integer;
1.443 albertel 9894: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 9895: my $symbseed=numval2($symb);
1.491 albertel 9896: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9897: my $CODEseed=numval(&getCODE());
1.443 albertel 9898: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 9899: my $num1=$symbseed+$CODEchck;
9900: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9901: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9902: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 9903: if ($_64bit) { $num1=(($num1<<32)>>32); }
9904: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 9905: return "$num1:$num2";
1.366 albertel 9906: }
9907: }
9908:
1.575 albertel 9909: sub rndseed_CODE_64bit4 {
9910: my ($symb,$courseid,$domain,$username)=@_;
9911: {
9912: use integer;
9913: my $symbchck=unpack("%32S*",$symb.' ') << 16;
9914: my $symbseed=numval3($symb);
9915: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
9916: my $CODEseed=numval3(&getCODE());
9917: my $courseseed=unpack("%32S*",$courseid.' ');
9918: my $num1=$symbseed+$CODEchck;
9919: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 9920: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
9921: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 9922: if ($_64bit) { $num1=(($num1<<32)>>32); }
9923: if ($_64bit) { $num2=(($num2<<32)>>32); }
9924: return "$num1:$num2";
9925: }
9926: }
9927:
1.675 albertel 9928: sub rndseed_CODE_64bit5 {
9929: my ($symb,$courseid,$domain,$username)=@_;
9930: my $code = &getCODE();
9931: my ($num1,$num2)=&digest("$symb,$courseid,$code");
9932: return "$num1:$num2";
9933: }
9934:
1.366 albertel 9935: sub setup_random_from_rndseed {
9936: my ($rndseed)=@_;
1.503 albertel 9937: if ($rndseed =~/([,:])/) {
9938: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 9939: &Math::Random::random_set_seed(abs($num1),abs($num2));
9940: } else {
9941: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 9942: }
1.36 albertel 9943: }
9944:
1.474 albertel 9945: sub latest_receipt_algorithm_id {
1.835 albertel 9946: return 'receipt3';
1.474 albertel 9947: }
9948:
1.480 www 9949: sub recunique {
9950: my $fucourseid=shift;
9951: my $unique;
1.835 albertel 9952: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
9953: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9954: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 9955: } else {
9956: $unique=$perlvar{'lonReceipt'};
9957: }
9958: return unpack("%32C*",$unique);
9959: }
9960:
9961: sub recprefix {
9962: my $fucourseid=shift;
9963: my $prefix;
1.835 albertel 9964: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
9965: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 9966: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 9967: } else {
9968: $prefix=$perlvar{'lonHostID'};
9969: }
9970: return unpack("%32C*",$prefix);
9971: }
9972:
1.76 www 9973: sub ireceipt {
1.474 albertel 9974: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 9975:
9976: my $return =&recprefix($fucourseid).'-';
9977:
9978: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
9979: $env{'request.state'} eq 'construct') {
9980: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
9981: return $return;
9982: }
9983:
1.76 www 9984: my $cuname=unpack("%32C*",$funame);
9985: my $cudom=unpack("%32C*",$fudom);
9986: my $cucourseid=unpack("%32C*",$fucourseid);
9987: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 9988: my $cunique=&recunique($fucourseid);
1.474 albertel 9989: my $cpart=unpack("%32S*",$part);
1.835 albertel 9990: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
9991:
1.790 albertel 9992: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 9993:
9994: $return.= ($cunique%$cuname+
9995: $cunique%$cudom+
9996: $cusymb%$cuname+
9997: $cusymb%$cudom+
9998: $cucourseid%$cuname+
9999: $cucourseid%$cudom+
10000: $cpart%$cuname+
10001: $cpart%$cudom);
10002: } else {
10003: $return.= ($cunique%$cuname+
10004: $cunique%$cudom+
10005: $cusymb%$cuname+
10006: $cusymb%$cudom+
10007: $cucourseid%$cuname+
10008: $cucourseid%$cudom);
10009: }
10010: return $return;
1.76 www 10011: }
10012:
10013: sub receipt {
1.474 albertel 10014: my ($part)=@_;
1.790 albertel 10015: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10016: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10017: }
1.260 ng 10018:
1.790 albertel 10019: sub whichuser {
10020: my ($passedsymb)=@_;
10021: my ($symb,$courseid,$domain,$name,$publicuser);
10022: if (defined($env{'form.grade_symb'})) {
10023: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10024: my $allowed=&allowed('vgr',$tmp_courseid);
10025: if (!$allowed &&
10026: exists($env{'request.course.sec'}) &&
10027: $env{'request.course.sec'} !~ /^\s*$/) {
10028: $allowed=&allowed('vgr',$tmp_courseid.
10029: '/'.$env{'request.course.sec'});
10030: }
10031: if ($allowed) {
10032: ($symb)=&get_env_multiple('form.grade_symb');
10033: $courseid=$tmp_courseid;
10034: ($domain)=&get_env_multiple('form.grade_domain');
10035: ($name)=&get_env_multiple('form.grade_username');
10036: return ($symb,$courseid,$domain,$name,$publicuser);
10037: }
10038: }
10039: if (!$passedsymb) {
10040: $symb=&symbread();
10041: } else {
10042: $symb=$passedsymb;
10043: }
10044: $courseid=$env{'request.course.id'};
10045: $domain=$env{'user.domain'};
10046: $name=$env{'user.name'};
10047: if ($name eq 'public' && $domain eq 'public') {
10048: if (!defined($env{'form.username'})) {
10049: $env{'form.username'}.=time.rand(10000000);
10050: }
10051: $name.=$env{'form.username'};
10052: }
10053: return ($symb,$courseid,$domain,$name,$publicuser);
10054:
10055: }
10056:
1.36 albertel 10057: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10058: # returns either the contents of the file or
10059: # -1 if the file doesn't exist
1.481 raeburn 10060: #
10061: # if the target is a file that was uploaded via DOCS,
10062: # a check will be made to see if a current copy exists on the local server,
10063: # if it does this will be served, otherwise a copy will be retrieved from
10064: # the home server for the course and stored in /home/httpd/html/userfiles on
10065: # the local server.
1.472 albertel 10066:
1.36 albertel 10067: sub getfile {
1.538 albertel 10068: my ($file) = @_;
1.609 banghart 10069: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10070: &repcopy($file);
10071: return &readfile($file);
10072: }
10073:
10074: sub repcopy_userfile {
10075: my ($file)=@_;
1.609 banghart 10076: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.610 albertel 10077: if ($file =~ m|^/home/httpd/html/lonUsers/|) { return 'ok'; }
1.538 albertel 10078: my ($cdom,$cnum,$filename) =
1.811 albertel 10079: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10080: my $uri="/uploaded/$cdom/$cnum/$filename";
10081: if (-e "$file") {
1.828 www 10082: # we already have a local copy, check it out
1.538 albertel 10083: my @fileinfo = stat($file);
1.828 www 10084: my $rtncode;
10085: my $info;
1.538 albertel 10086: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10087: if ($lwpresp ne 'ok') {
1.828 www 10088: # there is no such file anymore, even though we had a local copy
1.482 albertel 10089: if ($rtncode eq '404') {
1.538 albertel 10090: unlink($file);
1.482 albertel 10091: }
10092: return -1;
10093: }
10094: if ($info < $fileinfo[9]) {
1.828 www 10095: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10096: return 'ok';
1.828 www 10097: } else {
10098: # the file is outdated, get rid of it
10099: unlink($file);
1.482 albertel 10100: }
1.828 www 10101: }
10102: # one way or the other, at this point, we don't have the file
10103: # construct the correct path for the file
10104: my @parts = ($cdom,$cnum);
10105: if ($filename =~ m|^(.+)/[^/]+$|) {
10106: push @parts, split(/\//,$1);
10107: }
10108: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10109: foreach my $part (@parts) {
10110: $path .= '/'.$part;
10111: if (!-e $path) {
10112: mkdir($path,0770);
1.482 albertel 10113: }
10114: }
1.828 www 10115: # now the path exists for sure
10116: # get a user agent
10117: my $ua=new LWP::UserAgent;
10118: my $transferfile=$file.'.in.transfer';
10119: # FIXME: this should flock
10120: if (-e $transferfile) { return 'ok'; }
10121: my $request;
10122: $uri=~s/^\///;
1.980 raeburn 10123: my $homeserver = &homeserver($cnum,$cdom);
10124: my $protocol = $protocol{$homeserver};
10125: $protocol = 'http' if ($protocol ne 'https');
10126: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10127: my $response=$ua->request($request,$transferfile);
10128: # did it work?
10129: if ($response->is_error()) {
10130: unlink($transferfile);
10131: &logthis("Userfile repcopy failed for $uri");
10132: return -1;
10133: }
10134: # worked, rename the transfer file
10135: rename($transferfile,$file);
1.607 raeburn 10136: return 'ok';
1.481 raeburn 10137: }
10138:
1.517 albertel 10139: sub tokenwrapper {
10140: my $uri=shift;
1.980 raeburn 10141: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10142: $uri=~s|^/||;
1.620 albertel 10143: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10144: my $token=$1;
1.552 albertel 10145: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10146: if ($udom && $uname && $file) {
10147: $file=~s|(\?\.*)*$||;
1.949 raeburn 10148: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10149: my $homeserver = &homeserver($uname,$udom);
10150: my $protocol = $protocol{$homeserver};
10151: $protocol = 'http' if ($protocol ne 'https');
10152: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10153: (($uri=~/\?/)?'&':'?').'token='.$token.
10154: '&tokenissued='.$perlvar{'lonHostID'};
10155: } else {
10156: return '/adm/notfound.html';
10157: }
10158: }
10159:
1.828 www 10160: # call with reqtype HEAD: get last modification time
10161: # call with reqtype GET: get the file contents
10162: # Do not call this with reqtype GET for large files! It loads everything into memory
10163: #
1.481 raeburn 10164: sub getuploaded {
10165: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10166: $uri=~s/^\///;
1.980 raeburn 10167: my $homeserver = &homeserver($cnum,$cdom);
10168: my $protocol = $protocol{$homeserver};
10169: $protocol = 'http' if ($protocol ne 'https');
10170: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10171: my $ua=new LWP::UserAgent;
10172: my $request=new HTTP::Request($reqtype,$uri);
10173: my $response=$ua->request($request);
10174: $$rtncode = $response->code;
1.482 albertel 10175: if (! $response->is_success()) {
10176: return 'failed';
10177: }
10178: if ($reqtype eq 'HEAD') {
1.486 www 10179: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10180: } elsif ($reqtype eq 'GET') {
10181: $$info = $response->content;
1.472 albertel 10182: }
1.482 albertel 10183: return 'ok';
1.36 albertel 10184: }
10185:
1.481 raeburn 10186: sub readfile {
10187: my $file = shift;
10188: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10189: my $fh;
10190: open($fh,"<$file");
10191: my $a='';
1.800 albertel 10192: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10193: return $a;
10194: }
10195:
1.36 albertel 10196: sub filelocation {
1.590 banghart 10197: my ($dir,$file) = @_;
10198: my $location;
10199: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10200:
10201: if ($file =~ m-^/adm/-) {
10202: $file=~s-^/adm/wrapper/-/-;
10203: $file=~s-^/adm/coursedocs/showdoc/-/-;
10204: }
1.882 albertel 10205:
1.590 banghart 10206: if ($file=~m:^/~:) { # is a contruction space reference
10207: $location = $file;
10208: $location =~ s:/~(.*?)/(.*):/home/$1/public_html/$2:;
1.807 albertel 10209: } elsif ($file=~m{^/home/$match_username/public_html/}) {
1.649 albertel 10210: # is a correct contruction space reference
10211: $location = $file;
1.956 raeburn 10212: } elsif ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
10213: $location = $file;
1.609 banghart 10214: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10215: my ($udom,$uname,$filename)=
1.811 albertel 10216: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10217: my $home=&homeserver($uname,$udom);
10218: my $is_me=0;
10219: my @ids=¤t_machine_ids();
10220: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10221: if ($is_me) {
1.1117 foxr 10222: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10223: } else {
10224: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10225: $udom.'/'.$uname.'/'.$filename;
10226: }
1.882 albertel 10227: } elsif ($file =~ m-^/adm/-) {
10228: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10229: } else {
10230: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
10231: $file=~s:^/res/:/:;
10232: if ( !( $file =~ m:^/:) ) {
10233: $location = $dir. '/'.$file;
10234: } else {
10235: $location = '/home/httpd/html/res'.$file;
10236: }
1.59 albertel 10237: }
1.590 banghart 10238: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10239: while ($location=~m{/\.\./}) {
10240: if ($location =~ m{/[^/]+/\.\./}) {
10241: $location=~ s{/[^/]+/\.\./}{/}g;
10242: } else {
10243: $location=~ s{/\.\./}{/}g;
10244: }
10245: } #remove dir/..
1.590 banghart 10246: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10247: return $location;
1.46 www 10248: }
1.36 albertel 10249:
1.46 www 10250: sub hreflocation {
10251: my ($dir,$file)=@_;
1.980 raeburn 10252: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10253: $file=filelocation($dir,$file);
1.700 albertel 10254: } elsif ($file=~m-^/adm/-) {
10255: $file=~s-^/adm/wrapper/-/-;
10256: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10257: }
10258: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10259: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
1.807 albertel 10260: } elsif ($file=~m-/home/($match_username)/public_html/-) {
10261: $file=~s-^/home/($match_username)/public_html/-/~$1/-;
1.666 albertel 10262: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.811 albertel 10263: $file=~s-^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/
1.666 albertel 10264: -/uploaded/$1/$2/-x;
1.46 www 10265: }
1.913 albertel 10266: if ($file=~ m{^/userfiles/}) {
10267: $file =~ s{^/userfiles/}{/uploaded/};
10268: }
1.462 albertel 10269: return $file;
1.465 albertel 10270: }
10271:
10272: sub current_machine_domains {
1.853 albertel 10273: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10274: }
10275:
10276: sub machine_domains {
10277: my ($hostname) = @_;
1.465 albertel 10278: my @domains;
1.838 albertel 10279: my %hostname = &all_hostnames();
1.465 albertel 10280: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10281: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10282: if ($hostname eq $name) {
1.844 albertel 10283: push(@domains,&host_domain($id));
1.465 albertel 10284: }
10285: }
10286: return @domains;
10287: }
10288:
10289: sub current_machine_ids {
1.853 albertel 10290: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10291: }
10292:
10293: sub machine_ids {
10294: my ($hostname) = @_;
10295: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10296: my @ids;
1.888 albertel 10297: my %name_to_host = &all_names();
1.889 albertel 10298: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10299: return @{ $name_to_host{$hostname} };
10300: }
10301: return;
1.31 www 10302: }
10303:
1.824 raeburn 10304: sub additional_machine_domains {
10305: my @domains;
10306: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10307: while( my $line = <$fh>) {
10308: $line =~ s/\s//g;
10309: push(@domains,$line);
10310: }
10311: return @domains;
10312: }
10313:
10314: sub default_login_domain {
10315: my $domain = $perlvar{'lonDefDomain'};
10316: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10317: foreach my $posdom (¤t_machine_domains(),
10318: &additional_machine_domains()) {
10319: if (lc($posdom) eq lc($testdomain)) {
10320: $domain=$posdom;
10321: last;
10322: }
10323: }
10324: return $domain;
10325: }
10326:
1.31 www 10327: # ------------------------------------------------------------- Declutters URLs
10328:
10329: sub declutter {
10330: my $thisfn=shift;
1.569 albertel 10331: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10332: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10333: $thisfn=~s/^\///;
1.697 albertel 10334: $thisfn=~s|^adm/wrapper/||;
10335: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10336: $thisfn=~s/^res\///;
1.1032 raeburn 10337: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10338: $thisfn=~s/\?.+$//;
10339: }
1.268 www 10340: return $thisfn;
10341: }
10342:
10343: # ------------------------------------------------------------- Clutter up URLs
10344:
10345: sub clutter {
10346: my $thisfn='/'.&declutter(shift);
1.887 albertel 10347: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10348: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10349: $thisfn='/res'.$thisfn;
10350: }
1.1031 raeburn 10351: if ($thisfn !~m|^/adm|) {
10352: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10353: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10354: } else {
10355: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10356: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10357: if ($embstyle eq 'ssi'
10358: || ($embstyle eq 'hdn')
10359: || ($embstyle eq 'rat')
10360: || ($embstyle eq 'prv')
10361: || ($embstyle eq 'ign')) {
10362: #do nothing with these
10363: } elsif (($embstyle eq 'img')
1.695 albertel 10364: || ($embstyle eq 'emb')
10365: || ($embstyle eq 'wrp')) {
10366: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10367: } elsif ($embstyle eq 'unk'
10368: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10369: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10370: } else {
1.718 www 10371: # &logthis("Got a blank emb style");
1.695 albertel 10372: }
1.694 albertel 10373: }
10374: }
1.31 www 10375: return $thisfn;
1.12 www 10376: }
10377:
1.787 albertel 10378: sub clutter_with_no_wrapper {
10379: my $uri = &clutter(shift);
10380: if ($uri =~ m-^/adm/-) {
10381: $uri =~ s-^/adm/wrapper/-/-;
10382: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10383: }
10384: return $uri;
10385: }
10386:
1.557 albertel 10387: sub freeze_escape {
10388: my ($value)=@_;
10389: if (ref($value)) {
10390: $value=&nfreeze($value);
10391: return '__FROZEN__'.&escape($value);
10392: }
10393: return &escape($value);
10394: }
10395:
1.11 www 10396:
1.557 albertel 10397: sub thaw_unescape {
10398: my ($value)=@_;
10399: if ($value =~ /^__FROZEN__/) {
10400: substr($value,0,10,undef);
10401: $value=&unescape($value);
10402: return &thaw($value);
10403: }
10404: return &unescape($value);
10405: }
10406:
1.436 albertel 10407: sub correct_line_ends {
10408: my ($result)=@_;
10409: $$result =~s/\r\n/\n/mg;
10410: $$result =~s/\r/\n/mg;
1.415 albertel 10411: }
1.1 albertel 10412: # ================================================================ Main Program
10413:
1.184 www 10414: sub goodbye {
1.204 albertel 10415: &logthis("Starting Shut down");
1.443 albertel 10416: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10417: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10418: #converted
1.599 albertel 10419: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10420: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10421: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10422: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10423: #1.1 only
1.870 albertel 10424: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10425: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10426: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10427: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10428: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10429: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
10430: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 10431: &flushcourselogs();
10432: &logthis("Shutting down");
10433: }
10434:
1.852 albertel 10435: sub get_dns {
1.869 albertel 10436: my ($url,$func,$ignore_cache) = @_;
10437: if (!$ignore_cache) {
10438: my ($content,$cached)=
10439: &Apache::lonnet::is_cached_new('dns',$url);
10440: if ($cached) {
10441: &$func($content);
10442: return;
10443: }
10444: }
10445:
10446: my %alldns;
1.852 albertel 10447: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10448: foreach my $dns (<$config>) {
10449: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 10450: my $line = $1;
10451: my ($host,$protocol) = split(/:/,$line);
10452: if ($protocol ne 'https') {
10453: $protocol = 'http';
10454: }
10455: $alldns{$host} = $protocol;
1.869 albertel 10456: }
10457: while (%alldns) {
10458: my ($dns) = keys(%alldns);
1.852 albertel 10459: my $ua=new LWP::UserAgent;
1.979 raeburn 10460: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 10461: my $response=$ua->request($request);
1.979 raeburn 10462: delete($alldns{$dns});
1.852 albertel 10463: next if ($response->is_error());
10464: my @content = split("\n",$response->content);
1.869 albertel 10465: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 10466: &$func(\@content);
1.869 albertel 10467: return;
1.852 albertel 10468: }
10469: close($config);
1.871 albertel 10470: my $which = (split('/',$url))[3];
10471: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
10472: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 10473: my @content = <$config>;
10474: &$func(\@content);
10475: return;
1.852 albertel 10476: }
1.327 albertel 10477: # ------------------------------------------------------------ Read domain file
10478: {
1.852 albertel 10479: my $loaded;
1.846 albertel 10480: my %domain;
10481:
1.852 albertel 10482: sub parse_domain_tab {
10483: my ($lines) = @_;
10484: foreach my $line (@$lines) {
10485: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 10486:
1.846 albertel 10487: chomp($line);
1.852 albertel 10488: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 10489: my %this_domain;
10490: foreach my $field ('description', 'auth_def', 'auth_arg_def',
10491: 'lang_def', 'city', 'longi', 'lati',
10492: 'primary') {
10493: $this_domain{$field} = shift(@elements);
10494: }
10495: $domain{$name} = \%this_domain;
1.852 albertel 10496: }
10497: }
1.864 albertel 10498:
10499: sub reset_domain_info {
10500: undef($loaded);
10501: undef(%domain);
10502: }
10503:
1.852 albertel 10504: sub load_domain_tab {
1.869 albertel 10505: my ($ignore_cache) = @_;
10506: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 10507: my $fh;
10508: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
10509: my @lines = <$fh>;
10510: &parse_domain_tab(\@lines);
1.448 albertel 10511: }
1.852 albertel 10512: close($fh);
10513: $loaded = 1;
1.327 albertel 10514: }
1.846 albertel 10515:
10516: sub domain {
1.852 albertel 10517: &load_domain_tab() if (!$loaded);
10518:
1.846 albertel 10519: my ($name,$what) = @_;
10520: return if ( !exists($domain{$name}) );
10521:
10522: if (!$what) {
10523: return $domain{$name}{'description'};
10524: }
10525: return $domain{$name}{$what};
10526: }
1.974 raeburn 10527:
10528: sub domain_info {
10529: &load_domain_tab() if (!$loaded);
10530: return %domain;
10531: }
10532:
1.327 albertel 10533: }
10534:
10535:
1.1 albertel 10536: # ------------------------------------------------------------- Read hosts file
10537: {
1.838 albertel 10538: my %hostname;
1.844 albertel 10539: my %hostdom;
1.845 albertel 10540: my %libserv;
1.852 albertel 10541: my $loaded;
1.888 albertel 10542: my %name_to_host;
1.1074 raeburn 10543: my %internetdom;
1.1107 raeburn 10544: my %LC_dns_serv;
1.852 albertel 10545:
10546: sub parse_hosts_tab {
10547: my ($file) = @_;
10548: foreach my $configline (@$file) {
10549: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 10550: chomp($configline);
10551: if ($configline =~ /^\^/) {
10552: if ($configline =~ /^\^([\w.\-]+)/) {
10553: $LC_dns_serv{$1} = 1;
10554: }
10555: next;
10556: }
1.1074 raeburn 10557: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 10558: $name=~s/\s//g;
10559: if ($id && $domain && $role && $name) {
10560: $hostname{$id}=$name;
1.888 albertel 10561: push(@{$name_to_host{$name}}, $id);
1.852 albertel 10562: $hostdom{$id}=$domain;
10563: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 10564: if (defined($protocol)) {
10565: if ($protocol eq 'https') {
10566: $protocol{$id} = $protocol;
10567: } else {
10568: $protocol{$id} = 'http';
10569: }
1.968 raeburn 10570: } else {
1.969 raeburn 10571: $protocol{$id} = 'http';
1.968 raeburn 10572: }
1.1074 raeburn 10573: if (defined($intdom)) {
10574: $internetdom{$id} = $intdom;
10575: }
1.852 albertel 10576: }
10577: }
10578: }
1.864 albertel 10579:
10580: sub reset_hosts_info {
1.897 albertel 10581: &purge_remembered();
1.864 albertel 10582: &reset_domain_info();
10583: &reset_hosts_ip_info();
1.892 albertel 10584: undef(%name_to_host);
1.864 albertel 10585: undef(%hostname);
10586: undef(%hostdom);
10587: undef(%libserv);
10588: undef($loaded);
10589: }
1.1 albertel 10590:
1.852 albertel 10591: sub load_hosts_tab {
1.869 albertel 10592: my ($ignore_cache) = @_;
10593: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 10594: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
10595: my @config = <$config>;
10596: &parse_hosts_tab(\@config);
10597: close($config);
10598: $loaded=1;
1.1 albertel 10599: }
1.852 albertel 10600:
1.838 albertel 10601: sub hostname {
1.852 albertel 10602: &load_hosts_tab() if (!$loaded);
10603:
1.838 albertel 10604: my ($lonid) = @_;
10605: return $hostname{$lonid};
10606: }
1.845 albertel 10607:
1.838 albertel 10608: sub all_hostnames {
1.852 albertel 10609: &load_hosts_tab() if (!$loaded);
10610:
1.838 albertel 10611: return %hostname;
10612: }
1.845 albertel 10613:
1.888 albertel 10614: sub all_names {
10615: &load_hosts_tab() if (!$loaded);
10616:
10617: return %name_to_host;
10618: }
10619:
1.974 raeburn 10620: sub all_host_domain {
10621: &load_hosts_tab() if (!$loaded);
10622: return %hostdom;
10623: }
10624:
1.845 albertel 10625: sub is_library {
1.852 albertel 10626: &load_hosts_tab() if (!$loaded);
10627:
1.845 albertel 10628: return exists($libserv{$_[0]});
10629: }
10630:
10631: sub all_library {
1.852 albertel 10632: &load_hosts_tab() if (!$loaded);
10633:
1.845 albertel 10634: return %libserv;
10635: }
10636:
1.1062 droeschl 10637: sub unique_library {
10638: #2x reverse removes all hostnames that appear more than once
10639: my %unique = reverse &all_library();
10640: return reverse %unique;
10641: }
10642:
1.841 albertel 10643: sub get_servers {
1.852 albertel 10644: &load_hosts_tab() if (!$loaded);
10645:
1.841 albertel 10646: my ($domain,$type) = @_;
10647: my %possible_hosts = ($type eq 'library') ? %libserv
10648: : %hostname;
10649: my %result;
1.842 albertel 10650: if (ref($domain) eq 'ARRAY') {
10651: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 10652: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 10653: $result{$host} = $hostname;
10654: }
10655: }
10656: } else {
10657: while ( my ($host,$hostname) = each(%possible_hosts)) {
10658: if ($hostdom{$host} eq $domain) {
10659: $result{$host} = $hostname;
10660: }
1.841 albertel 10661: }
10662: }
10663: return %result;
10664: }
1.845 albertel 10665:
1.1062 droeschl 10666: sub get_unique_servers {
10667: my %unique = reverse &get_servers(@_);
10668: return reverse %unique;
10669: }
10670:
1.844 albertel 10671: sub host_domain {
1.852 albertel 10672: &load_hosts_tab() if (!$loaded);
10673:
1.844 albertel 10674: my ($lonid) = @_;
10675: return $hostdom{$lonid};
10676: }
10677:
1.841 albertel 10678: sub all_domains {
1.852 albertel 10679: &load_hosts_tab() if (!$loaded);
10680:
1.841 albertel 10681: my %seen;
10682: my @uniq = grep(!$seen{$_}++, values(%hostdom));
10683: return @uniq;
10684: }
1.1074 raeburn 10685:
10686: sub internet_dom {
10687: &load_hosts_tab() if (!$loaded);
10688:
10689: my ($lonid) = @_;
10690: return $internetdom{$lonid};
10691: }
1.1107 raeburn 10692:
10693: sub is_LC_dns {
10694: &load_hosts_tab() if (!$loaded);
10695:
10696: my ($hostname) = @_;
10697: return exists($LC_dns_serv{$hostname});
10698: }
10699:
1.1 albertel 10700: }
10701:
1.847 albertel 10702: {
10703: my %iphost;
1.856 albertel 10704: my %name_to_ip;
10705: my %lonid_to_ip;
1.869 albertel 10706:
1.847 albertel 10707: sub get_hosts_from_ip {
10708: my ($ip) = @_;
10709: my %iphosts = &get_iphost();
10710: if (ref($iphosts{$ip})) {
10711: return @{$iphosts{$ip}};
10712: }
10713: return;
1.839 albertel 10714: }
1.864 albertel 10715:
10716: sub reset_hosts_ip_info {
10717: undef(%iphost);
10718: undef(%name_to_ip);
10719: undef(%lonid_to_ip);
10720: }
1.856 albertel 10721:
10722: sub get_host_ip {
10723: my ($lonid) = @_;
10724: if (exists($lonid_to_ip{$lonid})) {
10725: return $lonid_to_ip{$lonid};
10726: }
10727: my $name=&hostname($lonid);
10728: my $ip = gethostbyname($name);
10729: return if (!$ip || length($ip) ne 4);
10730: $ip=inet_ntoa($ip);
10731: $name_to_ip{$name} = $ip;
10732: $lonid_to_ip{$lonid} = $ip;
10733: return $ip;
10734: }
1.847 albertel 10735:
10736: sub get_iphost {
1.869 albertel 10737: my ($ignore_cache) = @_;
1.894 albertel 10738:
1.869 albertel 10739: if (!$ignore_cache) {
10740: if (%iphost) {
10741: return %iphost;
10742: }
10743: my ($ip_info,$cached)=
10744: &Apache::lonnet::is_cached_new('iphost','iphost');
10745: if ($cached) {
10746: %iphost = %{$ip_info->[0]};
10747: %name_to_ip = %{$ip_info->[1]};
10748: %lonid_to_ip = %{$ip_info->[2]};
10749: return %iphost;
10750: }
10751: }
1.894 albertel 10752:
10753: # get yesterday's info for fallback
10754: my %old_name_to_ip;
10755: my ($ip_info,$cached)=
10756: &Apache::lonnet::is_cached_new('iphost','iphost');
10757: if ($cached) {
10758: %old_name_to_ip = %{$ip_info->[1]};
10759: }
10760:
1.888 albertel 10761: my %name_to_host = &all_names();
10762: foreach my $name (keys(%name_to_host)) {
1.847 albertel 10763: my $ip;
10764: if (!exists($name_to_ip{$name})) {
10765: $ip = gethostbyname($name);
10766: if (!$ip || length($ip) ne 4) {
1.894 albertel 10767: if (defined($old_name_to_ip{$name})) {
10768: $ip = $old_name_to_ip{$name};
10769: &logthis("Can't find $name defaulting to old $ip");
10770: } else {
10771: &logthis("Name $name no IP found");
10772: next;
10773: }
10774: } else {
10775: $ip=inet_ntoa($ip);
1.847 albertel 10776: }
10777: $name_to_ip{$name} = $ip;
10778: } else {
10779: $ip = $name_to_ip{$name};
1.653 albertel 10780: }
1.888 albertel 10781: foreach my $id (@{ $name_to_host{$name} }) {
10782: $lonid_to_ip{$id} = $ip;
10783: }
10784: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 10785: }
1.869 albertel 10786: &Apache::lonnet::do_cache_new('iphost','iphost',
10787: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 10788: 48*60*60);
1.869 albertel 10789:
1.847 albertel 10790: return %iphost;
1.598 albertel 10791: }
10792:
1.992 raeburn 10793: #
10794: # Given a DNS returns the loncapa host name for that DNS
10795: #
10796: sub host_from_dns {
10797: my ($dns) = @_;
10798: my @hosts;
10799: my $ip;
10800:
1.993 raeburn 10801: if (exists($name_to_ip{$dns})) {
1.992 raeburn 10802: $ip = $name_to_ip{$dns};
10803: }
10804: if (!$ip) {
10805: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
10806: if (length($ip) == 4) {
10807: $ip = &IO::Socket::inet_ntoa($ip);
10808: }
10809: }
10810: if ($ip) {
10811: @hosts = get_hosts_from_ip($ip);
10812: return $hosts[0];
10813: }
10814: return undef;
1.986 foxr 10815: }
1.992 raeburn 10816:
1.1074 raeburn 10817: sub get_internet_names {
10818: my ($lonid) = @_;
10819: return if ($lonid eq '');
10820: my ($idnref,$cached)=
10821: &Apache::lonnet::is_cached_new('internetnames',$lonid);
10822: if ($cached) {
10823: return $idnref;
10824: }
10825: my $ip = &get_host_ip($lonid);
10826: my @hosts = &get_hosts_from_ip($ip);
10827: my %iphost = &get_iphost();
10828: my (@idns,%seen);
10829: foreach my $id (@hosts) {
10830: my $dom = &host_domain($id);
10831: my $prim_id = &domain($dom,'primary');
10832: my $prim_ip = &get_host_ip($prim_id);
10833: next if ($seen{$prim_ip});
10834: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
10835: foreach my $id (@{$iphost{$prim_ip}}) {
10836: my $intdom = &internet_dom($id);
10837: unless (grep(/^\Q$intdom\E$/,@idns)) {
10838: push(@idns,$intdom);
10839: }
10840: }
10841: }
10842: $seen{$prim_ip} = 1;
10843: }
10844: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
10845: }
10846:
1.986 foxr 10847: }
10848:
1.1079 raeburn 10849: sub all_loncaparevs {
10850: return qw(1.1 1.2 1.3 2.0 2.1 2.2 2.3 2.4 2.5 2.6 2.7 2.8 2.9 2.10);
10851: }
10852:
1.862 albertel 10853: BEGIN {
10854:
10855: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
10856: unless ($readit) {
10857: {
10858: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
10859: %perlvar = (%perlvar,%{$configvars});
10860: }
10861:
10862:
1.1 albertel 10863: # ------------------------------------------------------ Read spare server file
10864: {
1.448 albertel 10865: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 10866:
10867: while (my $configline=<$config>) {
10868: chomp($configline);
1.284 matthew 10869: if ($configline) {
1.784 albertel 10870: my ($host,$type) = split(':',$configline,2);
1.785 albertel 10871: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 10872: push(@{ $spareid{$type} }, $host);
1.1 albertel 10873: }
10874: }
1.448 albertel 10875: close($config);
1.1 albertel 10876: }
1.11 www 10877: # ------------------------------------------------------------ Read permissions
10878: {
1.448 albertel 10879: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 10880:
10881: while (my $configline=<$config>) {
1.448 albertel 10882: chomp($configline);
10883: if ($configline) {
10884: my ($role,$perm)=split(/ /,$configline);
10885: if ($perm ne '') { $pr{$role}=$perm; }
10886: }
1.11 www 10887: }
1.448 albertel 10888: close($config);
1.11 www 10889: }
10890:
10891: # -------------------------------------------- Read plain texts for permissions
10892: {
1.448 albertel 10893: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 10894:
10895: while (my $configline=<$config>) {
1.448 albertel 10896: chomp($configline);
10897: if ($configline) {
1.742 raeburn 10898: my ($short,@plain)=split(/:/,$configline);
10899: %{$prp{$short}} = ();
10900: if (@plain > 0) {
10901: $prp{$short}{'std'} = $plain[0];
10902: for (my $i=1; $i<@plain; $i++) {
10903: $prp{$short}{'alt'.$i} = $plain[$i];
10904: }
10905: }
1.448 albertel 10906: }
1.135 www 10907: }
1.448 albertel 10908: close($config);
1.135 www 10909: }
10910:
10911: # ---------------------------------------------------------- Read package table
10912: {
1.448 albertel 10913: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 10914:
10915: while (my $configline=<$config>) {
1.483 albertel 10916: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 10917: chomp($configline);
10918: my ($short,$plain)=split(/:/,$configline);
10919: my ($pack,$name)=split(/\&/,$short);
10920: if ($plain ne '') {
10921: $packagetab{$pack.'&'.$name.'&name'}=$name;
10922: $packagetab{$short}=$plain;
10923: }
1.11 www 10924: }
1.448 albertel 10925: close($config);
1.329 matthew 10926: }
10927:
1.1073 raeburn 10928: # ---------------------------------------------------------- Read loncaparev table
10929: {
10930: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
10931: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
10932: while (my $configline=<$config>) {
10933: chomp($configline);
10934: my ($hostid,$loncaparev)=split(/:/,$configline);
10935: $loncaparevs{$hostid}=$loncaparev;
10936: }
10937: close($config);
10938: }
10939: }
10940: }
10941:
1.1074 raeburn 10942: # ---------------------------------------------------------- Read serverhostID table
10943: {
10944: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
10945: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
10946: while (my $configline=<$config>) {
10947: chomp($configline);
10948: my ($name,$id)=split(/:/,$configline);
10949: $serverhomeIDs{$name}=$id;
10950: }
10951: close($config);
10952: }
10953: }
10954: }
10955:
1.1079 raeburn 10956: {
10957: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
10958: if (-e $file) {
10959: my $parser = HTML::LCParser->new($file);
10960: while (my $token = $parser->get_token()) {
10961: if ($token->[0] eq 'S') {
10962: my $item = $token->[1];
10963: my $name = $token->[2]{'name'};
10964: my $value = $token->[2]{'value'};
10965: if ($item ne '' && $name ne '' && $value ne '') {
10966: my $release = $parser->get_text();
10967: $release =~ s/(^\s*|\s*$ )//gx;
10968: $needsrelease{$item.':'.$name.':'.$value} = $release;
10969: }
10970: }
10971: }
10972: }
1.1073 raeburn 10973: }
10974:
1.329 matthew 10975: # ------------- set up temporary directory
10976: {
1.1117 foxr 10977: $tmpdir = LONCAPA::tempdir();
1.329 matthew 10978:
1.11 www 10979: }
10980:
1.794 albertel 10981: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
10982: 'compress_threshold'=> 20_000,
10983: });
1.185 www 10984:
1.281 www 10985: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 10986: $dumpcount=0;
1.958 www 10987: $locknum=0;
1.22 www 10988:
1.163 harris41 10989: &logtouch();
1.672 albertel 10990: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 10991: $readit=1;
1.564 albertel 10992: {
10993: use integer;
10994: my $test=(2**32)+1;
1.568 albertel 10995: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 10996: &logthis(" Detected 64bit platform ($_64bit)");
10997: }
1.195 www 10998: }
1.1 albertel 10999: }
1.179 www 11000:
1.1 albertel 11001: 1;
1.191 harris41 11002: __END__
11003:
1.243 albertel 11004: =pod
11005:
1.191 harris41 11006: =head1 NAME
11007:
1.243 albertel 11008: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11009:
11010: =head1 SYNOPSIS
11011:
1.243 albertel 11012: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11013:
11014: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11015:
1.243 albertel 11016: Common parameters:
11017:
11018: =over 4
11019:
11020: =item *
11021:
11022: $uname : an internal username (if $cname expecting a course Id specifically)
11023:
11024: =item *
11025:
11026: $udom : a domain (if $cdom expecting a course's domain specifically)
11027:
11028: =item *
11029:
11030: $symb : a resource instance identifier
11031:
11032: =item *
11033:
11034: $namespace : the name of a .db file that contains the data needed or
11035: being set.
11036:
11037: =back
11038:
1.394 bowersj2 11039: =head1 OVERVIEW
1.191 harris41 11040:
1.394 bowersj2 11041: lonnet provides subroutines which interact with the
11042: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11043: about classes, users, and resources.
1.243 albertel 11044:
11045: For many of these objects you can also use this to store data about
11046: them or modify them in various ways.
1.191 harris41 11047:
1.394 bowersj2 11048: =head2 Symbs
1.191 harris41 11049:
1.394 bowersj2 11050: To identify a specific instance of a resource, LON-CAPA uses symbols
11051: or "symbs"X<symb>. These identifiers are built from the URL of the
11052: map, the resource number of the resource in the map, and the URL of
11053: the resource itself. The latter is somewhat redundant, but might help
11054: if maps change.
11055:
11056: An example is
11057:
11058: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11059:
11060: The respective map entry is
11061:
11062: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11063: title="Problem 2">
11064: </resource>
11065:
11066: Symbs are used by the random number generator, as well as to store and
11067: restore data specific to a certain instance of for example a problem.
11068:
11069: =head2 Storing And Retrieving Data
11070:
11071: X<store()>X<cstore()>X<restore()>Three of the most important functions
11072: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11073: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11074: is is the non-critical message twin of cstore. These functions are for
11075: handlers to store a perl hash to a user's permanent data space in an
11076: easy manner, and to retrieve it again on another call. It is expected
11077: that a handler would use this once at the beginning to retrieve data,
11078: and then again once at the end to send only the new data back.
11079:
11080: The data is stored in the user's data directory on the user's
11081: homeserver under the ID of the course.
11082:
11083: The hash that is returned by restore will have all of the previous
11084: value for all of the elements of the hash.
11085:
11086: Example:
11087:
11088: #creating a hash
11089: my %hash;
11090: $hash{'foo'}='bar';
11091:
11092: #storing it
11093: &Apache::lonnet::cstore(\%hash);
11094:
11095: #changing a value
11096: $hash{'foo'}='notbar';
11097:
11098: #adding a new value
11099: $hash{'bar'}='foo';
11100: &Apache::lonnet::cstore(\%hash);
11101:
11102: #retrieving the hash
11103: my %history=&Apache::lonnet::restore();
11104:
11105: #print the hash
11106: foreach my $key (sort(keys(%history))) {
11107: print("\%history{$key} = $history{$key}");
11108: }
11109:
11110: Will print out:
1.191 harris41 11111:
1.394 bowersj2 11112: %history{1:foo} = bar
11113: %history{1:keys} = foo:timestamp
11114: %history{1:timestamp} = 990455579
11115: %history{2:bar} = foo
11116: %history{2:foo} = notbar
11117: %history{2:keys} = foo:bar:timestamp
11118: %history{2:timestamp} = 990455580
11119: %history{bar} = foo
11120: %history{foo} = notbar
11121: %history{timestamp} = 990455580
11122: %history{version} = 2
11123:
11124: Note that the special hash entries C<keys>, C<version> and
11125: C<timestamp> were added to the hash. C<version> will be equal to the
11126: total number of versions of the data that have been stored. The
11127: C<timestamp> attribute will be the UNIX time the hash was
11128: stored. C<keys> is available in every historical section to list which
11129: keys were added or changed at a specific historical revision of a
11130: hash.
11131:
11132: B<Warning>: do not store the hash that restore returns directly. This
11133: will cause a mess since it will restore the historical keys as if the
11134: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11135:
1.394 bowersj2 11136: Calling convention:
1.191 harris41 11137:
1.394 bowersj2 11138: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11139: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11140:
1.394 bowersj2 11141: For more detailed information, see lonnet specific documentation.
1.191 harris41 11142:
1.394 bowersj2 11143: =head1 RETURN MESSAGES
1.191 harris41 11144:
1.394 bowersj2 11145: =over 4
1.191 harris41 11146:
1.394 bowersj2 11147: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11148:
1.394 bowersj2 11149: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11150: when the connection is brought back up
1.191 harris41 11151:
1.394 bowersj2 11152: =item * B<con_failed>: unable to contact remote host and unable to save message
11153: for later delivery
1.191 harris41 11154:
1.967 bisitz 11155: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11156:
1.394 bowersj2 11157: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11158: that was requested
1.191 harris41 11159:
1.243 albertel 11160: =back
1.191 harris41 11161:
1.243 albertel 11162: =head1 PUBLIC SUBROUTINES
1.191 harris41 11163:
1.243 albertel 11164: =head2 Session Environment Functions
1.191 harris41 11165:
1.243 albertel 11166: =over 4
1.191 harris41 11167:
1.394 bowersj2 11168: =item *
11169: X<appenv()>
1.949 raeburn 11170: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11171: the user envirnoment file, and will be restored for each access this
1.620 albertel 11172: user makes during this session, also modifies the %env for the current
1.949 raeburn 11173: process. Optional rolesarrayref - if defined contains a reference to an array
11174: of roles which are exempt from the restriction on modifying user.role entries
11175: in the user's environment.db and in %env.
1.191 harris41 11176:
11177: =item *
1.394 bowersj2 11178: X<delenv()>
1.987 raeburn 11179: B<delenv($delthis,$regexp)>: removes all items from the session
11180: environment file that begin with $delthis. If the
11181: optional second arg - $regexp - is true, $delthis is treated as a
11182: regular expression, otherwise \Q$delthis\E is used.
11183: The values are also deleted from the current processes %env.
1.191 harris41 11184:
1.795 albertel 11185: =item * get_env_multiple($name)
11186:
11187: gets $name from the %env hash, it seemlessly handles the cases where multiple
11188: values may be defined and end up as an array ref.
11189:
11190: returns an array of values
11191:
1.243 albertel 11192: =back
11193:
11194: =head2 User Information
1.191 harris41 11195:
1.243 albertel 11196: =over 4
1.191 harris41 11197:
11198: =item *
1.394 bowersj2 11199: X<queryauthenticate()>
11200: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11201: authentication scheme
11202:
11203: =item *
1.394 bowersj2 11204: X<authenticate()>
1.1073 raeburn 11205: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11206: authenticate user from domain's lib servers (first use the current
11207: one). C<$upass> should be the users password.
1.1073 raeburn 11208: $checkdefauth is optional (value is 1 if a check should be made to
11209: authenticate user using default authentication method, and allow
11210: account creation if username does not have account in the domain).
11211: $clientcancheckhost is optional (value is 1 if checking whether the
11212: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11213:
11214: =item *
1.394 bowersj2 11215: X<homeserver()>
11216: B<homeserver($uname,$udom)>: find the server which has
11217: the user's directory and files (there must be only one), this caches
11218: the answer, and also caches if there is a borken connection.
1.191 harris41 11219:
11220: =item *
1.394 bowersj2 11221: X<idget()>
11222: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11223: (IDs are a unique resource in a domain, there must be only 1 ID per
11224: username, and only 1 username per ID in a specific domain) (returns
11225: hash: id=>name,id=>name)
1.191 harris41 11226:
11227: =item *
1.394 bowersj2 11228: X<idrget()>
11229: B<idrget($udom,@unames)>: find the IDs behind a list of
11230: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11231:
11232: =item *
1.394 bowersj2 11233: X<idput()>
11234: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11235:
11236: =item *
1.394 bowersj2 11237: X<rolesinit()>
11238: B<rolesinit($udom,$username,$authhost)>: get user privileges
1.243 albertel 11239:
11240: =item *
1.551 albertel 11241: X<getsection()>
11242: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11243: course $cname, return section name/number or '' for "not in course"
11244: and '-1' for "no section"
11245:
11246: =item *
1.394 bowersj2 11247: X<userenvironment()>
11248: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11249: passed in @what from the requested user's environment, returns a hash
11250:
1.858 raeburn 11251: =item *
11252: X<userlog_query()>
1.859 albertel 11253: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11254: activity.log file. %filters defines filters applied when parsing the
11255: log file. These can be start or end timestamps, or the type of action
11256: - log to look for Login or Logout events, check for Checkin or
11257: Checkout, role for role selection. The response is in the form
11258: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11259: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11260:
1.243 albertel 11261: =back
11262:
11263: =head2 User Roles
11264:
11265: =over 4
11266:
11267: =item *
11268:
1.810 raeburn 11269: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11270: F: full access
11271: U,I,K: authentication modes (cxx only)
11272: '': forbidden
11273: 1: user needs to choose course
11274: 2: browse allowed
1.766 albertel 11275: A: passphrase authentication needed
1.243 albertel 11276:
11277: =item *
11278:
11279: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11280: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11281: and course level
11282:
11283: =item *
11284:
1.988 raeburn 11285: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11286: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11287: $type is Course (default) or Community.
1.988 raeburn 11288: If $forcedefault evaluates to true, text returned will be default
11289: text for $type. Otherwise, if this is a course, the text returned
11290: will be a custom name for the role (if defined in the course's
11291: environment). If no custom name is defined the default is returned.
11292:
1.832 raeburn 11293: =item *
11294:
1.935 raeburn 11295: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11296: All arguments are optional. Returns a hash of a roles, either for
11297: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11298: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11299: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11300: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11301: For each key, value is set to colon-separated start and end times for
11302: the role. If no username and domain are specified, will default to
1.934 raeburn 11303: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11304: of role statuses (active, future or previous), roles
11305: (e.g., cc,in, st etc.) and domains of the roles which can be used
11306: to restrict the list of roles reported. If no array ref is
11307: provided for types, will default to return only active roles.
1.834 albertel 11308:
1.243 albertel 11309: =back
11310:
11311: =head2 User Modification
11312:
11313: =over 4
11314:
11315: =item *
11316:
1.957 raeburn 11317: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11318: user for the level given by URL. Optional start and end dates (leave empty
11319: string or zero for "no date")
1.191 harris41 11320:
11321: =item *
11322:
1.243 albertel 11323: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11324: change a users, password, possible return values are: ok,
11325: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11326: refused
1.191 harris41 11327:
11328: =item *
11329:
1.243 albertel 11330: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11331:
11332: =item *
11333:
1.1058 raeburn 11334: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11335: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11336:
11337: will update user information (firstname,middlename,lastname,generation,
11338: permanentemail), and if forceid is true, student/employee ID also.
11339: A user's institutional affiliation(s) can also be updated.
11340: User information fields will not be overwritten with empty entries
11341: unless the field is included in the $candelete array reference.
11342: This array is included when a single user is modified via "Manage Users",
11343: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11344:
11345: =item *
11346:
1.286 matthew 11347: modifystudent
11348:
1.957 raeburn 11349: modify a student's enrollment and identification information.
1.286 matthew 11350: The course id is resolved based on the current users environment.
11351: This means the envoking user must be a course coordinator or otherwise
11352: associated with a course.
11353:
1.297 matthew 11354: This call is essentially a wrapper for lonnet::modifyuser and
11355: lonnet::modify_student_enrollment
1.286 matthew 11356:
11357: Inputs:
11358:
11359: =over 4
11360:
1.957 raeburn 11361: =item B<$udom> Student's loncapa domain
1.286 matthew 11362:
1.957 raeburn 11363: =item B<$uname> Student's loncapa login name
1.286 matthew 11364:
1.964 bisitz 11365: =item B<$uid> Student/Employee ID
1.286 matthew 11366:
1.957 raeburn 11367: =item B<$umode> Student's authentication mode
1.286 matthew 11368:
1.957 raeburn 11369: =item B<$upass> Student's password
1.286 matthew 11370:
1.957 raeburn 11371: =item B<$first> Student's first name
1.286 matthew 11372:
1.957 raeburn 11373: =item B<$middle> Student's middle name
1.286 matthew 11374:
1.957 raeburn 11375: =item B<$last> Student's last name
1.286 matthew 11376:
1.957 raeburn 11377: =item B<$gene> Student's generation
1.286 matthew 11378:
1.957 raeburn 11379: =item B<$usec> Student's section in course
1.286 matthew 11380:
11381: =item B<$end> Unix time of the roles expiration
11382:
11383: =item B<$start> Unix time of the roles start date
11384:
11385: =item B<$forceid> If defined, allow $uid to be changed
11386:
11387: =item B<$desiredhome> server to use as home server for student
11388:
1.957 raeburn 11389: =item B<$email> Student's permanent e-mail address
11390:
11391: =item B<$type> Type of enrollment (auto or manual)
11392:
1.963 raeburn 11393: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11394:
11395: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11396:
1.963 raeburn 11397: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11398:
1.963 raeburn 11399: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11400:
1.963 raeburn 11401: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11402:
1.286 matthew 11403: =back
1.297 matthew 11404:
11405: =item *
11406:
11407: modify_student_enrollment
11408:
11409: Change a students enrollment status in a class. The environment variable
11410: 'role.request.course' must be defined for this function to proceed.
11411:
11412: Inputs:
11413:
11414: =over 4
11415:
11416: =item $udom, students domain
11417:
11418: =item $uname, students name
11419:
11420: =item $uid, students user id
11421:
11422: =item $first, students first name
11423:
11424: =item $middle
11425:
11426: =item $last
11427:
11428: =item $gene
11429:
11430: =item $usec
11431:
11432: =item $end
11433:
11434: =item $start
11435:
1.957 raeburn 11436: =item $type
11437:
11438: =item $locktype
11439:
11440: =item $cid
11441:
11442: =item $selfenroll
11443:
11444: =item $context
11445:
1.297 matthew 11446: =back
11447:
1.191 harris41 11448:
11449: =item *
11450:
1.243 albertel 11451: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
11452: custom role; give a custom role to a user for the level given by URL. Specify
11453: name and domain of role author, and role name
1.191 harris41 11454:
11455: =item *
11456:
1.243 albertel 11457: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 11458:
11459: =item *
11460:
1.243 albertel 11461: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
11462:
11463: =back
11464:
11465: =head2 Course Infomation
11466:
11467: =over 4
1.191 harris41 11468:
11469: =item *
11470:
1.1118 foxr 11471: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 11472: specified course id, including all environment settings for the
11473: course, the description of the course will be in the hash under the
11474: key 'description'
1.191 harris41 11475:
1.1118 foxr 11476: $options is an optional parameter that if supplied is a hash reference that controls
11477: what how this function works. It has the following key/values:
11478:
11479: =over 4
11480:
11481: =item freshen_cache
11482:
11483: If defined, and the environment cache for the course is valid, it is
11484: returned in the returned hash.
11485:
11486: =item one_time
11487:
11488: If defined, the last cache time is set to _now_
11489:
11490: =item user
11491:
11492: If defined, the supplied username is used instead of the current user.
11493:
11494:
11495: =back
11496:
1.191 harris41 11497: =item *
11498:
1.624 albertel 11499: resdata($name,$domain,$type,@which) : request for current parameter
11500: setting for a specific $type, where $type is either 'course' or 'user',
11501: @what should be a list of parameters to ask about. This routine caches
11502: answers for 5 minutes.
1.243 albertel 11503:
1.877 foxr 11504: =item *
11505:
11506: get_courseresdata($courseid, $domain) : dump the entire course resource
11507: data base, returning a hash that is keyed by the resource name and has
11508: values that are the resource value. I believe that the timestamps and
11509: versions are also returned.
11510:
11511:
1.243 albertel 11512: =back
11513:
11514: =head2 Course Modification
11515:
11516: =over 4
1.191 harris41 11517:
11518: =item *
11519:
1.243 albertel 11520: writecoursepref($courseid,%prefs) : write preferences (environment
11521: database) for a course
1.191 harris41 11522:
11523: =item *
11524:
1.1011 raeburn 11525: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
11526:
11527: =item *
11528:
1.1038 raeburn 11529: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 11530:
11531: =back
11532:
11533: =head2 Resource Subroutines
11534:
11535: =over 4
1.191 harris41 11536:
11537: =item *
11538:
1.243 albertel 11539: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 11540:
11541: =item *
11542:
1.243 albertel 11543: repcopy($filename) : subscribes to the requested file, and attempts to
11544: replicate from the owning library server, Might return
1.607 raeburn 11545: 'unavailable', 'not_found', 'forbidden', 'ok', or
11546: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 11547: resource. Expects the local filesystem pathname
11548: (/home/httpd/html/res/....)
11549:
11550: =back
11551:
11552: =head2 Resource Information
11553:
11554: =over 4
1.191 harris41 11555:
11556: =item *
11557:
1.243 albertel 11558: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
11559: a vairety of different possible values, $varname should be a request
11560: string, and the other parameters can be used to specify who and what
11561: one is asking about.
11562:
11563: Possible values for $varname are environment.lastname (or other item
11564: from the envirnment hash), user.name (or someother aspect about the
11565: user), resource.0.maxtries (or some other part and parameter of a
11566: resource)
1.204 albertel 11567:
11568: =item *
11569:
1.243 albertel 11570: directcondval($number) : get current value of a condition; reads from a state
11571: string
1.204 albertel 11572:
11573: =item *
11574:
1.243 albertel 11575: condval($condidx) : value of condition index based on state
1.204 albertel 11576:
11577: =item *
11578:
1.243 albertel 11579: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
11580: resource's metadata, $what should be either a specific key, or either
11581: 'keys' (to get a list of possible keys) or 'packages' to get a list of
11582: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
11583:
11584: this function automatically caches all requests
1.191 harris41 11585:
11586: =item *
11587:
1.243 albertel 11588: metadata_query($query,$custom,$customshow) : make a metadata query against the
11589: network of library servers; returns file handle of where SQL and regex results
11590: will be stored for query
1.191 harris41 11591:
11592: =item *
11593:
1.243 albertel 11594: symbread($filename) : return symbolic list entry (filename argument optional);
11595: returns the data handle
1.191 harris41 11596:
11597: =item *
11598:
1.243 albertel 11599: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 11600: a possible symb for the URL in $thisfn, and if is an encryypted
11601: resource that the user accessed using /enc/ returns a 1 on success, 0
11602: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 11603: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 11604:
1.191 harris41 11605:
11606: =item *
11607:
1.243 albertel 11608: symbclean($symb) : removes versions numbers from a symb, returns the
11609: cleaned symb
1.191 harris41 11610:
11611: =item *
11612:
1.243 albertel 11613: is_on_map($uri) : checks if the $uri is somewhere on the current
11614: course map, user must be in a course for it to work.
1.191 harris41 11615:
11616: =item *
11617:
1.243 albertel 11618: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 11619:
11620: =item *
11621:
1.243 albertel 11622: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
11623: a random seed, all arguments are optional, if they aren't sent it uses the
11624: environment to derive them. Note: if symb isn't sent and it can't get one
11625: from &symbread it will use the current time as its return value
1.191 harris41 11626:
11627: =item *
11628:
1.243 albertel 11629: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
11630: unfakeable, receipt
1.191 harris41 11631:
11632: =item *
11633:
1.620 albertel 11634: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 11635:
11636: =item *
11637:
1.243 albertel 11638: countacc($url) : count the number of accesses to a given URL
1.191 harris41 11639:
11640: =item *
11641:
1.243 albertel 11642: 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
1.191 harris41 11643:
11644: =item *
11645:
1.243 albertel 11646: 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)
1.191 harris41 11647:
11648: =item *
11649:
1.243 albertel 11650: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 11651:
11652: =item *
11653:
1.243 albertel 11654: devalidate($symb) : devalidate temporary spreadsheet calculations,
11655: forcing spreadsheet to reevaluate the resource scores next time.
11656:
11657: =back
11658:
11659: =head2 Storing/Retreiving Data
11660:
11661: =over 4
1.191 harris41 11662:
11663: =item *
11664:
1.243 albertel 11665: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
11666: for this url; hashref needs to be given and should be a \%hashname; the
11667: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 11668: be derived from the env
1.191 harris41 11669:
11670: =item *
11671:
1.243 albertel 11672: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
11673: uses critical subroutine
1.191 harris41 11674:
11675: =item *
11676:
1.243 albertel 11677: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
11678: all args are optional
1.191 harris41 11679:
11680: =item *
11681:
1.717 albertel 11682: dumpstore($namespace,$udom,$uname,$regexp,$range) :
11683: dumps the complete (or key matching regexp) namespace into a hash
11684: ($udom, $uname, $regexp, $range are optional) for a namespace that is
11685: normally &store()ed into
11686:
11687: $range should be either an integer '100' (give me the first 100
11688: matching records)
11689: or be two integers sperated by a - with no spaces
11690: '30-50' (give me the 30th through the 50th matching
11691: records)
11692:
11693:
11694: =item *
11695:
11696: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
11697: replaces a &store() version of data with a replacement set of data
11698: for a particular resource in a namespace passed in the $storehash hash
11699: reference
11700:
11701: =item *
11702:
1.243 albertel 11703: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
11704: works very similar to store/cstore, but all data is stored in a
11705: temporary location and can be reset using tmpreset, $storehash should
11706: be a hash reference, returns nothing on success
1.191 harris41 11707:
11708: =item *
11709:
1.243 albertel 11710: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
11711: similar to restore, but all data is stored in a temporary location and
11712: can be reset using tmpreset. Returns a hash of values on success,
11713: error string otherwise.
1.191 harris41 11714:
11715: =item *
11716:
1.243 albertel 11717: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
11718: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 11719:
11720: =item *
11721:
1.243 albertel 11722: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11723: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 11724:
11725: =item *
11726:
1.243 albertel 11727: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
11728: namesp ($udom and $uname are optional)
1.191 harris41 11729:
11730: =item *
11731:
1.702 albertel 11732: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 11733: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 11734: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 11735:
1.702 albertel 11736: $range should be either an integer '100' (give me the first 100
11737: matching records)
11738: or be two integers sperated by a - with no spaces
11739: '30-50' (give me the 30th through the 50th matching
11740: records)
1.449 matthew 11741: =item *
11742:
11743: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
11744: $store can be a scalar, an array reference, or if the amount to be
11745: incremented is > 1, a hash reference.
11746:
11747: ($udom and $uname are optional)
1.191 harris41 11748:
11749: =item *
11750:
1.243 albertel 11751: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
11752: ($udom and $uname are optional)
1.191 harris41 11753:
11754: =item *
11755:
1.243 albertel 11756: cput($namespace,$storehash,$udom,$uname) : critical put
11757: ($udom and $uname are optional)
1.191 harris41 11758:
11759: =item *
11760:
1.748 albertel 11761: newput($namespace,$storehash,$udom,$uname) :
11762:
11763: Attempts to store the items in the $storehash, but only if they don't
11764: currently exist, if this succeeds you can be certain that you have
11765: successfully created a new key value pair in the $namespace db.
11766:
11767:
11768: Args:
11769: $namespace: name of database to store values to
11770: $storehash: hashref to store to the db
11771: $udom: (optional) domain of user containing the db
11772: $uname: (optional) name of user caontaining the db
11773:
11774: Returns:
11775: 'ok' -> succeeded in storing all keys of $storehash
11776: 'key_exists: <key>' -> failed to anything out of $storehash, as at
11777: least <key> already existed in the db (other
11778: requested keys may also already exist)
1.967 bisitz 11779: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 11780: 'con_lost' -> unable to contact request server
11781: 'refused' -> action was not allowed by remote machine
11782:
11783:
11784: =item *
11785:
1.243 albertel 11786: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
11787: reference filled in from namesp (encrypts the return communication)
11788: ($udom and $uname are optional)
1.191 harris41 11789:
11790: =item *
11791:
1.243 albertel 11792: log($udom,$name,$home,$message) : write to permanent log for user; use
11793: critical subroutine
11794:
1.806 raeburn 11795: =item *
11796:
1.860 raeburn 11797: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
11798: array reference filled in from namespace found in domain level on either
11799: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 11800:
11801: =item *
11802:
1.860 raeburn 11803: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
11804: domain level either on specified domain server ($uhome) or primary domain
11805: server ($udom and $uhome are optional)
1.806 raeburn 11806:
1.943 raeburn 11807: =item *
11808:
11809: get_domain_defaults($target_domain) : returns hash with defaults for
11810: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
11811: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
11812: or localauth), initial password or a kerberos realm, language (e.g., en-us).
11813: Values are retrieved from cache (if current), or from domain's configuration.db
11814: (if available), or lastly from values in lonTabs/dns_domain,tab,
11815: or lonTabs/domain.tab.
11816:
11817: %domdefaults = &get_auth_defaults($target_domain);
11818:
1.243 albertel 11819: =back
11820:
11821: =head2 Network Status Functions
11822:
11823: =over 4
1.191 harris41 11824:
11825: =item *
11826:
11827: dirlist($uri) : return directory list based on URI
11828:
11829: =item *
11830:
1.243 albertel 11831: spareserver() : find server with least workload from spare.tab
11832:
1.986 foxr 11833:
11834: =item *
11835:
11836: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
11837: if there is no corresponding loncapa host.
11838:
1.243 albertel 11839: =back
11840:
1.986 foxr 11841:
1.243 albertel 11842: =head2 Apache Request
11843:
11844: =over 4
1.191 harris41 11845:
11846: =item *
11847:
1.243 albertel 11848: ssi($url,%hash) : server side include, does a complete request cycle on url to
11849: localhost, posts hash
11850:
11851: =back
11852:
11853: =head2 Data to String to Data
11854:
11855: =over 4
1.191 harris41 11856:
11857: =item *
11858:
1.243 albertel 11859: hash2str(%hash) : convert a hash into a string complete with escaping and '='
11860: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 11861:
11862: =item *
11863:
1.243 albertel 11864: hashref2str($hashref) : convert a hashref into a string complete with
11865: escaping and '=' and '&' separators, supports elements that are
11866: arrayrefs and hashrefs
1.191 harris41 11867:
11868: =item *
11869:
1.243 albertel 11870: arrayref2str($arrayref) : convert an arrayref into a string complete
11871: with escaping and '&' separators, supports elements that are arrayrefs
11872: and hashrefs
1.191 harris41 11873:
11874: =item *
11875:
1.243 albertel 11876: str2hash($string) : convert string to hash using unescaping and
11877: splitting on '=' and '&', supports elements that are arrayrefs and
11878: hashrefs
1.191 harris41 11879:
11880: =item *
11881:
1.243 albertel 11882: str2array($string) : convert string to hash using unescaping and
11883: splitting on '&', supports elements that are arrayrefs and hashrefs
11884:
11885: =back
11886:
11887: =head2 Logging Routines
11888:
11889:
11890: These routines allow one to make log messages in the lonnet.log and
11891: lonnet.perm logfiles.
1.191 harris41 11892:
1.1119 foxr 11893: =over 4
11894:
1.191 harris41 11895: =item *
11896:
1.243 albertel 11897: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 11898:
11899: =item *
11900:
1.243 albertel 11901: logthis() : append message to the normal lonnet.log file, it gets
11902: preiodically rolled over and deleted.
1.191 harris41 11903:
11904: =item *
11905:
1.243 albertel 11906: logperm() : append a permanent message to lonnet.perm.log, this log
11907: file never gets deleted by any automated portion of the system, only
11908: messages of critical importance should go in here.
11909:
1.1119 foxr 11910:
1.243 albertel 11911: =back
11912:
11913: =head2 General File Helper Routines
11914:
11915: =over 4
1.191 harris41 11916:
11917: =item *
11918:
1.481 raeburn 11919: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
11920: (a) files in /uploaded
11921: (i) If a local copy of the file exists -
11922: compares modification date of local copy with last-modified date for
11923: definitive version stored on home server for course. If local copy is
11924: stale, requests a new version from the home server and stores it.
11925: If the original has been removed from the home server, then local copy
11926: is unlinked.
11927: (ii) If local copy does not exist -
11928: requests the file from the home server and stores it.
11929:
11930: If $caller is 'uploadrep':
11931: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
11932: for request for files originally uploaded via DOCS.
11933: - returns 'ok' if fresh local copy now available, -1 otherwise.
11934:
11935: Otherwise:
11936: This indicates a call from the content generation phase of the request.
11937: - returns the entire contents of the file or -1.
11938:
11939: (b) files in /res
11940: - returns the entire contents of a file or -1;
11941: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 11942:
1.712 albertel 11943:
11944: =item *
11945:
11946: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
11947: reference
11948:
11949: returns either a stat() list of data about the file or an empty list
11950: if the file doesn't exist or couldn't find out about it (connection
11951: problems or user unknown)
11952:
1.191 harris41 11953: =item *
11954:
1.243 albertel 11955: filelocation($dir,$file) : returns file system location of a file
11956: based on URI; meant to be "fairly clean" absolute reference, $dir is a
11957: directory that relative $file lookups are to looked in ($dir of /a/dir
11958: and a file of ../bob will become /a/bob)
1.191 harris41 11959:
11960: =item *
11961:
11962: hreflocation($dir,$file) : returns file system location or a URL; same as
11963: filelocation except for hrefs
11964:
11965: =item *
11966:
11967: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
11968:
1.243 albertel 11969: =back
11970:
1.608 albertel 11971: =head2 Usererfile file routines (/uploaded*)
11972:
11973: =over 4
11974:
11975: =item *
11976:
11977: userfileupload(): main rotine for putting a file in a user or course's
11978: filespace, arguments are,
11979:
1.620 albertel 11980: formname - required - this is the name of the element in $env where the
1.608 albertel 11981: filename, and the contents of the file to create/modifed exist
1.620 albertel 11982: the filename is in $env{'form.'.$formname.'.filename'} and the
11983: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 11984: context - if coursedoc, store the file in the course of the active role
11985: of the current user;
11986: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
11987: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 11988: subdir - required - subdirectory to put the file in under ../userfiles/
11989: if undefined, it will be placed in "unknown"
11990:
11991: (This routine calls clean_filename() to remove any dangerous
11992: characters from the filename, and then calls finuserfileupload() to
11993: complete the transaction)
11994:
11995: returns either the url of the uploaded file (/uploaded/....) if successful
11996: and /adm/notfound.html if unsuccessful
11997:
11998: =item *
11999:
12000: clean_filename(): routine for cleaing a filename up for storage in
12001: userfile space, argument is:
12002:
12003: filename - proposed filename
12004:
12005: returns: the new clean filename
12006:
12007: =item *
12008:
1.1090 raeburn 12009: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12010: userspace, probably shouldn't be called directly
12011:
12012: docuname: username or courseid of destination for the file
12013: docudom: domain of user/course of destination for the file
12014: formname: same as for userfileupload()
1.1090 raeburn 12015: fname: filename (including subdirectories) for the file
12016: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12017: allfiles: reference to hash used to store objects found by parser
12018: codebase: reference to hash used for codebases of java objects found by parser
12019: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12020: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12021: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12022: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12023: context: if 'overwrite', will move the uploaded file from its temporary location to
12024: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12025: mimetype: reference to scalar to accommodate mime type determined
12026: from File::MMagic if $parser = parse.
1.608 albertel 12027:
12028: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12029: and /adm/notfound.html if unsuccessful (or an error message if context
12030: was 'overwrite').
12031:
1.608 albertel 12032:
12033: =item *
12034:
12035: renameuserfile(): renames an existing userfile to a new name
12036:
12037: Args:
12038: docuname: username or courseid of destination for the file
12039: docudom: domain of user/course of destination for the file
12040: old: current file name (including any subdirs under userfiles)
12041: new: desired file name (including any subdirs under userfiles)
12042:
12043: =item *
12044:
12045: mkdiruserfile(): creates a directory is a userfiles dir
12046:
12047: Args:
12048: docuname: username or courseid of destination for the file
12049: docudom: domain of user/course of destination for the file
12050: dir: dir to create (including any subdirs under userfiles)
12051:
12052: =item *
12053:
12054: removeuserfile(): removes a file that exists in userfiles
12055:
12056: Args:
12057: docuname: username or courseid of destination for the file
12058: docudom: domain of user/course of destination for the file
12059: fname: filname to delete (including any subdirs under userfiles)
12060:
12061: =item *
12062:
12063: removeuploadedurl(): convience function for removeuserfile()
12064:
12065: Args:
12066: url: a full /uploaded/... url to delete
12067:
1.747 albertel 12068: =item *
12069:
12070: get_portfile_permissions():
12071: Args:
12072: domain: domain of user or course contain the portfolio files
12073: user: name of user or num of course contain the portfolio files
12074: Returns:
12075: hashref of a dump of the proper file_permissions.db
12076:
12077:
12078: =item *
12079:
12080: get_access_controls():
12081:
12082: Args:
12083: current_permissions: the hash ref returned from get_portfile_permissions()
12084: group: (optional) the group you want the files associated with
12085: file: (optional) the file you want access info on
12086:
12087: Returns:
1.749 raeburn 12088: a hash (keys are file names) of hashes containing
12089: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12090: values are XML containing access control settings (see below)
1.747 albertel 12091:
12092: Internal notes:
12093:
1.749 raeburn 12094: access controls are stored in file_permissions.db as key=value pairs.
12095: key -> path to file/file_name\0uniqueID:scope_end_start
12096: where scope -> public,guest,course,group,domains or users.
12097: end -> UNIX time for end of access (0 -> no end date)
12098: start -> UNIX time for start of access
12099:
12100: value -> XML description of access control
12101: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12102: <start></start>
12103: <end></end>
12104:
12105: <password></password> for scope type = guest
12106:
12107: <domain></domain> for scope type = course or group
12108: <number></number>
12109: <roles id="">
12110: <role></role>
12111: <access></access>
12112: <section></section>
12113: <group></group>
12114: </roles>
12115:
12116: <dom></dom> for scope type = domains
12117:
12118: <users> for scope type = users
12119: <user>
12120: <uname></uname>
12121: <udom></udom>
12122: </user>
12123: </users>
12124: </scope>
12125:
12126: Access data is also aggregated for each file in an additional key=value pair:
12127: key -> path to file/file_name\0accesscontrol
12128: value -> reference to hash
12129: hash contains key = value pairs
12130: where key = uniqueID:scope_end_start
12131: value = UNIX time record was last updated
12132:
12133: Used to improve speed of look-ups of access controls for each file.
12134:
12135: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12136:
12137: modify_access_controls():
12138:
12139: Modifies access controls for a portfolio file
12140: Args
12141: 1. file name
12142: 2. reference to hash of required changes,
12143: 3. domain
12144: 4. username
12145: where domain,username are the domain of the portfolio owner
12146: (either a user or a course)
12147:
12148: Returns:
12149: 1. result of additions or updates ('ok' or 'error', with error message).
12150: 2. result of deletions ('ok' or 'error', with error message).
12151: 3. reference to hash of any new or updated access controls.
12152: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12153: key = integer (inbound ID)
12154: value = uniqueID
1.747 albertel 12155:
1.608 albertel 12156: =back
12157:
1.243 albertel 12158: =head2 HTTP Helper Routines
12159:
12160: =over 4
12161:
1.191 harris41 12162: =item *
12163:
12164: escape() : unpack non-word characters into CGI-compatible hex codes
12165:
12166: =item *
12167:
12168: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12169:
1.243 albertel 12170: =back
12171:
12172: =head1 PRIVATE SUBROUTINES
12173:
12174: =head2 Underlying communication routines (Shouldn't call)
12175:
12176: =over 4
12177:
12178: =item *
12179:
12180: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12181:
12182: =item *
12183:
12184: reply() : uses subreply to send a message to remote machine, logs all failures
12185:
12186: =item *
12187:
12188: critical() : passes a critical message to another server; if cannot
12189: get through then place message in connection buffer directory and
12190: returns con_delayed, if incapable of saving message, returns
12191: con_failed
12192:
12193: =item *
12194:
12195: reconlonc() : tries to reconnect lonc client processes.
12196:
12197: =back
12198:
12199: =head2 Resource Access Logging
12200:
12201: =over 4
12202:
12203: =item *
12204:
12205: flushcourselogs() : flush (save) buffer logs and access logs
12206:
12207: =item *
12208:
12209: courselog($what) : save message for course in hash
12210:
12211: =item *
12212:
12213: courseacclog($what) : save message for course using &courselog(). Perform
12214: special processing for specific resource types (problems, exams, quizzes, etc).
12215:
1.191 harris41 12216: =item *
12217:
12218: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12219: as a PerlChildExitHandler
1.243 albertel 12220:
12221: =back
12222:
12223: =head2 Other
12224:
12225: =over 4
12226:
12227: =item *
12228:
12229: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12230:
12231: =back
12232:
12233: =cut
1.877 foxr 12234:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>