Annotation of loncom/lonnet/perl/lonnet.pm, revision 1.1183
1.1 albertel 1: # The LearningOnline Network
2: # TCP networking package
1.12 www 3: #
1.1183 ! raeburn 4: # $Id: lonnet.pm,v 1.1182 2012/08/03 10:55:53 foxr 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.1182 foxr 78:
1.1173 foxr 79: use Encode;
80:
1.871 albertel 81: use vars qw(%perlvar %spareid %pr %prp $memcache %packagetab $tmpdir
1.1138 raeburn 82: $_64bit %env %protocol %loncaparevs %serverhomeIDs %needsrelease
83: %managerstab);
1.871 albertel 84:
85: my (%badServerCache, $memcache, %courselogs, %accesshash, %domainrolehash,
86: %userrolehash, $processmarker, $dumpcount, %coursedombuf,
87: %coursenumbuf, %coursehombuf, %coursedescrbuf, %courseinstcodebuf,
1.958 www 88: %courseownerbuf, %coursetypebuf,$locknum);
1.403 www 89:
1.1 albertel 90: use IO::Socket;
1.31 www 91: use GDBM_File;
1.208 albertel 92: use HTML::LCParser;
1.88 www 93: use Fcntl qw(:flock);
1.870 albertel 94: use Storable qw(thaw nfreeze);
1.539 albertel 95: use Time::HiRes qw( gettimeofday tv_interval );
1.599 albertel 96: use Cache::Memcached;
1.676 albertel 97: use Digest::MD5;
1.790 albertel 98: use Math::Random;
1.1024 raeburn 99: use File::MMagic;
1.807 albertel 100: use LONCAPA qw(:DEFAULT :match);
1.740 www 101: use LONCAPA::Configuration;
1.1160 www 102: use LONCAPA::lonmetadata;
1.1167 droeschl 103: use LONCAPA::Lond;
1.1117 foxr 104:
1.1090 raeburn 105: use File::Copy;
1.676 albertel 106:
1.195 www 107: my $readit;
1.550 foxr 108: my $max_connection_retries = 10; # Or some such value.
1.1 albertel 109:
1.619 albertel 110: require Exporter;
111:
112: our @ISA = qw (Exporter);
113: our @EXPORT = qw(%env);
114:
1.449 matthew 115:
1.1 albertel 116: # --------------------------------------------------------------------- Logging
1.729 www 117: {
118: my $logid;
119: sub instructor_log {
1.957 raeburn 120: my ($hash_name,$storehash,$delflag,$uname,$udom,$cnum,$cdom)=@_;
121: if (($cnum eq '') || ($cdom eq '')) {
122: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
123: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
124: }
1.729 www 125: $logid++;
1.957 raeburn 126: my $now = time();
127: my $id=$now.'00000'.$$.'00000'.$logid;
1.729 www 128: return &Apache::lonnet::put('nohist_'.$hash_name,
1.730 www 129: { $id => {
130: 'exe_uname' => $env{'user.name'},
131: 'exe_udom' => $env{'user.domain'},
1.957 raeburn 132: 'exe_time' => $now,
1.730 www 133: 'exe_ip' => $ENV{'REMOTE_ADDR'},
134: 'delflag' => $delflag,
135: 'logentry' => $storehash,
136: 'uname' => $uname,
137: 'udom' => $udom,
138: }
1.957 raeburn 139: },$cdom,$cnum);
1.729 www 140: }
141: }
1.1 albertel 142:
1.163 harris41 143: sub logtouch {
144: my $execdir=$perlvar{'lonDaemons'};
1.448 albertel 145: unless (-e "$execdir/logs/lonnet.log") {
146: open(my $fh,">>$execdir/logs/lonnet.log");
1.163 harris41 147: close $fh;
148: }
149: my ($wwwuid,$wwwgid)=(getpwnam('www'))[2,3];
150: chown($wwwuid,$wwwgid,$execdir.'/logs/lonnet.log');
151: }
152:
1.1 albertel 153: sub logthis {
154: my $message=shift;
155: my $execdir=$perlvar{'lonDaemons'};
156: my $now=time;
157: my $local=localtime($now);
1.448 albertel 158: if (open(my $fh,">>$execdir/logs/lonnet.log")) {
1.986 foxr 159: my $logstring = $local. " ($$): ".$message."\n"; # Keep any \'s in string.
160: print $fh $logstring;
1.448 albertel 161: close($fh);
162: }
1.1 albertel 163: return 1;
164: }
165:
166: sub logperm {
167: my $message=shift;
168: my $execdir=$perlvar{'lonDaemons'};
169: my $now=time;
170: my $local=localtime($now);
1.448 albertel 171: if (open(my $fh,">>$execdir/logs/lonnet.perm.log")) {
172: print $fh "$now:$message:$local\n";
173: close($fh);
174: }
1.1 albertel 175: return 1;
176: }
177:
1.850 albertel 178: sub create_connection {
1.853 albertel 179: my ($hostname,$lonid) = @_;
1.851 albertel 180: my $client=IO::Socket::UNIX->new(Peer => $perlvar{'lonSockCreate'},
1.850 albertel 181: Type => SOCK_STREAM,
182: Timeout => 10);
183: return 0 if (!$client);
1.890 albertel 184: print $client (join(':',$hostname,$lonid,&machine_ids($hostname))."\n");
1.850 albertel 185: my $result = <$client>;
186: chomp($result);
187: return 1 if ($result eq 'done');
188: return 0;
189: }
190:
1.983 raeburn 191: sub get_server_timezone {
192: my ($cnum,$cdom) = @_;
193: my $home=&homeserver($cnum,$cdom);
194: if ($home ne 'no_host') {
195: my $cachetime = 24*3600;
196: my ($timezone,$cached)=&is_cached_new('servertimezone',$home);
197: if (defined($cached)) {
198: return $timezone;
199: } else {
200: my $timezone = &reply('servertimezone',$home);
201: return &do_cache_new('servertimezone',$home,$timezone,$cachetime);
202: }
203: }
204: }
1.850 albertel 205:
1.1106 raeburn 206: sub get_server_distarch {
207: my ($lonhost,$ignore_cache) = @_;
208: if (defined($lonhost)) {
209: if (!defined(&hostname($lonhost))) {
210: return;
211: }
212: my $cachetime = 12*3600;
213: if (!$ignore_cache) {
214: my ($distarch,$cached)=&is_cached_new('serverdistarch',$lonhost);
215: if (defined($cached)) {
216: return $distarch;
217: }
218: }
219: my $rep = &reply('serverdistarch',$lonhost);
220: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
221: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
222: $rep eq '') {
223: return &do_cache_new('serverdistarch',$lonhost,$rep,$cachetime);
224: }
225: }
226: return;
227: }
228:
1.993 raeburn 229: sub get_server_loncaparev {
1.1073 raeburn 230: my ($dom,$lonhost,$ignore_cache,$caller) = @_;
1.993 raeburn 231: if (defined($lonhost)) {
232: if (!defined(&hostname($lonhost))) {
233: undef($lonhost);
234: }
235: }
236: if (!defined($lonhost)) {
237: if (defined(&domain($dom,'primary'))) {
238: $lonhost=&domain($dom,'primary');
239: if ($lonhost eq 'no_host') {
240: undef($lonhost);
241: }
242: }
243: }
244: if (defined($lonhost)) {
1.1073 raeburn 245: my $cachetime = 12*3600;
246: if (!$ignore_cache) {
247: my ($loncaparev,$cached)=&is_cached_new('serverloncaparev',$lonhost);
248: if (defined($cached)) {
249: return $loncaparev;
250: }
251: }
252: my ($answer,$loncaparev);
253: my @ids=¤t_machine_ids();
254: if (grep(/^\Q$lonhost\E$/,@ids)) {
255: $answer = $perlvar{'lonVersion'};
1.1081 raeburn 256: if ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 257: $loncaparev = $1;
258: }
259: } else {
260: $answer = &reply('serverloncaparev',$lonhost);
261: if (($answer eq 'unknown_cmd') || ($answer eq 'con_lost')) {
262: if ($caller eq 'loncron') {
263: my $ua=new LWP::UserAgent;
1.1082 raeburn 264: $ua->timeout(4);
1.1073 raeburn 265: my $protocol = $protocol{$lonhost};
266: $protocol = 'http' if ($protocol ne 'https');
267: my $url = $protocol.'://'.&hostname($lonhost).'/adm/about.html';
268: my $request=new HTTP::Request('GET',$url);
269: my $response=$ua->request($request);
270: unless ($response->is_error()) {
271: my $content = $response->content;
1.1081 raeburn 272: if ($content =~ /<p>VERSION\:\s*([\w.\-]+)<\/p>/) {
1.1073 raeburn 273: $loncaparev = $1;
274: }
275: }
276: } else {
277: $loncaparev = $loncaparevs{$lonhost};
278: }
1.1081 raeburn 279: } elsif ($answer =~ /^[\'\"]?([\w.\-]+)[\'\"]?$/) {
1.1073 raeburn 280: $loncaparev = $1;
281: }
1.993 raeburn 282: }
1.1073 raeburn 283: return &do_cache_new('serverloncaparev',$lonhost,$loncaparev,$cachetime);
1.993 raeburn 284: }
285: }
286:
1.1074 raeburn 287: sub get_server_homeID {
288: my ($hostname,$ignore_cache,$caller) = @_;
289: unless ($ignore_cache) {
290: my ($serverhomeID,$cached)=&is_cached_new('serverhomeID',$hostname);
291: if (defined($cached)) {
292: return $serverhomeID;
293: }
294: }
295: my $cachetime = 12*3600;
296: my $serverhomeID;
297: if ($caller eq 'loncron') {
298: my @machine_ids = &machine_ids($hostname);
299: foreach my $id (@machine_ids) {
300: my $response = &reply('serverhomeID',$id);
301: unless (($response eq 'unknown_cmd') || ($response eq 'con_lost')) {
302: $serverhomeID = $response;
303: last;
304: }
305: }
306: if ($serverhomeID eq '') {
307: $serverhomeID = $machine_ids[-1];
308: }
309: } else {
310: $serverhomeID = $serverhomeIDs{$hostname};
311: }
312: return &do_cache_new('serverhomeID',$hostname,$serverhomeID,$cachetime);
313: }
314:
1.1121 raeburn 315: sub get_remote_globals {
316: my ($lonhost,$whathash,$ignore_cache) = @_;
1.1125 raeburn 317: my ($result,%returnhash,%whatneeded);
318: if (ref($whathash) eq 'HASH') {
1.1121 raeburn 319: foreach my $what (sort(keys(%{$whathash}))) {
320: my $hashid = $lonhost.'-'.$what;
1.1125 raeburn 321: my ($response,$cached);
1.1121 raeburn 322: unless ($ignore_cache) {
1.1125 raeburn 323: ($response,$cached)=&is_cached_new('lonnetglobal',$hashid);
1.1121 raeburn 324: }
325: if (defined($cached)) {
1.1125 raeburn 326: $returnhash{$what} = $response;
1.1121 raeburn 327: } else {
1.1125 raeburn 328: $whatneeded{$what} = 1;
1.1121 raeburn 329: }
330: }
1.1125 raeburn 331: if (keys(%whatneeded) == 0) {
332: $result = 'ok';
333: } else {
1.1121 raeburn 334: my $requested = &freeze_escape(\%whatneeded);
335: my $rep=&reply('readlonnetglobal:'.$requested,$lonhost);
1.1125 raeburn 336: if (($rep=~/^(refused|rejected|error)/) || ($rep eq 'con_lost') ||
337: ($rep eq 'unknown_cmd')) {
338: $result = $rep;
339: } else {
340: $result = 'ok';
1.1121 raeburn 341: my @pairs=split(/\&/,$rep);
1.1125 raeburn 342: foreach my $item (@pairs) {
343: my ($key,$value)=split(/=/,$item,2);
344: my $what = &unescape($key);
345: my $hashid = $lonhost.'-'.$what;
346: $returnhash{$what}=&thaw_unescape($value);
347: &do_cache_new('lonnetglobal',$hashid,$returnhash{$what},600);
1.1121 raeburn 348: }
349: }
350: }
351: }
1.1125 raeburn 352: return ($result,\%returnhash);
1.1121 raeburn 353: }
354:
1.1124 raeburn 355: sub remote_devalidate_cache {
356: my ($lonhost,$name,$id) = @_;
1.1130 raeburn 357: my $response = &reply('devalidatecache:'.&escape($name).':'.&escape($id),$lonhost);
1.1124 raeburn 358: return $response;
359: }
360:
1.1 albertel 361: # -------------------------------------------------- Non-critical communication
362: sub subreply {
363: my ($cmd,$server)=@_;
1.838 albertel 364: my $peerfile="$perlvar{'lonSockDir'}/".&hostname($server);
1.549 foxr 365: #
366: # With loncnew process trimming, there's a timing hole between lonc server
367: # process exit and the master server picking up the listen on the AF_UNIX
368: # socket. In that time interval, a lock file will exist:
369:
370: my $lockfile=$peerfile.".lock";
371: while (-e $lockfile) { # Need to wait for the lockfile to disappear.
372: sleep(1);
373: }
374: # At this point, either a loncnew parent is listening or an old lonc
1.550 foxr 375: # or loncnew child is listening so we can connect or everything's dead.
1.549 foxr 376: #
1.550 foxr 377: # We'll give the connection a few tries before abandoning it. If
378: # connection is not possible, we'll con_lost back to the client.
379: #
380: my $client;
381: for (my $retries = 0; $retries < $max_connection_retries; $retries++) {
382: $client=IO::Socket::UNIX->new(Peer =>"$peerfile",
383: Type => SOCK_STREAM,
384: Timeout => 10);
1.869 albertel 385: if ($client) {
1.550 foxr 386: last; # Connected!
1.850 albertel 387: } else {
1.853 albertel 388: &create_connection(&hostname($server),$server);
1.550 foxr 389: }
1.850 albertel 390: sleep(1); # Try again later if failed connection.
1.550 foxr 391: }
392: my $answer;
393: if ($client) {
1.704 albertel 394: print $client "sethost:$server:$cmd\n";
1.550 foxr 395: $answer=<$client>;
396: if (!$answer) { $answer="con_lost"; }
397: chomp($answer);
398: } else {
399: $answer = 'con_lost'; # Failed connection.
400: }
1.1 albertel 401: return $answer;
402: }
403:
404: sub reply {
405: my ($cmd,$server)=@_;
1.838 albertel 406: unless (defined(&hostname($server))) { return 'no_such_host'; }
1.1 albertel 407: my $answer=subreply($cmd,$server);
1.65 www 408: if (($answer=~/^refused/) || ($answer=~/^rejected/)) {
1.672 albertel 409: &logthis("<font color=\"blue\">WARNING:".
1.12 www 410: " $cmd to $server returned $answer</font>");
411: }
1.1 albertel 412: return $answer;
413: }
414:
415: # ----------------------------------------------------------- Send USR1 to lonc
416:
417: sub reconlonc {
1.891 albertel 418: my ($lonid) = @_;
419: my $hostname = &hostname($lonid);
420: if ($lonid) {
421: my $peerfile="$perlvar{'lonSockDir'}/$hostname";
422: if ($hostname && -e $peerfile) {
423: &logthis("Trying to reconnect lonc for $lonid ($hostname)");
424: my $client=IO::Socket::UNIX->new(Peer => $peerfile,
425: Type => SOCK_STREAM,
426: Timeout => 10);
427: if ($client) {
428: print $client ("reset_retries\n");
429: my $answer=<$client>;
430: #reset just this one.
431: }
432: }
433: return;
434: }
435:
1.836 www 436: &logthis("Trying to reconnect lonc");
1.1 albertel 437: my $loncfile="$perlvar{'lonDaemons'}/logs/lonc.pid";
1.448 albertel 438: if (open(my $fh,"<$loncfile")) {
1.1 albertel 439: my $loncpid=<$fh>;
440: chomp($loncpid);
441: if (kill 0 => $loncpid) {
442: &logthis("lonc at pid $loncpid responding, sending USR1");
443: kill USR1 => $loncpid;
444: sleep 1;
1.836 www 445: } else {
1.12 www 446: &logthis(
1.672 albertel 447: "<font color=\"blue\">WARNING:".
1.12 www 448: " lonc at pid $loncpid not responding, giving up</font>");
1.1 albertel 449: }
450: } else {
1.836 www 451: &logthis('<font color="blue">WARNING: lonc not running, giving up</font>');
1.1 albertel 452: }
453: }
454:
455: # ------------------------------------------------------ Critical communication
1.12 www 456:
1.1 albertel 457: sub critical {
458: my ($cmd,$server)=@_;
1.838 albertel 459: unless (&hostname($server)) {
1.672 albertel 460: &logthis("<font color=\"blue\">WARNING:".
1.89 www 461: " Critical message to unknown server ($server)</font>");
462: return 'no_such_host';
463: }
1.1 albertel 464: my $answer=reply($cmd,$server);
465: if ($answer eq 'con_lost') {
466: &reconlonc("$perlvar{'lonSockDir'}/$server");
1.589 albertel 467: my $answer=reply($cmd,$server);
1.1 albertel 468: if ($answer eq 'con_lost') {
469: my $now=time;
470: my $middlename=$cmd;
1.5 www 471: $middlename=substr($middlename,0,16);
1.1 albertel 472: $middlename=~s/\W//g;
473: my $dfilename=
1.305 www 474: "$perlvar{'lonSockDir'}/delayed/$now.$dumpcount.$$.$middlename.$server";
475: $dumpcount++;
1.1 albertel 476: {
1.448 albertel 477: my $dfh;
478: if (open($dfh,">$dfilename")) {
479: print $dfh "$cmd\n";
480: close($dfh);
481: }
1.1 albertel 482: }
483: sleep 2;
484: my $wcmd='';
485: {
1.448 albertel 486: my $dfh;
487: if (open($dfh,"<$dfilename")) {
488: $wcmd=<$dfh>;
489: close($dfh);
490: }
1.1 albertel 491: }
492: chomp($wcmd);
1.7 www 493: if ($wcmd eq $cmd) {
1.672 albertel 494: &logthis("<font color=\"blue\">WARNING: ".
1.12 www 495: "Connection buffer $dfilename: $cmd</font>");
1.1 albertel 496: &logperm("D:$server:$cmd");
497: return 'con_delayed';
498: } else {
1.672 albertel 499: &logthis("<font color=\"red\">CRITICAL:"
1.12 www 500: ." Critical connection failed: $server $cmd</font>");
1.1 albertel 501: &logperm("F:$server:$cmd");
502: return 'con_failed';
503: }
504: }
505: }
506: return $answer;
1.405 albertel 507: }
508:
1.755 albertel 509: # ------------------------------------------- check if return value is an error
510:
511: sub error {
512: my ($result) = @_;
1.756 albertel 513: if ($result =~ /^(con_lost|no_such_host|error: (\d+) (.*))/) {
1.755 albertel 514: if ($2 == 2) { return undef; }
515: return $1;
516: }
517: return undef;
518: }
519:
1.783 albertel 520: sub convert_and_load_session_env {
521: my ($lonidsdir,$handle)=@_;
522: my @profile;
523: {
1.917 albertel 524: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
525: if (!$opened) {
1.915 albertel 526: return 0;
527: }
1.783 albertel 528: flock($idf,LOCK_SH);
529: @profile=<$idf>;
530: close($idf);
531: }
532: my %temp_env;
533: foreach my $line (@profile) {
1.786 albertel 534: if ($line !~ m/=/) {
535: return 0;
536: }
1.783 albertel 537: chomp($line);
538: my ($envname,$envvalue)=split(/=/,$line,2);
539: $temp_env{&unescape($envname)} = &unescape($envvalue);
540: }
541: unlink("$lonidsdir/$handle.id");
542: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",&GDBM_WRCREAT(),
543: 0640)) {
544: %disk_env = %temp_env;
545: @env{keys(%temp_env)} = @disk_env{keys(%temp_env)};
546: untie(%disk_env);
547: }
1.786 albertel 548: return 1;
1.783 albertel 549: }
550:
1.374 www 551: # ------------------------------------------- Transfer profile into environment
1.780 albertel 552: my $env_loaded;
553: sub transfer_profile_to_env {
1.788 albertel 554: my ($lonidsdir,$handle,$force_transfer) = @_;
555: if (!$force_transfer && $env_loaded) { return; }
1.374 www 556:
1.720 albertel 557: if (!defined($lonidsdir)) {
558: $lonidsdir = $perlvar{'lonIDsDir'};
559: }
560: if (!defined($handle)) {
561: ($handle) = ($env{'user.environment'} =~m|/([^/]+)\.id$| );
562: }
563:
1.786 albertel 564: my $convert;
565: {
1.917 albertel 566: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
567: if (!$opened) {
1.915 albertel 568: return;
569: }
1.786 albertel 570: flock($idf,LOCK_SH);
571: if (tie(my %disk_env,'GDBM_File',"$lonidsdir/$handle.id",
572: &GDBM_READER(),0640)) {
573: @env{keys(%disk_env)} = @disk_env{keys(%disk_env)};
574: untie(%disk_env);
575: } else {
576: $convert = 1;
577: }
578: }
579: if ($convert) {
580: if (!&convert_and_load_session_env($lonidsdir,$handle)) {
581: &logthis("Failed to load session, or convert session.");
582: }
1.374 www 583: }
1.783 albertel 584:
1.786 albertel 585: my %remove;
1.783 albertel 586: while ( my $envname = each(%env) ) {
1.433 matthew 587: if (my ($key,$time) = ($envname =~ /^(cgi\.(\d+)_\d+\.)/)) {
588: if ($time < time-300) {
1.783 albertel 589: $remove{$key}++;
1.433 matthew 590: }
591: }
592: }
1.783 albertel 593:
1.619 albertel 594: $env{'user.environment'} = "$lonidsdir/$handle.id";
1.780 albertel 595: $env_loaded=1;
1.783 albertel 596: foreach my $expired_key (keys(%remove)) {
1.433 matthew 597: &delenv($expired_key);
1.374 www 598: }
1.1 albertel 599: }
600:
1.916 albertel 601: # ---------------------------------------------------- Check for valid session
602: sub check_for_valid_session {
1.1155 raeburn 603: my ($r,$name) = @_;
1.916 albertel 604: my %cookies=CGI::Cookie->parse($r->header_in('Cookie'));
1.1155 raeburn 605: if ($name eq '') {
606: $name = 'lonID';
607: }
608: my $lonid=$cookies{$name};
1.916 albertel 609: return undef if (!$lonid);
610:
611: my $handle=&LONCAPA::clean_handle($lonid->value);
1.1155 raeburn 612: my $lonidsdir;
613: if ($name eq 'lonDAV') {
614: $lonidsdir=$r->dir_config('lonDAVsessDir');
615: } else {
616: $lonidsdir=$r->dir_config('lonIDsDir');
617: }
1.916 albertel 618: return undef if (!-e "$lonidsdir/$handle.id");
619:
1.917 albertel 620: my $opened = open(my $idf,'+<',"$lonidsdir/$handle.id");
621: return undef if (!$opened);
1.916 albertel 622:
623: flock($idf,LOCK_SH);
624: my %disk_env;
625: if (!tie(%disk_env,'GDBM_File',"$lonidsdir/$handle.id",
626: &GDBM_READER(),0640)) {
627: return undef;
628: }
629:
630: if (!defined($disk_env{'user.name'})
631: || !defined($disk_env{'user.domain'})) {
632: return undef;
633: }
634: return $handle;
635: }
636:
1.830 albertel 637: sub timed_flock {
638: my ($file,$lock_type) = @_;
639: my $failed=0;
640: eval {
641: local $SIG{__DIE__}='DEFAULT';
642: local $SIG{ALRM}=sub {
643: $failed=1;
644: die("failed lock");
645: };
646: alarm(13);
647: flock($file,$lock_type);
648: alarm(0);
649: };
650: if ($failed) {
651: return undef;
652: } else {
653: return 1;
654: }
655: }
656:
1.5 www 657: # ---------------------------------------------------------- Append Environment
658:
659: sub appenv {
1.949 raeburn 660: my ($newenv,$roles) = @_;
661: if (ref($newenv) eq 'HASH') {
662: foreach my $key (keys(%{$newenv})) {
663: my $refused = 0;
664: if (($key =~ /^user\.role/) || ($key =~ /^user\.priv/)) {
665: $refused = 1;
666: if (ref($roles) eq 'ARRAY') {
667: my ($type,$role) = ($key =~ /^user\.(role|priv)\.([^.]+)\./);
668: if (grep(/^\Q$role\E$/,@{$roles})) {
669: $refused = 0;
670: }
671: }
672: }
673: if ($refused) {
674: &logthis("<font color=\"blue\">WARNING: ".
675: "Attempt to modify environment ".$key." to ".$newenv->{$key}
676: .'</font>');
677: delete($newenv->{$key});
678: } else {
679: $env{$key}=$newenv->{$key};
680: }
681: }
682: my $opened = open(my $env_file,'+<',$env{'user.environment'});
683: if ($opened
684: && &timed_flock($env_file,LOCK_EX)
685: &&
686: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
687: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
688: while (my ($key,$value) = each(%{$newenv})) {
689: $disk_env{$key} = $value;
690: }
691: untie(%disk_env);
1.35 www 692: }
1.191 harris41 693: }
1.56 www 694: return 'ok';
695: }
696: # ----------------------------------------------------- Delete from Environment
697:
698: sub delenv {
1.1104 raeburn 699: my ($delthis,$regexp,$roles) = @_;
700: if (($delthis=~/^user\.role/) || ($delthis=~/^user\.priv/)) {
701: my $refused = 1;
702: if (ref($roles) eq 'ARRAY') {
703: my ($type,$role) = ($delthis =~ /^user\.(role|priv)\.([^.]+)\./);
704: if (grep(/^\Q$role\E$/,@{$roles})) {
705: $refused = 0;
706: }
707: }
708: if ($refused) {
709: &logthis("<font color=\"blue\">WARNING: ".
710: "Attempt to delete from environment ".$delthis);
711: return 'error';
712: }
1.56 www 713: }
1.917 albertel 714: my $opened = open(my $env_file,'+<',$env{'user.environment'});
715: if ($opened
1.915 albertel 716: && &timed_flock($env_file,LOCK_EX)
1.830 albertel 717: &&
718: tie(my %disk_env,'GDBM_File',$env{'user.environment'},
719: (&GDBM_WRITER()|&GDBM_NOLOCK()),0640)) {
1.783 albertel 720: foreach my $key (keys(%disk_env)) {
1.987 raeburn 721: if ($regexp) {
722: if ($key=~/^$delthis/) {
723: delete($env{$key});
724: delete($disk_env{$key});
725: }
726: } else {
727: if ($key=~/^\Q$delthis\E/) {
728: delete($env{$key});
729: delete($disk_env{$key});
730: }
731: }
1.448 albertel 732: }
1.783 albertel 733: untie(%disk_env);
1.5 www 734: }
735: return 'ok';
1.369 albertel 736: }
737:
1.790 albertel 738: sub get_env_multiple {
739: my ($name) = @_;
740: my @values;
741: if (defined($env{$name})) {
742: # exists is it an array
743: if (ref($env{$name})) {
744: @values=@{ $env{$name} };
745: } else {
746: $values[0]=$env{$name};
747: }
748: }
749: return(@values);
750: }
751:
1.958 www 752: # ------------------------------------------------------------------- Locking
753:
754: sub set_lock {
755: my ($text)=@_;
756: $locknum++;
757: my $id=$$.'-'.$locknum;
758: &appenv({'session.locks' => $env{'session.locks'}.','.$id,
759: 'session.lock.'.$id => $text});
760: return $id;
761: }
762:
763: sub get_locks {
764: my $num=0;
765: my %texts=();
766: foreach my $lock (split(/\,/,$env{'session.locks'})) {
767: if ($lock=~/\w/) {
768: $num++;
769: $texts{$lock}=$env{'session.lock.'.$lock};
770: }
771: }
772: return ($num,%texts);
773: }
774:
775: sub remove_lock {
776: my ($id)=@_;
777: my $newlocks='';
778: foreach my $lock (split(/\,/,$env{'session.locks'})) {
779: if (($lock=~/\w/) && ($lock ne $id)) {
780: $newlocks.=','.$lock;
781: }
782: }
783: &appenv({'session.locks' => $newlocks});
784: &delenv('session.lock.'.$id);
785: }
786:
787: sub remove_all_locks {
788: my $activelocks=$env{'session.locks'};
789: foreach my $lock (split(/\,/,$env{'session.locks'})) {
790: if ($lock=~/\w/) {
791: &remove_lock($lock);
792: }
793: }
794: }
795:
796:
1.369 albertel 797: # ------------------------------------------ Find out current server userload
798: sub userload {
799: my $numusers=0;
800: {
801: opendir(LONIDS,$perlvar{'lonIDsDir'});
802: my $filename;
803: my $curtime=time;
804: while ($filename=readdir(LONIDS)) {
1.925 albertel 805: next if ($filename eq '.' || $filename eq '..');
806: next if ($filename =~ /publicuser_\d+\.id/);
1.404 albertel 807: my ($mtime)=(stat($perlvar{'lonIDsDir'}.'/'.$filename))[9];
1.437 albertel 808: if ($curtime-$mtime < 1800) { $numusers++; }
1.369 albertel 809: }
810: closedir(LONIDS);
811: }
812: my $userloadpercent=0;
813: my $maxuserload=$perlvar{'lonUserLoadLim'};
814: if ($maxuserload) {
1.371 albertel 815: $userloadpercent=100*$numusers/$maxuserload;
1.369 albertel 816: }
1.372 albertel 817: $userloadpercent=sprintf("%.2f",$userloadpercent);
1.369 albertel 818: return $userloadpercent;
1.283 www 819: }
820:
1.1 albertel 821: # ------------------------------ Find server with least workload from spare.tab
1.11 www 822:
1.1 albertel 823: sub spareserver {
1.1083 raeburn 824: my ($loadpercent,$userloadpercent,$want_server_name,$udom) = @_;
1.784 albertel 825: my $spare_server;
1.370 albertel 826: if ($userloadpercent !~ /\d/) { $userloadpercent=0; }
1.784 albertel 827: my $lowest_load=($loadpercent > $userloadpercent) ? $loadpercent
828: : $userloadpercent;
1.1083 raeburn 829: my ($uint_dom,$remotesessions);
830: if (($udom ne '') && (&domain($udom) ne '')) {
831: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
832: $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
833: my %udomdefaults = &Apache::lonnet::get_domain_defaults($udom);
834: $remotesessions = $udomdefaults{'remotesessions'};
835: }
1.1123 raeburn 836: my $spareshash = &this_host_spares($udom);
837: if (ref($spareshash) eq 'HASH') {
838: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
839: foreach my $try_server (@{ $spareshash->{'primary'} }) {
840: if ($uint_dom) {
841: next unless (&spare_can_host($udom,$uint_dom,$remotesessions,
842: $try_server));
843: }
844: ($spare_server, $lowest_load) =
845: &compare_server_load($try_server, $spare_server, $lowest_load);
846: }
1.1083 raeburn 847: }
1.784 albertel 848:
1.1123 raeburn 849: my $found_server = ($spare_server ne '' && $lowest_load < 100);
850:
851: if (!$found_server) {
852: if (ref($spareshash->{'default'}) eq 'ARRAY') {
853: foreach my $try_server (@{ $spareshash->{'default'} }) {
854: if ($uint_dom) {
855: next unless (&spare_can_host($udom,$uint_dom,
856: $remotesessions,$try_server));
857: }
858: ($spare_server, $lowest_load) =
859: &compare_server_load($try_server, $spare_server, $lowest_load);
860: }
861: }
862: }
1.784 albertel 863: }
864:
865: if (!$want_server_name) {
1.968 raeburn 866: my $protocol = 'http';
867: if ($protocol{$spare_server} eq 'https') {
868: $protocol = $protocol{$spare_server};
869: }
1.1001 raeburn 870: if (defined($spare_server)) {
871: my $hostname = &hostname($spare_server);
1.1083 raeburn 872: if (defined($hostname)) {
1.1001 raeburn 873: $spare_server = $protocol.'://'.$hostname;
874: }
875: }
1.784 albertel 876: }
877: return $spare_server;
878: }
879:
880: sub compare_server_load {
881: my ($try_server, $spare_server, $lowest_load) = @_;
882:
883: my $loadans = &reply('load', $try_server);
884: my $userloadans = &reply('userload',$try_server);
885:
886: if ($loadans !~ /\d/ && $userloadans !~ /\d/) {
1.1114 raeburn 887: return ($spare_server, $lowest_load); #didn't get a number from the server
1.784 albertel 888: }
889:
890: my $load;
891: if ($loadans =~ /\d/) {
892: if ($userloadans =~ /\d/) {
893: #both are numbers, pick the bigger one
894: $load = ($loadans > $userloadans) ? $loadans
895: : $userloadans;
1.411 albertel 896: } else {
1.784 albertel 897: $load = $loadans;
1.411 albertel 898: }
1.784 albertel 899: } else {
900: $load = $userloadans;
901: }
902:
903: if (($load =~ /\d/) && ($load < $lowest_load)) {
904: $spare_server = $try_server;
905: $lowest_load = $load;
1.370 albertel 906: }
1.784 albertel 907: return ($spare_server,$lowest_load);
1.202 matthew 908: }
1.914 albertel 909:
910: # --------------------------- ask offload servers if user already has a session
911: sub find_existing_session {
912: my ($udom,$uname) = @_;
1.1123 raeburn 913: my $spareshash = &this_host_spares($udom);
914: if (ref($spareshash) eq 'HASH') {
915: if (ref($spareshash->{'primary'}) eq 'ARRAY') {
916: foreach my $try_server (@{ $spareshash->{'primary'} }) {
917: return $try_server if (&has_user_session($try_server, $udom, $uname));
918: }
919: }
920: if (ref($spareshash->{'default'}) eq 'ARRAY') {
921: foreach my $try_server (@{ $spareshash->{'default'} }) {
922: return $try_server if (&has_user_session($try_server, $udom, $uname));
923: }
924: }
1.914 albertel 925: }
926: return;
927: }
928:
929: # -------------------------------- ask if server already has a session for user
930: sub has_user_session {
931: my ($lonid,$udom,$uname) = @_;
932: my $result = &reply(join(':','userhassession',
933: map {&escape($_)} ($udom,$uname)),$lonid);
934: return 1 if ($result eq 'ok');
935:
936: return 0;
937: }
938:
1.1076 raeburn 939: # --------- determine least loaded server in a user's domain which allows login
940:
941: sub choose_server {
1.1115 raeburn 942: my ($udom,$checkloginvia) = @_;
1.1076 raeburn 943: my %domconfhash = &Apache::loncommon::get_domainconf($udom);
1.1077 raeburn 944: my %servers = &get_servers($udom);
1.1076 raeburn 945: my $lowest_load = 30000;
1.1151 raeburn 946: my ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 947: foreach my $lonhost (keys(%servers)) {
1.1115 raeburn 948: my $loginvia;
949: if ($checkloginvia) {
950: $loginvia = $domconfhash{$udom.'.login.loginvia_'.$lonhost};
1.1116 raeburn 951: if ($loginvia) {
952: my ($server,$path) = split(/:/,$loginvia);
953: ($login_host, $lowest_load) =
954: &compare_server_load($server, $login_host, $lowest_load);
955: if ($login_host eq $server) {
956: $portal_path = $path;
1.1151 raeburn 957: $isredirect = 1;
1.1116 raeburn 958: }
959: } else {
960: ($login_host, $lowest_load) =
961: &compare_server_load($lonhost, $login_host, $lowest_load);
962: if ($login_host eq $lonhost) {
963: $portal_path = '';
1.1151 raeburn 964: $isredirect = '';
1.1116 raeburn 965: }
966: }
967: } else {
1.1076 raeburn 968: ($login_host, $lowest_load) =
1.1116 raeburn 969: &compare_server_load($lonhost, $login_host, $lowest_load);
1.1076 raeburn 970: }
971: }
972: if ($login_host ne '') {
1.1116 raeburn 973: $hostname = &hostname($login_host);
1.1076 raeburn 974: }
1.1151 raeburn 975: return ($login_host,$hostname,$portal_path,$isredirect);
1.1076 raeburn 976: }
977:
1.202 matthew 978: # --------------------------------------------- Try to change a user's password
979:
980: sub changepass {
1.799 raeburn 981: my ($uname,$udom,$currentpass,$newpass,$server,$context)=@_;
1.202 matthew 982: $currentpass = &escape($currentpass);
983: $newpass = &escape($newpass);
1.1030 raeburn 984: my $lonhost = $perlvar{'lonHostID'};
985: my $answer = reply("encrypt:passwd:$udom:$uname:$currentpass:$newpass:$context:$lonhost",
1.202 matthew 986: $server);
987: if (! $answer) {
988: &logthis("No reply on password change request to $server ".
989: "by $uname in domain $udom.");
990: } elsif ($answer =~ "^ok") {
991: &logthis("$uname in $udom successfully changed their password ".
992: "on $server.");
993: } elsif ($answer =~ "^pwchange_failure") {
994: &logthis("$uname in $udom was unable to change their password ".
995: "on $server. The action was blocked by either lcpasswd ".
996: "or pwchange");
997: } elsif ($answer =~ "^non_authorized") {
998: &logthis("$uname in $udom did not get their password correct when ".
999: "attempting to change it on $server.");
1000: } elsif ($answer =~ "^auth_mode_error") {
1001: &logthis("$uname in $udom attempted to change their password despite ".
1002: "not being locally or internally authenticated on $server.");
1003: } elsif ($answer =~ "^unknown_user") {
1004: &logthis("$uname in $udom attempted to change their password ".
1005: "on $server but were unable to because $server is not ".
1006: "their home server.");
1007: } elsif ($answer =~ "^refused") {
1008: &logthis("$server refused to change $uname in $udom password because ".
1009: "it was sent an unencrypted request to change the password.");
1.1030 raeburn 1010: } elsif ($answer =~ "invalid_client") {
1011: &logthis("$server refused to change $uname in $udom password because ".
1012: "it was a reset by e-mail originating from an invalid server.");
1.202 matthew 1013: }
1014: return $answer;
1.1 albertel 1015: }
1016:
1.169 harris41 1017: # ----------------------- Try to determine user's current authentication scheme
1018:
1019: sub queryauthenticate {
1020: my ($uname,$udom)=@_;
1.456 albertel 1021: my $uhome=&homeserver($uname,$udom);
1022: if (!$uhome) {
1023: &logthis("User $uname at $udom is unknown when looking for authentication mechanism");
1024: return 'no_host';
1025: }
1026: my $answer=reply("encrypt:currentauth:$udom:$uname",$uhome);
1027: if ($answer =~ /^(unknown_user|refused|con_lost)/) {
1028: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.169 harris41 1029: }
1.456 albertel 1030: return $answer;
1.169 harris41 1031: }
1032:
1.1 albertel 1033: # --------- Try to authenticate user from domain's lib servers (first this one)
1.11 www 1034:
1.1 albertel 1035: sub authenticate {
1.1073 raeburn 1036: my ($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)=@_;
1.807 albertel 1037: $upass=&escape($upass);
1038: $uname= &LONCAPA::clean_username($uname);
1.836 www 1039: my $uhome=&homeserver($uname,$udom,1);
1.952 raeburn 1040: my $newhome;
1.836 www 1041: if ((!$uhome) || ($uhome eq 'no_host')) {
1042: # Maybe the machine was offline and only re-appeared again recently?
1043: &reconlonc();
1044: # One more
1.952 raeburn 1045: $uhome=&homeserver($uname,$udom,1);
1046: if (($uhome eq 'no_host') && $checkdefauth) {
1047: if (defined(&domain($udom,'primary'))) {
1048: $newhome=&domain($udom,'primary');
1049: }
1050: if ($newhome ne '') {
1051: $uhome = $newhome;
1052: }
1053: }
1.836 www 1054: if ((!$uhome) || ($uhome eq 'no_host')) {
1055: &logthis("User $uname at $udom is unknown in authenticate");
1.952 raeburn 1056: return 'no_host';
1057: }
1.1 albertel 1058: }
1.1073 raeburn 1059: my $answer=reply("encrypt:auth:$udom:$uname:$upass:$checkdefauth:$clientcancheckhost",$uhome);
1.471 albertel 1060: if ($answer eq 'authorized') {
1.952 raeburn 1061: if ($newhome) {
1062: &logthis("User $uname at $udom authorized by $uhome, but needs account");
1063: return 'no_account_on_host';
1064: } else {
1065: &logthis("User $uname at $udom authorized by $uhome");
1066: return $uhome;
1067: }
1.471 albertel 1068: }
1069: if ($answer eq 'non_authorized') {
1070: &logthis("User $uname at $udom rejected by $uhome");
1071: return 'no_host';
1.9 www 1072: }
1.471 albertel 1073: &logthis("User $uname at $udom threw error $answer when checking authentication mechanism");
1.1 albertel 1074: return 'no_host';
1075: }
1076:
1.1073 raeburn 1077: sub can_host_session {
1.1074 raeburn 1078: my ($udom,$lonhost,$remoterev,$remotesessions,$hostedsessions) = @_;
1.1073 raeburn 1079: my $canhost = 1;
1.1074 raeburn 1080: my $host_idn = &Apache::lonnet::internet_dom($lonhost);
1.1073 raeburn 1081: if (ref($remotesessions) eq 'HASH') {
1082: if (ref($remotesessions->{'excludedomain'}) eq 'ARRAY') {
1.1074 raeburn 1083: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'excludedomain'}})) {
1.1073 raeburn 1084: $canhost = 0;
1085: } else {
1086: $canhost = 1;
1087: }
1088: }
1089: if (ref($remotesessions->{'includedomain'}) eq 'ARRAY') {
1.1074 raeburn 1090: if (grep(/^\Q$host_idn\E$/,@{$remotesessions->{'includedomain'}})) {
1.1073 raeburn 1091: $canhost = 1;
1092: } else {
1093: $canhost = 0;
1094: }
1095: }
1096: if ($canhost) {
1097: if ($remotesessions->{'version'} ne '') {
1098: my ($reqmajor,$reqminor) = ($remotesessions->{'version'} =~ /^(\d+)\.(\d+)$/);
1099: if ($reqmajor ne '' && $reqminor ne '') {
1100: if ($remoterev =~ /^\'?(\d+)\.(\d+)/) {
1101: my $major = $1;
1102: my $minor = $2;
1103: if (($major < $reqmajor ) ||
1104: (($major == $reqmajor) && ($minor < $reqminor))) {
1105: $canhost = 0;
1106: }
1107: } else {
1108: $canhost = 0;
1109: }
1110: }
1111: }
1112: }
1113: }
1114: if ($canhost) {
1115: if (ref($hostedsessions) eq 'HASH') {
1.1120 raeburn 1116: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1117: my $uint_dom = &Apache::lonnet::internet_dom($uprimary_id);
1.1073 raeburn 1118: if (ref($hostedsessions->{'excludedomain'}) eq 'ARRAY') {
1.1120 raeburn 1119: if (($uint_dom ne '') &&
1120: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'excludedomain'}}))) {
1.1073 raeburn 1121: $canhost = 0;
1122: } else {
1123: $canhost = 1;
1124: }
1125: }
1126: if (ref($hostedsessions->{'includedomain'}) eq 'ARRAY') {
1.1120 raeburn 1127: if (($uint_dom ne '') &&
1128: (grep(/^\Q$uint_dom\E$/,@{$hostedsessions->{'includedomain'}}))) {
1.1073 raeburn 1129: $canhost = 1;
1130: } else {
1131: $canhost = 0;
1132: }
1133: }
1134: }
1135: }
1136: return $canhost;
1137: }
1138:
1.1083 raeburn 1139: sub spare_can_host {
1140: my ($udom,$uint_dom,$remotesessions,$try_server)=@_;
1141: my $canhost=1;
1142: my @intdoms;
1143: my $internet_names = &Apache::lonnet::get_internet_names($try_server);
1144: if (ref($internet_names) eq 'ARRAY') {
1145: @intdoms = @{$internet_names};
1146: }
1147: unless (grep(/^\Q$uint_dom\E$/,@intdoms)) {
1148: my $serverhomeID = &Apache::lonnet::get_server_homeID($try_server);
1149: my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1150: my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
1151: my $remoterev = &Apache::lonnet::get_server_loncaparev(undef,$try_server);
1152: $canhost = &can_host_session($udom,$try_server,$remoterev,
1153: $remotesessions,
1154: $defdomdefaults{'hostedsessions'});
1155: }
1156: return $canhost;
1157: }
1158:
1.1123 raeburn 1159: sub this_host_spares {
1160: my ($dom) = @_;
1.1126 raeburn 1161: my ($dom_in_use,$lonhost_in_use,$result);
1.1123 raeburn 1162: my @hosts = ¤t_machine_ids();
1163: foreach my $lonhost (@hosts) {
1164: if (&host_domain($lonhost) eq $dom) {
1.1126 raeburn 1165: $dom_in_use = $dom;
1166: $lonhost_in_use = $lonhost;
1.1123 raeburn 1167: last;
1168: }
1169: }
1.1126 raeburn 1170: if ($dom_in_use ne '') {
1171: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1172: }
1173: if (ref($result) ne 'HASH') {
1174: $lonhost_in_use = $perlvar{'lonHostID'};
1175: $dom_in_use = &host_domain($lonhost_in_use);
1176: $result = &spares_for_offload($dom_in_use,$lonhost_in_use);
1177: if (ref($result) ne 'HASH') {
1178: $result = \%spareid;
1179: }
1180: }
1181: return $result;
1182: }
1183:
1184: sub spares_for_offload {
1185: my ($dom_in_use,$lonhost_in_use) = @_;
1186: my ($result,$cached)=&is_cached_new('spares',$dom_in_use);
1.1123 raeburn 1187: if (defined($cached)) {
1188: return $result;
1189: } else {
1.1126 raeburn 1190: my $cachetime = 60*60*24;
1191: my %domconfig =
1192: &Apache::lonnet::get_dom('configuration',['usersessions'],$dom_in_use);
1193: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1194: if (ref($domconfig{'usersessions'}{'spares'}) eq 'HASH') {
1195: if (ref($domconfig{'usersessions'}{'spares'}{$lonhost_in_use}) eq 'HASH') {
1196: return &do_cache_new('spares',$dom_in_use,$domconfig{'usersessions'}{'spares'}{$lonhost_in_use},$cachetime);
1.1123 raeburn 1197: }
1198: }
1199: }
1200: }
1.1126 raeburn 1201: return;
1.1123 raeburn 1202: }
1203:
1.1129 raeburn 1204: sub get_lonbalancer_config {
1205: my ($servers) = @_;
1206: my ($currbalancer,$currtargets);
1207: if (ref($servers) eq 'HASH') {
1208: foreach my $server (keys(%{$servers})) {
1209: my %what = (
1210: spareid => 1,
1211: perlvar => 1,
1212: );
1213: my ($result,$returnhash) = &get_remote_globals($server,\%what);
1214: if ($result eq 'ok') {
1215: if (ref($returnhash) eq 'HASH') {
1216: if (ref($returnhash->{'perlvar'}) eq 'HASH') {
1217: if ($returnhash->{'perlvar'}->{'lonBalancer'} eq 'yes') {
1218: $currbalancer = $server;
1219: $currtargets = {};
1220: if (ref($returnhash->{'spareid'}) eq 'HASH') {
1221: if (ref($returnhash->{'spareid'}->{'primary'}) eq 'ARRAY') {
1222: $currtargets->{'primary'} = $returnhash->{'spareid'}->{'primary'};
1223: }
1224: if (ref($returnhash->{'spareid'}->{'default'}) eq 'ARRAY') {
1225: $currtargets->{'default'} = $returnhash->{'spareid'}->{'default'};
1226: }
1227: }
1228: last;
1229: }
1230: }
1231: }
1232: }
1233: }
1234: }
1235: return ($currbalancer,$currtargets);
1236: }
1237:
1238: sub check_loadbalancing {
1239: my ($uname,$udom) = @_;
1240: my ($is_balancer,$dom_in_use,$homeintdom,$rule_in_effect,
1241: $offloadto,$otherserver);
1242: my $lonhost = $perlvar{'lonHostID'};
1.1175 raeburn 1243: my @hosts = ¤t_machine_ids();
1.1129 raeburn 1244: my $uprimary_id = &Apache::lonnet::domain($udom,'primary');
1245: my $uintdom = &Apache::lonnet::internet_dom($uprimary_id);
1246: my $intdom = &Apache::lonnet::internet_dom($lonhost);
1247: my $serverhomedom = &host_domain($lonhost);
1248:
1249: my $cachetime = 60*60*24;
1250:
1251: if (($uintdom ne '') && ($uintdom eq $intdom)) {
1252: $dom_in_use = $udom;
1253: $homeintdom = 1;
1254: } else {
1255: $dom_in_use = $serverhomedom;
1256: }
1257: my ($result,$cached)=&is_cached_new('loadbalancing',$dom_in_use);
1258: unless (defined($cached)) {
1259: my %domconfig =
1260: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$dom_in_use);
1261: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1262: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1263: }
1264: }
1265: if (ref($result) eq 'HASH') {
1266: my $currbalancer = $result->{'lonhost'};
1267: my $currtargets = $result->{'targets'};
1268: my $currrules = $result->{'rules'};
1269: if ($currbalancer ne '') {
1270: if (grep(/^\Q$currbalancer\E$/,@hosts)) {
1271: $is_balancer = 1;
1272: }
1273: }
1274: if ($is_balancer) {
1275: if (ref($currrules) eq 'HASH') {
1276: if ($homeintdom) {
1277: if ($uname ne '') {
1278: if (($currrules->{'_LC_adv'} ne '') || ($currrules->{'_LC_author'} ne '')) {
1279: my ($is_adv,$is_author) = &is_advanced_user($udom,$uname);
1280: if (($currrules->{'_LC_author'} ne '') && ($is_author)) {
1281: $rule_in_effect = $currrules->{'_LC_author'};
1282: } elsif (($currrules->{'_LC_adv'} ne '') && ($is_adv)) {
1283: $rule_in_effect = $currrules->{'_LC_adv'}
1284: }
1285: }
1286: if ($rule_in_effect eq '') {
1287: my %userenv = &userenvironment($udom,$uname,'inststatus');
1288: if ($userenv{'inststatus'} ne '') {
1289: my @statuses = map { &unescape($_); } split(/:/,$userenv{'inststatus'});
1290: my ($othertitle,$usertypes,$types) =
1291: &Apache::loncommon::sorted_inst_types($udom);
1292: if (ref($types) eq 'ARRAY') {
1293: foreach my $type (@{$types}) {
1294: if (grep(/^\Q$type\E$/,@statuses)) {
1295: if (exists($currrules->{$type})) {
1296: $rule_in_effect = $currrules->{$type};
1297: }
1298: }
1299: }
1300: }
1301: } else {
1302: if (exists($currrules->{'default'})) {
1303: $rule_in_effect = $currrules->{'default'};
1304: }
1305: }
1306: }
1307: } else {
1308: if (exists($currrules->{'default'})) {
1309: $rule_in_effect = $currrules->{'default'};
1310: }
1311: }
1312: } else {
1313: if ($currrules->{'_LC_external'} ne '') {
1314: $rule_in_effect = $currrules->{'_LC_external'};
1315: }
1316: }
1317: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1318: $uname,$udom);
1319: }
1320: }
1321: } elsif (($homeintdom) && ($udom ne $serverhomedom)) {
1322: my ($result,$cached)=&is_cached_new('loadbalancing',$serverhomedom);
1323: unless (defined($cached)) {
1324: my %domconfig =
1325: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$serverhomedom);
1326: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1.1130 raeburn 1327: $result = &do_cache_new('loadbalancing',$dom_in_use,$domconfig{'loadbalancing'},$cachetime);
1.1129 raeburn 1328: }
1329: }
1330: if (ref($result) eq 'HASH') {
1331: my $currbalancer = $result->{'lonhost'};
1332: my $currtargets = $result->{'targets'};
1333: my $currrules = $result->{'rules'};
1334:
1335: if ($currbalancer eq $lonhost) {
1336: $is_balancer = 1;
1337: if (ref($currrules) eq 'HASH') {
1338: if ($currrules->{'_LC_internetdom'} ne '') {
1339: $rule_in_effect = $currrules->{'_LC_internetdom'};
1340: }
1341: }
1342: $offloadto = &get_loadbalancer_targets($rule_in_effect,$currtargets,
1343: $uname,$udom);
1344: }
1345: } else {
1346: if ($perlvar{'lonBalancer'} eq 'yes') {
1347: $is_balancer = 1;
1348: $offloadto = &this_host_spares($dom_in_use);
1349: }
1350: }
1351: } else {
1352: if ($perlvar{'lonBalancer'} eq 'yes') {
1353: $is_balancer = 1;
1354: $offloadto = &this_host_spares($dom_in_use);
1355: }
1356: }
1.1176 raeburn 1357: if ($is_balancer) {
1358: my $lowest_load = 30000;
1359: if (ref($offloadto) eq 'HASH') {
1360: if (ref($offloadto->{'primary'}) eq 'ARRAY') {
1361: foreach my $try_server (@{$offloadto->{'primary'}}) {
1362: ($otherserver,$lowest_load) =
1363: &compare_server_load($try_server,$otherserver,$lowest_load);
1364: }
1.1129 raeburn 1365: }
1.1176 raeburn 1366: my $found_server = ($otherserver ne '' && $lowest_load < 100);
1.1129 raeburn 1367:
1.1176 raeburn 1368: if (!$found_server) {
1369: if (ref($offloadto->{'default'}) eq 'ARRAY') {
1370: foreach my $try_server (@{$offloadto->{'default'}}) {
1371: ($otherserver,$lowest_load) =
1372: &compare_server_load($try_server,$otherserver,$lowest_load);
1373: }
1374: }
1375: }
1376: } elsif (ref($offloadto) eq 'ARRAY') {
1377: if (@{$offloadto} == 1) {
1378: $otherserver = $offloadto->[0];
1379: } elsif (@{$offloadto} > 1) {
1380: foreach my $try_server (@{$offloadto}) {
1.1129 raeburn 1381: ($otherserver,$lowest_load) =
1382: &compare_server_load($try_server,$otherserver,$lowest_load);
1383: }
1384: }
1385: }
1.1176 raeburn 1386: if (($otherserver ne '') && (grep(/^\Q$otherserver\E$/,@hosts))) {
1387: $is_balancer = 0;
1388: if ($uname ne '' && $udom ne '') {
1389: if (($env{'user.name'} eq $uname) && ($env{'user.domain'} eq $udom)) {
1390:
1391: &appenv({'user.loadbalexempt' => $lonhost,
1392: 'user.loadbalcheck.time' => time});
1393: }
1.1129 raeburn 1394: }
1395: }
1396: }
1397: return ($is_balancer,$otherserver);
1398: }
1399:
1400: sub get_loadbalancer_targets {
1401: my ($rule_in_effect,$currtargets,$uname,$udom) = @_;
1402: my $offloadto;
1.1175 raeburn 1403: if ($rule_in_effect eq 'none') {
1404: return [$perlvar{'lonHostID'}];
1405: } elsif ($rule_in_effect eq '') {
1.1129 raeburn 1406: $offloadto = $currtargets;
1407: } else {
1408: if ($rule_in_effect eq 'homeserver') {
1409: my $homeserver = &homeserver($uname,$udom);
1410: if ($homeserver ne 'no_host') {
1411: $offloadto = [$homeserver];
1412: }
1413: } elsif ($rule_in_effect eq 'externalbalancer') {
1414: my %domconfig =
1415: &Apache::lonnet::get_dom('configuration',['loadbalancing'],$udom);
1416: if (ref($domconfig{'loadbalancing'}) eq 'HASH') {
1417: if ($domconfig{'loadbalancing'}{'lonhost'} ne '') {
1418: if (&hostname($domconfig{'loadbalancing'}{'lonhost'}) ne '') {
1419: $offloadto = [$domconfig{'loadbalancing'}{'lonhost'}];
1420: }
1421: }
1422: } else {
1.1178 raeburn 1423: my %servers = &internet_dom_servers($udom);
1.1129 raeburn 1424: my ($remotebalancer,$remotetargets) = &get_lonbalancer_config(\%servers);
1425: if (&hostname($remotebalancer) ne '') {
1426: $offloadto = [$remotebalancer];
1427: }
1428: }
1429: } elsif (&hostname($rule_in_effect) ne '') {
1430: $offloadto = [$rule_in_effect];
1431: }
1432: }
1433: return $offloadto;
1434: }
1435:
1.1127 raeburn 1436: sub internet_dom_servers {
1437: my ($dom) = @_;
1438: my (%uniqservers,%servers);
1439: my $primaryserver = &hostname(&domain($dom,'primary'));
1440: my @machinedoms = &machine_domains($primaryserver);
1441: foreach my $mdom (@machinedoms) {
1442: my %currservers = %servers;
1443: my %server = &get_servers($mdom);
1444: %servers = (%currservers,%server);
1445: }
1446: my %by_hostname;
1447: foreach my $id (keys(%servers)) {
1448: push(@{$by_hostname{$servers{$id}}},$id);
1449: }
1450: foreach my $hostname (sort(keys(%by_hostname))) {
1451: if (@{$by_hostname{$hostname}} > 1) {
1452: my $match = 0;
1453: foreach my $id (@{$by_hostname{$hostname}}) {
1454: if (&host_domain($id) eq $dom) {
1455: $uniqservers{$id} = $hostname;
1456: $match = 1;
1457: }
1458: }
1459: unless ($match) {
1460: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1461: }
1462: } else {
1463: $uniqservers{$by_hostname{$hostname}[0]} = $hostname;
1464: }
1465: }
1466: return %uniqservers;
1467: }
1468:
1.1 albertel 1469: # ---------------------- Find the homebase for a user from domain's lib servers
1.11 www 1470:
1.599 albertel 1471: my %homecache;
1.1 albertel 1472: sub homeserver {
1.230 stredwic 1473: my ($uname,$udom,$ignoreBadCache)=@_;
1.1 albertel 1474: my $index="$uname:$udom";
1.426 albertel 1475:
1.599 albertel 1476: if (exists($homecache{$index})) { return $homecache{$index}; }
1.841 albertel 1477:
1478: my %servers = &get_servers($udom,'library');
1479: foreach my $tryserver (keys(%servers)) {
1.230 stredwic 1480: next if ($ignoreBadCache ne 'true' &&
1.231 stredwic 1481: exists($badServerCache{$tryserver}));
1.841 albertel 1482:
1483: my $answer=reply("home:$udom:$uname",$tryserver);
1484: if ($answer eq 'found') {
1485: delete($badServerCache{$tryserver});
1486: return $homecache{$index}=$tryserver;
1487: } elsif ($answer eq 'no_host') {
1488: $badServerCache{$tryserver}=1;
1489: }
1.1 albertel 1490: }
1491: return 'no_host';
1.70 www 1492: }
1493:
1494: # ------------------------------------- Find the usernames behind a list of IDs
1495:
1496: sub idget {
1497: my ($udom,@ids)=@_;
1498: my %returnhash=();
1499:
1.841 albertel 1500: my %servers = &get_servers($udom,'library');
1501: foreach my $tryserver (keys(%servers)) {
1502: my $idlist=join('&',@ids);
1503: $idlist=~tr/A-Z/a-z/;
1504: my $reply=&reply("idget:$udom:".$idlist,$tryserver);
1505: my @answer=();
1506: if (($reply ne 'con_lost') && ($reply!~/^error\:/)) {
1507: @answer=split(/\&/,$reply);
1508: } ;
1509: my $i;
1510: for ($i=0;$i<=$#ids;$i++) {
1511: if ($answer[$i]) {
1512: $returnhash{$ids[$i]}=$answer[$i];
1513: }
1514: }
1515: }
1.70 www 1516: return %returnhash;
1517: }
1518:
1519: # ------------------------------------- Find the IDs behind a list of usernames
1520:
1521: sub idrget {
1522: my ($udom,@unames)=@_;
1523: my %returnhash=();
1.800 albertel 1524: foreach my $uname (@unames) {
1525: $returnhash{$uname}=(&userenvironment($udom,$uname,'id'))[1];
1.191 harris41 1526: }
1.70 www 1527: return %returnhash;
1528: }
1529:
1530: # ------------------------------- Store away a list of names and associated IDs
1531:
1532: sub idput {
1533: my ($udom,%ids)=@_;
1534: my %servers=();
1.800 albertel 1535: foreach my $uname (keys(%ids)) {
1536: &cput('environment',{'id'=>$ids{$uname}},$udom,$uname);
1537: my $uhom=&homeserver($uname,$udom);
1.70 www 1538: if ($uhom ne 'no_host') {
1.800 albertel 1539: my $id=&escape($ids{$uname});
1.70 www 1540: $id=~tr/A-Z/a-z/;
1.800 albertel 1541: my $esc_unam=&escape($uname);
1.70 www 1542: if ($servers{$uhom}) {
1.800 albertel 1543: $servers{$uhom}.='&'.$id.'='.$esc_unam;
1.70 www 1544: } else {
1.800 albertel 1545: $servers{$uhom}=$id.'='.$esc_unam;
1.70 www 1546: }
1547: }
1.191 harris41 1548: }
1.800 albertel 1549: foreach my $server (keys(%servers)) {
1550: &critical('idput:'.$udom.':'.$servers{$server},$server);
1.191 harris41 1551: }
1.344 www 1552: }
1553:
1.1023 raeburn 1554: # ------------------------------dump from db file owned by domainconfig user
1.1012 raeburn 1555: sub dump_dom {
1.1165 droeschl 1556: my ($namespace, $udom, $regexp) = @_;
1557:
1558: $udom ||= $env{'user.domain'};
1559:
1560: return () unless $udom;
1561:
1562: return &dump($namespace, $udom, &get_domainconfiguser($udom), $regexp);
1.1012 raeburn 1563: }
1564:
1.1023 raeburn 1565: # ------------------------------------------ get items from domain db files
1.806 raeburn 1566:
1567: sub get_dom {
1.860 raeburn 1568: my ($namespace,$storearr,$udom,$uhome)=@_;
1.806 raeburn 1569: my $items='';
1570: foreach my $item (@$storearr) {
1571: $items.=&escape($item).'&';
1572: }
1573: $items=~s/\&$//;
1.860 raeburn 1574: if (!$udom) {
1575: $udom=$env{'user.domain'};
1576: if (defined(&domain($udom,'primary'))) {
1577: $uhome=&domain($udom,'primary');
1578: } else {
1.874 albertel 1579: undef($uhome);
1.860 raeburn 1580: }
1581: } else {
1582: if (!$uhome) {
1583: if (defined(&domain($udom,'primary'))) {
1584: $uhome=&domain($udom,'primary');
1585: }
1586: }
1587: }
1588: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1589: my $rep=&reply("getdom:$udom:$namespace:$items",$uhome);
1.866 raeburn 1590: my %returnhash;
1.875 albertel 1591: if ($rep eq '' || $rep =~ /^error: 2 /) {
1.866 raeburn 1592: return %returnhash;
1593: }
1.806 raeburn 1594: my @pairs=split(/\&/,$rep);
1595: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
1596: return @pairs;
1597: }
1598: my $i=0;
1599: foreach my $item (@$storearr) {
1600: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1601: $i++;
1602: }
1603: return %returnhash;
1604: } else {
1.880 banghart 1605: &logthis("get_dom failed - no homeserver and/or domain ($udom) ($uhome)");
1.806 raeburn 1606: }
1607: }
1608:
1609: # -------------------------------------------- put items in domain db files
1610:
1611: sub put_dom {
1.860 raeburn 1612: my ($namespace,$storehash,$udom,$uhome)=@_;
1613: if (!$udom) {
1614: $udom=$env{'user.domain'};
1615: if (defined(&domain($udom,'primary'))) {
1616: $uhome=&domain($udom,'primary');
1617: } else {
1.874 albertel 1618: undef($uhome);
1.860 raeburn 1619: }
1620: } else {
1621: if (!$uhome) {
1622: if (defined(&domain($udom,'primary'))) {
1623: $uhome=&domain($udom,'primary');
1624: }
1625: }
1626: }
1627: if ($udom && $uhome && ($uhome ne 'no_host')) {
1.806 raeburn 1628: my $items='';
1629: foreach my $item (keys(%$storehash)) {
1630: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1631: }
1632: $items=~s/\&$//;
1633: return &reply("putdom:$udom:$namespace:$items",$uhome);
1634: } else {
1.860 raeburn 1635: &logthis("put_dom failed - no homeserver and/or domain");
1.806 raeburn 1636: }
1637: }
1638:
1.1023 raeburn 1639: # --------------------- newput for items in db file owned by domainconfig user
1.1012 raeburn 1640: sub newput_dom {
1.1023 raeburn 1641: my ($namespace,$storehash,$udom) = @_;
1.1012 raeburn 1642: my $result;
1643: if (!$udom) {
1644: $udom=$env{'user.domain'};
1645: }
1.1023 raeburn 1646: if ($udom) {
1647: my $uname = &get_domainconfiguser($udom);
1648: $result = &newput($namespace,$storehash,$udom,$uname);
1.1012 raeburn 1649: }
1650: return $result;
1651: }
1652:
1.1023 raeburn 1653: # --------------------- delete for items in db file owned by domainconfig user
1.1012 raeburn 1654: sub del_dom {
1.1023 raeburn 1655: my ($namespace,$storearr,$udom)=@_;
1.1012 raeburn 1656: if (ref($storearr) eq 'ARRAY') {
1657: if (!$udom) {
1658: $udom=$env{'user.domain'};
1659: }
1.1023 raeburn 1660: if ($udom) {
1661: my $uname = &get_domainconfiguser($udom);
1662: return &del($namespace,$storearr,$udom,$uname);
1.1012 raeburn 1663: }
1664: }
1665: }
1666:
1.1023 raeburn 1667: # ----------------------------------construct domainconfig user for a domain
1668: sub get_domainconfiguser {
1669: my ($udom) = @_;
1670: return $udom.'-domainconfig';
1671: }
1672:
1.837 raeburn 1673: sub retrieve_inst_usertypes {
1674: my ($udom) = @_;
1675: my (%returnhash,@order);
1.989 raeburn 1676: my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1677: if ((ref($domdefs{'inststatustypes'}) eq 'HASH') &&
1678: (ref($domdefs{'inststatusorder'}) eq 'ARRAY')) {
1679: %returnhash = %{$domdefs{'inststatustypes'}};
1680: @order = @{$domdefs{'inststatusorder'}};
1681: } else {
1682: if (defined(&domain($udom,'primary'))) {
1683: my $uhome=&domain($udom,'primary');
1684: my $rep=&reply("inst_usertypes:$udom",$uhome);
1685: if ($rep =~ /^(con_lost|error|no_such_host|refused)/) {
1686: &logthis("get_dom failed - $rep returned from $uhome in domain: $udom");
1687: return (\%returnhash,\@order);
1688: }
1689: my ($hashitems,$orderitems) = split(/:/,$rep);
1690: my @pairs=split(/\&/,$hashitems);
1691: foreach my $item (@pairs) {
1692: my ($key,$value)=split(/=/,$item,2);
1693: $key = &unescape($key);
1694: next if ($key =~ /^error: 2 /);
1695: $returnhash{$key}=&thaw_unescape($value);
1696: }
1697: my @esc_order = split(/\&/,$orderitems);
1698: foreach my $item (@esc_order) {
1699: push(@order,&unescape($item));
1700: }
1701: } else {
1702: &logthis("get_dom failed - no primary domain server for $udom");
1.837 raeburn 1703: }
1704: }
1705: return (\%returnhash,\@order);
1706: }
1707:
1.868 raeburn 1708: sub is_domainimage {
1709: my ($url) = @_;
1710: if ($url=~m-^/+res/+($match_domain)/+\1\-domainconfig/+(img|logo|domlogo)/+-) {
1711: if (&domain($1) ne '') {
1712: return '1';
1713: }
1714: }
1715: return;
1716: }
1717:
1.899 raeburn 1718: sub inst_directory_query {
1719: my ($srch) = @_;
1720: my $udom = $srch->{'srchdomain'};
1721: my %results;
1722: my $homeserver = &domain($udom,'primary');
1.909 raeburn 1723: my $outcome;
1.899 raeburn 1724: if ($homeserver ne '') {
1.904 albertel 1725: my $queryid=&reply("querysend:instdirsearch:".
1726: &escape($srch->{'srchby'}).':'.
1727: &escape($srch->{'srchterm'}).':'.
1728: &escape($srch->{'srchtype'}),$homeserver);
1729: my $host=&hostname($homeserver);
1730: if ($queryid !~/^\Q$host\E\_/) {
1731: &logthis('instituional directory search invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1732: return;
1733: }
1734: my $response = &get_query_reply($queryid);
1735: my $maxtries = 5;
1736: my $tries = 1;
1737: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1738: $response = &get_query_reply($queryid);
1739: $tries ++;
1740: }
1741:
1742: if (!&error($response) && $response ne 'refused') {
1.909 raeburn 1743: if ($response eq 'unavailable') {
1744: $outcome = $response;
1745: } else {
1746: $outcome = 'ok';
1747: my @matches = split(/\n/,$response);
1748: foreach my $match (@matches) {
1749: my ($key,$value) = split(/=/,$match);
1750: $results{&unescape($key).':'.$udom} = &thaw_unescape($value);
1751: }
1.899 raeburn 1752: }
1753: }
1754: }
1.909 raeburn 1755: return ($outcome,%results);
1.899 raeburn 1756: }
1757:
1758: sub usersearch {
1759: my ($srch) = @_;
1760: my $dom = $srch->{'srchdomain'};
1761: my %results;
1762: my %libserv = &all_library();
1763: my $query = 'usersearch';
1764: foreach my $tryserver (keys(%libserv)) {
1765: if (&host_domain($tryserver) eq $dom) {
1766: my $host=&hostname($tryserver);
1767: my $queryid=
1.911 raeburn 1768: &reply("querysend:".&escape($query).':'.
1769: &escape($srch->{'srchby'}).':'.
1.899 raeburn 1770: &escape($srch->{'srchtype'}).':'.
1771: &escape($srch->{'srchterm'}),$tryserver);
1772: if ($queryid !~/^\Q$host\E\_/) {
1773: &logthis('usersearch: invalid queryid: '.$queryid.' for host: '.$host.'in domain '.$dom.' and server: '.$tryserver);
1.902 raeburn 1774: next;
1.899 raeburn 1775: }
1776: my $reply = &get_query_reply($queryid);
1777: my $maxtries = 1;
1778: my $tries = 1;
1779: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
1780: $reply = &get_query_reply($queryid);
1781: $tries ++;
1782: }
1783: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1784: &logthis('usersrch error: '.$reply.' for '.$dom.' - searching for : '.$srch->{'srchterm'}.' by '.$srch->{'srchby'}.' ('.$srch->{'srchtype'}.') - maxtries: '.$maxtries.' tries: '.$tries);
1785: } else {
1.911 raeburn 1786: my @matches;
1787: if ($reply =~ /\n/) {
1788: @matches = split(/\n/,$reply);
1789: } else {
1790: @matches = split(/\&/,$reply);
1791: }
1.899 raeburn 1792: foreach my $match (@matches) {
1793: my ($uname,$udom,%userhash);
1.911 raeburn 1794: foreach my $entry (split(/:/,$match)) {
1795: my ($key,$value) =
1796: map {&unescape($_);} split(/=/,$entry);
1.899 raeburn 1797: $userhash{$key} = $value;
1798: if ($key eq 'username') {
1799: $uname = $value;
1800: } elsif ($key eq 'domain') {
1801: $udom = $value;
1.911 raeburn 1802: }
1.899 raeburn 1803: }
1804: $results{$uname.':'.$udom} = \%userhash;
1805: }
1806: }
1807: }
1808: }
1809: return %results;
1810: }
1811:
1.912 raeburn 1812: sub get_instuser {
1813: my ($udom,$uname,$id) = @_;
1814: my $homeserver = &domain($udom,'primary');
1815: my ($outcome,%results);
1816: if ($homeserver ne '') {
1817: my $queryid=&reply("querysend:getinstuser:".&escape($uname).':'.
1818: &escape($id).':'.&escape($udom),$homeserver);
1819: my $host=&hostname($homeserver);
1820: if ($queryid !~/^\Q$host\E\_/) {
1821: &logthis('get_instuser invalid queryid: '.$queryid.' for host: '.$homeserver.'in domain '.$udom);
1822: return;
1823: }
1824: my $response = &get_query_reply($queryid);
1825: my $maxtries = 5;
1826: my $tries = 1;
1827: while (($response=~/^timeout/) && ($tries < $maxtries)) {
1828: $response = &get_query_reply($queryid);
1829: $tries ++;
1830: }
1831: if (!&error($response) && $response ne 'refused') {
1832: if ($response eq 'unavailable') {
1833: $outcome = $response;
1834: } else {
1835: $outcome = 'ok';
1836: my @matches = split(/\n/,$response);
1837: foreach my $match (@matches) {
1838: my ($key,$value) = split(/=/,$match);
1839: $results{&unescape($key)} = &thaw_unescape($value);
1840: }
1841: }
1842: }
1843: }
1844: my %userinfo;
1845: if (ref($results{$uname}) eq 'HASH') {
1846: %userinfo = %{$results{$uname}};
1847: }
1848: return ($outcome,%userinfo);
1849: }
1850:
1851: sub inst_rulecheck {
1.923 raeburn 1852: my ($udom,$uname,$id,$item,$rules) = @_;
1.912 raeburn 1853: my %returnhash;
1854: if ($udom ne '') {
1855: if (ref($rules) eq 'ARRAY') {
1856: @{$rules} = map {&escape($_);} (@{$rules});
1857: my $rulestr = join(':',@{$rules});
1858: my $homeserver=&domain($udom,'primary');
1859: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1860: my $response;
1861: if ($item eq 'username') {
1862: $response=&unescape(&reply('instrulecheck:'.&escape($udom).
1863: ':'.&escape($uname).':'.$rulestr,
1.912 raeburn 1864: $homeserver));
1.923 raeburn 1865: } elsif ($item eq 'id') {
1866: $response=&unescape(&reply('instidrulecheck:'.&escape($udom).
1867: ':'.&escape($id).':'.$rulestr,
1868: $homeserver));
1.945 raeburn 1869: } elsif ($item eq 'selfcreate') {
1870: $response=&unescape(&reply('instselfcreatecheck:'.
1.943 raeburn 1871: &escape($udom).':'.&escape($uname).
1872: ':'.$rulestr,$homeserver));
1.923 raeburn 1873: }
1.912 raeburn 1874: if ($response ne 'refused') {
1875: my @pairs=split(/\&/,$response);
1876: foreach my $item (@pairs) {
1877: my ($key,$value)=split(/=/,$item,2);
1878: $key = &unescape($key);
1879: next if ($key =~ /^error: 2 /);
1880: $returnhash{$key}=&thaw_unescape($value);
1881: }
1882: }
1883: }
1884: }
1885: }
1886: return %returnhash;
1887: }
1888:
1889: sub inst_userrules {
1.923 raeburn 1890: my ($udom,$check) = @_;
1.912 raeburn 1891: my (%ruleshash,@ruleorder);
1892: if ($udom ne '') {
1893: my $homeserver=&domain($udom,'primary');
1894: if (($homeserver ne '') && ($homeserver ne 'no_host')) {
1.923 raeburn 1895: my $response;
1896: if ($check eq 'id') {
1897: $response=&reply('instidrules:'.&escape($udom),
1.912 raeburn 1898: $homeserver);
1.943 raeburn 1899: } elsif ($check eq 'email') {
1900: $response=&reply('instemailrules:'.&escape($udom),
1901: $homeserver);
1.923 raeburn 1902: } else {
1903: $response=&reply('instuserrules:'.&escape($udom),
1904: $homeserver);
1905: }
1.912 raeburn 1906: if (($response ne 'refused') && ($response ne 'error') &&
1.923 raeburn 1907: ($response ne 'unknown_cmd') &&
1.912 raeburn 1908: ($response ne 'no_such_host')) {
1909: my ($hashitems,$orderitems) = split(/:/,$response);
1910: my @pairs=split(/\&/,$hashitems);
1911: foreach my $item (@pairs) {
1912: my ($key,$value)=split(/=/,$item,2);
1913: $key = &unescape($key);
1914: next if ($key =~ /^error: 2 /);
1915: $ruleshash{$key}=&thaw_unescape($value);
1916: }
1917: my @esc_order = split(/\&/,$orderitems);
1918: foreach my $item (@esc_order) {
1919: push(@ruleorder,&unescape($item));
1920: }
1921: }
1922: }
1923: }
1924: return (\%ruleshash,\@ruleorder);
1925: }
1926:
1.976 raeburn 1927: # ------------- Get Authentication, Language and User Tools Defaults for Domain
1.943 raeburn 1928:
1929: sub get_domain_defaults {
1930: my ($domain) = @_;
1931: my $cachetime = 60*60*24;
1932: my ($result,$cached)=&is_cached_new('domdefaults',$domain);
1933: if (defined($cached)) {
1934: if (ref($result) eq 'HASH') {
1935: return %{$result};
1936: }
1937: }
1938: my %domdefaults;
1939: my %domconfig =
1.989 raeburn 1940: &Apache::lonnet::get_dom('configuration',['defaults','quotas',
1.1047 raeburn 1941: 'requestcourses','inststatus',
1.1183 ! raeburn 1942: 'coursedefaults','usersessions',
! 1943: 'requestauthor'],$domain);
1.943 raeburn 1944: if (ref($domconfig{'defaults'}) eq 'HASH') {
1945: $domdefaults{'lang_def'} = $domconfig{'defaults'}{'lang_def'};
1946: $domdefaults{'auth_def'} = $domconfig{'defaults'}{'auth_def'};
1947: $domdefaults{'auth_arg_def'} = $domconfig{'defaults'}{'auth_arg_def'};
1.982 raeburn 1948: $domdefaults{'timezone_def'} = $domconfig{'defaults'}{'timezone_def'};
1.985 raeburn 1949: $domdefaults{'datelocale_def'} = $domconfig{'defaults'}{'datelocale_def'};
1.1147 raeburn 1950: $domdefaults{'portal_def'} = $domconfig{'defaults'}{'portal_def'};
1.943 raeburn 1951: } else {
1952: $domdefaults{'lang_def'} = &domain($domain,'lang_def');
1953: $domdefaults{'auth_def'} = &domain($domain,'auth_def');
1954: $domdefaults{'auth_arg_def'} = &domain($domain,'auth_arg_def');
1955: }
1.976 raeburn 1956: if (ref($domconfig{'quotas'}) eq 'HASH') {
1957: if (ref($domconfig{'quotas'}{'defaultquota'}) eq 'HASH') {
1958: $domdefaults{'defaultquota'} = $domconfig{'quotas'}{'defaultquota'};
1959: } else {
1960: $domdefaults{'defaultquota'} = $domconfig{'quotas'};
1961: }
1.1177 raeburn 1962: my @usertools = ('aboutme','blog','webdav','portfolio');
1.976 raeburn 1963: foreach my $item (@usertools) {
1964: if (ref($domconfig{'quotas'}{$item}) eq 'HASH') {
1965: $domdefaults{$item} = $domconfig{'quotas'}{$item};
1966: }
1967: }
1968: }
1.985 raeburn 1969: if (ref($domconfig{'requestcourses'}) eq 'HASH') {
1.1006 raeburn 1970: foreach my $item ('official','unofficial','community') {
1.985 raeburn 1971: $domdefaults{$item} = $domconfig{'requestcourses'}{$item};
1972: }
1973: }
1.1183 ! raeburn 1974: if (ref($domconfig{'requestauthor'}) eq 'HASH') {
! 1975: $domdefaults{'requestauthor'} = $domconfig{'requestauthor'};
! 1976: }
1.989 raeburn 1977: if (ref($domconfig{'inststatus'}) eq 'HASH') {
1978: foreach my $item ('inststatustypes','inststatusorder') {
1979: $domdefaults{$item} = $domconfig{'inststatus'}{$item};
1980: }
1981: }
1.1047 raeburn 1982: if (ref($domconfig{'coursedefaults'}) eq 'HASH') {
1983: foreach my $item ('canuse_pdfforms') {
1984: $domdefaults{$item} = $domconfig{'coursedefaults'}{$item};
1985: }
1986: }
1.1073 raeburn 1987: if (ref($domconfig{'usersessions'}) eq 'HASH') {
1988: if (ref($domconfig{'usersessions'}{'remote'}) eq 'HASH') {
1989: $domdefaults{'remotesessions'} = $domconfig{'usersessions'}{'remote'};
1990: }
1991: if (ref($domconfig{'usersessions'}{'hosted'}) eq 'HASH') {
1992: $domdefaults{'hostedsessions'} = $domconfig{'usersessions'}{'hosted'};
1993: }
1994: }
1.943 raeburn 1995: &Apache::lonnet::do_cache_new('domdefaults',$domain,\%domdefaults,
1996: $cachetime);
1997: return %domdefaults;
1998: }
1999:
1.344 www 2000: # --------------------------------------------------- Assign a key to a student
2001:
2002: sub assign_access_key {
1.364 www 2003: #
2004: # a valid key looks like uname:udom#comments
2005: # comments are being appended
2006: #
1.498 www 2007: my ($ckey,$kdom,$knum,$cdom,$cnum,$udom,$uname,$logentry)=@_;
2008: $kdom=
1.620 albertel 2009: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($kdom));
1.498 www 2010: $knum=
1.620 albertel 2011: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($knum));
1.344 www 2012: $cdom=
1.620 albertel 2013: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2014: $cnum=
1.620 albertel 2015: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2016: $udom=$env{'user.name'} unless (defined($udom));
2017: $uname=$env{'user.domain'} unless (defined($uname));
1.498 www 2018: my %existing=&get('accesskeys',[$ckey],$kdom,$knum);
1.364 www 2019: if (($existing{$ckey}=~/^\#(.*)$/) || # - new key
1.479 albertel 2020: ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#(.*)$/)) {
1.364 www 2021: # assigned to this person
2022: # - this should not happen,
1.345 www 2023: # unless something went wrong
2024: # the first time around
2025: # ready to assign
1.364 www 2026: $logentry=$1.'; '.$logentry;
1.496 www 2027: if (&put('accesskeys',{$ckey=>$uname.':'.$udom.'#'.$logentry},
1.498 www 2028: $kdom,$knum) eq 'ok') {
1.345 www 2029: # key now belongs to user
1.346 www 2030: my $envkey='key.'.$cdom.'_'.$cnum;
1.345 www 2031: if (&put('environment',{$envkey => $ckey}) eq 'ok') {
1.949 raeburn 2032: &appenv({'environment.'.$envkey => $ckey});
1.345 www 2033: return 'ok';
2034: } else {
2035: return
2036: 'error: Count not permanently assign key, will need to be re-entered later.';
2037: }
2038: } else {
2039: return 'error: Could not assign key, try again later.';
2040: }
1.364 www 2041: } elsif (!$existing{$ckey}) {
1.345 www 2042: # the key does not exist
2043: return 'error: The key does not exist';
2044: } else {
2045: # the key is somebody else's
2046: return 'error: The key is already in use';
2047: }
1.344 www 2048: }
2049:
1.364 www 2050: # ------------------------------------------ put an additional comment on a key
2051:
2052: sub comment_access_key {
2053: #
2054: # a valid key looks like uname:udom#comments
2055: # comments are being appended
2056: #
2057: my ($ckey,$cdom,$cnum,$logentry)=@_;
2058: $cdom=
1.620 albertel 2059: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.364 www 2060: $cnum=
1.620 albertel 2061: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.364 www 2062: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
2063: if ($existing{$ckey}) {
2064: $existing{$ckey}.='; '.$logentry;
2065: # ready to assign
1.367 www 2066: if (&put('accesskeys',{$ckey=>$existing{$ckey}},
1.364 www 2067: $cdom,$cnum) eq 'ok') {
2068: return 'ok';
2069: } else {
2070: return 'error: Count not store comment.';
2071: }
2072: } else {
2073: # the key does not exist
2074: return 'error: The key does not exist';
2075: }
2076: }
2077:
1.344 www 2078: # ------------------------------------------------------ Generate a set of keys
2079:
2080: sub generate_access_keys {
1.364 www 2081: my ($number,$cdom,$cnum,$logentry)=@_;
1.344 www 2082: $cdom=
1.620 albertel 2083: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2084: $cnum=
1.620 albertel 2085: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
1.361 www 2086: unless (&allowed('mky',$cdom)) { return 0; }
1.344 www 2087: unless (($cdom) && ($cnum)) { return 0; }
2088: if ($number>10000) { return 0; }
2089: sleep(2); # make sure don't get same seed twice
2090: srand(time()^($$+($$<<15))); # from "Programming Perl"
2091: my $total=0;
2092: for (my $i=1;$i<=$number;$i++) {
2093: my $newkey=sprintf("%lx",int(100000*rand)).'-'.
2094: sprintf("%lx",int(100000*rand)).'-'.
2095: sprintf("%lx",int(100000*rand));
2096: $newkey=~s/1/g/g; # folks mix up 1 and l
2097: $newkey=~s/0/h/g; # and also 0 and O
2098: my %existing=&get('accesskeys',[$newkey],$cdom,$cnum);
2099: if ($existing{$newkey}) {
2100: $i--;
2101: } else {
1.364 www 2102: if (&put('accesskeys',
2103: { $newkey => '# generated '.localtime().
1.620 albertel 2104: ' by '.$env{'user.name'}.'@'.$env{'user.domain'}.
1.364 www 2105: '; '.$logentry },
2106: $cdom,$cnum) eq 'ok') {
1.344 www 2107: $total++;
2108: }
2109: }
2110: }
1.620 albertel 2111: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.344 www 2112: 'Generated '.$total.' keys for '.$cnum.' at '.$cdom);
2113: return $total;
2114: }
2115:
2116: # ------------------------------------------------------- Validate an accesskey
2117:
2118: sub validate_access_key {
2119: my ($ckey,$cdom,$cnum,$udom,$uname)=@_;
2120: $cdom=
1.620 albertel 2121: $env{'course.'.$env{'request.course.id'}.'.domain'} unless (defined($cdom));
1.344 www 2122: $cnum=
1.620 albertel 2123: $env{'course.'.$env{'request.course.id'}.'.num'} unless (defined($cnum));
2124: $udom=$env{'user.domain'} unless (defined($udom));
2125: $uname=$env{'user.name'} unless (defined($uname));
1.345 www 2126: my %existing=&get('accesskeys',[$ckey],$cdom,$cnum);
1.479 albertel 2127: return ($existing{$ckey}=~/^\Q$uname\E\:\Q$udom\E\#/);
1.70 www 2128: }
2129:
2130: # ------------------------------------- Find the section of student in a course
1.652 albertel 2131: sub devalidate_getsection_cache {
2132: my ($udom,$unam,$courseid)=@_;
2133: my $hashid="$udom:$unam:$courseid";
2134: &devalidate_cache_new('getsection',$hashid);
2135: }
1.298 matthew 2136:
1.815 albertel 2137: sub courseid_to_courseurl {
2138: my ($courseid) = @_;
2139: #already url style courseid
2140: return $courseid if ($courseid =~ m{^/});
2141:
2142: if (exists($env{'course.'.$courseid.'.num'})) {
2143: my $cnum = $env{'course.'.$courseid.'.num'};
2144: my $cdom = $env{'course.'.$courseid.'.domain'};
2145: return "/$cdom/$cnum";
2146: }
2147:
2148: my %courseinfo=&Apache::lonnet::coursedescription($courseid);
2149: if (exists($courseinfo{'num'})) {
2150: return "/$courseinfo{'domain'}/$courseinfo{'num'}";
2151: }
2152:
2153: return undef;
2154: }
2155:
1.298 matthew 2156: sub getsection {
2157: my ($udom,$unam,$courseid)=@_;
1.599 albertel 2158: my $cachetime=1800;
1.551 albertel 2159:
2160: my $hashid="$udom:$unam:$courseid";
1.599 albertel 2161: my ($result,$cached)=&is_cached_new('getsection',$hashid);
1.551 albertel 2162: if (defined($cached)) { return $result; }
2163:
1.298 matthew 2164: my %Pending;
2165: my %Expired;
2166: #
2167: # Each role can either have not started yet (pending), be active,
2168: # or have expired.
2169: #
2170: # If there is an active role, we are done.
2171: #
2172: # If there is more than one role which has not started yet,
2173: # choose the one which will start sooner
2174: # If there is one role which has not started yet, return it.
2175: #
2176: # If there is more than one expired role, choose the one which ended last.
2177: # If there is a role which has expired, return it.
2178: #
1.815 albertel 2179: $courseid = &courseid_to_courseurl($courseid);
1.1166 raeburn 2180: my %roleshash = &dump('roles',$udom,$unam,$courseid);
1.817 raeburn 2181: foreach my $key (keys(%roleshash)) {
1.479 albertel 2182: next if ($key !~/^\Q$courseid\E(?:\/)*(\w+)*\_st$/);
1.298 matthew 2183: my $section=$1;
2184: if ($key eq $courseid.'_st') { $section=''; }
1.817 raeburn 2185: my ($dummy,$end,$start)=split(/\_/,&unescape($roleshash{$key}));
1.298 matthew 2186: my $now=time;
1.548 albertel 2187: if (defined($end) && $end && ($now > $end)) {
1.298 matthew 2188: $Expired{$end}=$section;
2189: next;
2190: }
1.548 albertel 2191: if (defined($start) && $start && ($now < $start)) {
1.298 matthew 2192: $Pending{$start}=$section;
2193: next;
2194: }
1.599 albertel 2195: return &do_cache_new('getsection',$hashid,$section,$cachetime);
1.298 matthew 2196: }
2197: #
2198: # Presumedly there will be few matching roles from the above
2199: # loop and the sorting time will be negligible.
2200: if (scalar(keys(%Pending))) {
2201: my ($time) = sort {$a <=> $b} keys(%Pending);
1.599 albertel 2202: return &do_cache_new('getsection',$hashid,$Pending{$time},$cachetime);
1.298 matthew 2203: }
2204: if (scalar(keys(%Expired))) {
2205: my @sorted = sort {$a <=> $b} keys(%Expired);
2206: my $time = pop(@sorted);
1.599 albertel 2207: return &do_cache_new('getsection',$hashid,$Expired{$time},$cachetime);
1.298 matthew 2208: }
1.599 albertel 2209: return &do_cache_new('getsection',$hashid,'-1',$cachetime);
1.298 matthew 2210: }
1.70 www 2211:
1.599 albertel 2212: sub save_cache {
2213: &purge_remembered();
1.722 albertel 2214: #&Apache::loncommon::validate_page();
1.620 albertel 2215: undef(%env);
1.780 albertel 2216: undef($env_loaded);
1.599 albertel 2217: }
1.452 albertel 2218:
1.599 albertel 2219: my $to_remember=-1;
2220: my %remembered;
2221: my %accessed;
2222: my $kicks=0;
2223: my $hits=0;
1.849 albertel 2224: sub make_key {
2225: my ($name,$id) = @_;
1.872 albertel 2226: if (length($id) > 65
2227: && length(&escape($id)) > 200) {
2228: $id=length($id).':'.&Digest::MD5::md5_hex($id);
2229: }
1.849 albertel 2230: return &escape($name.':'.$id);
2231: }
2232:
1.599 albertel 2233: sub devalidate_cache_new {
2234: my ($name,$id,$debug) = @_;
2235: if ($debug) { &Apache::lonnet::logthis("deleting $name:$id"); }
1.849 albertel 2236: $id=&make_key($name,$id);
1.599 albertel 2237: $memcache->delete($id);
2238: delete($remembered{$id});
2239: delete($accessed{$id});
2240: }
2241:
2242: sub is_cached_new {
2243: my ($name,$id,$debug) = @_;
1.849 albertel 2244: $id=&make_key($name,$id);
1.599 albertel 2245: if (exists($remembered{$id})) {
1.1133 foxr 2246: if ($debug) { &Apache::lonnet::logthis("Early return $id of $remembered{$id} "); }
1.599 albertel 2247: $accessed{$id}=[&gettimeofday()];
2248: $hits++;
2249: return ($remembered{$id},1);
2250: }
2251: my $value = $memcache->get($id);
2252: if (!(defined($value))) {
2253: if ($debug) { &Apache::lonnet::logthis("getting $id is not defined"); }
1.417 albertel 2254: return (undef,undef);
1.416 albertel 2255: }
1.599 albertel 2256: if ($value eq '__undef__') {
2257: if ($debug) { &Apache::lonnet::logthis("getting $id is __undef__"); }
2258: $value=undef;
2259: }
2260: &make_room($id,$value,$debug);
2261: if ($debug) { &Apache::lonnet::logthis("getting $id is $value"); }
2262: return ($value,1);
2263: }
2264:
2265: sub do_cache_new {
2266: my ($name,$id,$value,$time,$debug) = @_;
1.849 albertel 2267: $id=&make_key($name,$id);
1.599 albertel 2268: my $setvalue=$value;
2269: if (!defined($setvalue)) {
2270: $setvalue='__undef__';
2271: }
1.623 albertel 2272: if (!defined($time) ) {
2273: $time=600;
2274: }
1.599 albertel 2275: if ($debug) { &Apache::lonnet::logthis("Setting $id to $value"); }
1.910 albertel 2276: my $result = $memcache->set($id,$setvalue,$time);
2277: if (! $result) {
1.872 albertel 2278: &logthis("caching of id -> $id failed");
1.910 albertel 2279: $memcache->disconnect_all();
1.872 albertel 2280: }
1.600 albertel 2281: # need to make a copy of $value
1.919 albertel 2282: &make_room($id,$value,$debug);
1.599 albertel 2283: return $value;
2284: }
2285:
2286: sub make_room {
2287: my ($id,$value,$debug)=@_;
1.919 albertel 2288:
2289: $remembered{$id}= (ref($value)) ? &Storable::dclone($value)
2290: : $value;
1.599 albertel 2291: if ($to_remember<0) { return; }
2292: $accessed{$id}=[&gettimeofday()];
2293: if (scalar(keys(%remembered)) <= $to_remember) { return; }
2294: my $to_kick;
2295: my $max_time=0;
2296: foreach my $other (keys(%accessed)) {
2297: if (&tv_interval($accessed{$other}) > $max_time) {
2298: $to_kick=$other;
2299: $max_time=&tv_interval($accessed{$other});
2300: }
2301: }
2302: delete($remembered{$to_kick});
2303: delete($accessed{$to_kick});
2304: $kicks++;
2305: if ($debug) { &logthis("kicking $to_kick $max_time $kicks\n"); }
1.541 albertel 2306: return;
2307: }
2308:
1.599 albertel 2309: sub purge_remembered {
1.604 albertel 2310: #&logthis("Tossing ".scalar(keys(%remembered)));
2311: #&logthis(sprintf("%-20s is %s",'%remembered',length(&freeze(\%remembered))));
1.599 albertel 2312: undef(%remembered);
2313: undef(%accessed);
1.428 albertel 2314: }
1.70 www 2315: # ------------------------------------- Read an entry from a user's environment
2316:
2317: sub userenvironment {
2318: my ($udom,$unam,@what)=@_;
1.976 raeburn 2319: my $items;
2320: foreach my $item (@what) {
2321: $items.=&escape($item).'&';
2322: }
2323: $items=~s/\&$//;
1.70 www 2324: my %returnhash=();
1.1009 raeburn 2325: my $uhome = &homeserver($unam,$udom);
2326: unless ($uhome eq 'no_host') {
2327: my @answer=split(/\&/,
2328: &reply('get:'.$udom.':'.$unam.':environment:'.$items,$uhome));
1.1048 raeburn 2329: if ($#answer==0 && $answer[0] =~ /^(con_lost|error:|no_such_host)/i) {
2330: return %returnhash;
2331: }
1.1009 raeburn 2332: my $i;
2333: for ($i=0;$i<=$#what;$i++) {
2334: $returnhash{$what[$i]}=&unescape($answer[$i]);
2335: }
1.70 www 2336: }
2337: return %returnhash;
1.1 albertel 2338: }
2339:
1.617 albertel 2340: # ---------------------------------------------------------- Get a studentphoto
2341: sub studentphoto {
2342: my ($udom,$unam,$ext) = @_;
2343: my $home=&Apache::lonnet::homeserver($unam,$udom);
1.706 raeburn 2344: if (defined($env{'request.course.id'})) {
1.708 raeburn 2345: if ($env{'course.'.$env{'request.course.id'}.'.internal.showphoto'}) {
1.706 raeburn 2346: if ($udom eq $env{'course.'.$env{'request.course.id'}.'.domain'}) {
2347: return(&retrievestudentphoto($udom,$unam,$ext));
2348: } else {
2349: my ($result,$perm_reqd)=
1.707 albertel 2350: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2351: if ($result eq 'ok') {
2352: if (!($perm_reqd eq 'yes')) {
2353: return(&retrievestudentphoto($udom,$unam,$ext));
2354: }
2355: }
2356: }
2357: }
2358: } else {
2359: my ($result,$perm_reqd) =
1.707 albertel 2360: &Apache::lonnet::auto_photo_permission($unam,$udom);
1.706 raeburn 2361: if ($result eq 'ok') {
2362: if (!($perm_reqd eq 'yes')) {
2363: return(&retrievestudentphoto($udom,$unam,$ext));
2364: }
2365: }
2366: }
2367: return '/adm/lonKaputt/lonlogo_broken.gif';
2368: }
2369:
2370: sub retrievestudentphoto {
2371: my ($udom,$unam,$ext,$type) = @_;
2372: my $home=&Apache::lonnet::homeserver($unam,$udom);
2373: my $ret=&Apache::lonnet::reply("studentphoto:$udom:$unam:$ext:$type",$home);
2374: if ($ret eq 'ok') {
2375: my $url="/uploaded/$udom/$unam/internal/studentphoto.$ext";
2376: if ($type eq 'thumbnail') {
2377: $url="/uploaded/$udom/$unam/internal/studentphoto_tn.$ext";
2378: }
2379: my $tokenurl=&Apache::lonnet::tokenwrapper($url);
2380: return $tokenurl;
2381: } else {
2382: if ($type eq 'thumbnail') {
2383: return '/adm/lonKaputt/genericstudent_tn.gif';
2384: } else {
2385: return '/adm/lonKaputt/lonlogo_broken.gif';
2386: }
1.617 albertel 2387: }
2388: }
2389:
1.263 www 2390: # -------------------------------------------------------------------- New chat
2391:
2392: sub chatsend {
1.724 raeburn 2393: my ($newentry,$anon,$group)=@_;
1.620 albertel 2394: my $cnum=$env{'course.'.$env{'request.course.id'}.'.num'};
2395: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2396: my $chome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.263 www 2397: &reply('chatsend:'.$cdom.':'.$cnum.':'.
1.620 albertel 2398: &escape($env{'user.domain'}.':'.$env{'user.name'}.':'.$anon.':'.
1.724 raeburn 2399: &escape($newentry)).':'.$group,$chome);
1.292 www 2400: }
2401:
2402: # ------------------------------------------ Find current version of a resource
2403:
2404: sub getversion {
2405: my $fname=&clutter(shift);
2406: unless ($fname=~/^\/res\//) { return -1; }
2407: return ¤tversion(&filelocation('',$fname));
2408: }
2409:
2410: sub currentversion {
2411: my $fname=shift;
2412: my $author=$fname;
2413: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2414: my ($udom,$uname)=split(/\//,$author);
1.1112 www 2415: my $home=&homeserver($uname,$udom);
1.292 www 2416: if ($home eq 'no_host') {
2417: return -1;
2418: }
1.1112 www 2419: my $answer=&reply("currentversion:$fname",$home);
1.292 www 2420: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2421: return -1;
2422: }
1.1112 www 2423: return $answer;
1.263 www 2424: }
2425:
1.1111 www 2426: #
2427: # Return special version number of resource if set by override, empty otherwise
2428: #
2429: sub usedversion {
2430: my $fname=shift;
2431: unless ($fname) { $fname=$env{'request.uri'}; }
2432: my ($urlversion)=($fname=~/\.(\d+)\.\w+$/);
2433: if ($urlversion) { return $urlversion; }
2434: return '';
2435: }
2436:
1.1 albertel 2437: # ----------------------------- Subscribe to a resource, return URL if possible
1.11 www 2438:
1.1 albertel 2439: sub subscribe {
2440: my $fname=shift;
1.761 raeburn 2441: if ($fname=~/\/(aboutme|syllabus|bulletinboard|smppg)$/) { return ''; }
1.532 albertel 2442: $fname=~s/[\n\r]//g;
1.1 albertel 2443: my $author=$fname;
2444: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2445: my ($udom,$uname)=split(/\//,$author);
2446: my $home=homeserver($uname,$udom);
1.335 albertel 2447: if ($home eq 'no_host') {
2448: return 'not_found';
1.1 albertel 2449: }
2450: my $answer=reply("sub:$fname",$home);
1.64 www 2451: if (($answer eq 'con_lost') || ($answer eq 'rejected')) {
2452: $answer.=' by '.$home;
2453: }
1.1 albertel 2454: return $answer;
2455: }
2456:
1.8 www 2457: # -------------------------------------------------------------- Replicate file
2458:
2459: sub repcopy {
2460: my $filename=shift;
1.23 www 2461: $filename=~s/\/+/\//g;
1.1142 raeburn 2462: my $londocroot = $perlvar{'lonDocRoot'};
2463: if ($filename=~m{^\Q$londocroot/adm/\E}) { return 'ok'; }
1.1164 raeburn 2464: if ($filename=~m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.1142 raeburn 2465: if ($filename=~m{^\Q$londocroot/userfiles/\E} or
2466: $filename=~m{^/*(uploaded|editupload)/}) {
1.538 albertel 2467: return &repcopy_userfile($filename);
2468: }
1.532 albertel 2469: $filename=~s/[\n\r]//g;
1.8 www 2470: my $transname="$filename.in.transfer";
1.828 www 2471: # FIXME: this should flock
1.607 raeburn 2472: if ((-e $filename) || (-e $transname)) { return 'ok'; }
1.8 www 2473: my $remoteurl=subscribe($filename);
1.64 www 2474: if ($remoteurl =~ /^con_lost by/) {
2475: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2476: return 'unavailable';
1.8 www 2477: } elsif ($remoteurl eq 'not_found') {
1.441 albertel 2478: #&logthis("Subscribe returned not_found: $filename");
1.607 raeburn 2479: return 'not_found';
1.64 www 2480: } elsif ($remoteurl =~ /^rejected by/) {
2481: &logthis("Subscribe returned $remoteurl: $filename");
1.607 raeburn 2482: return 'forbidden';
1.20 www 2483: } elsif ($remoteurl eq 'directory') {
1.607 raeburn 2484: return 'ok';
1.8 www 2485: } else {
1.290 www 2486: my $author=$filename;
2487: $author=~s/\/home\/httpd\/html\/res\/([^\/]*)\/([^\/]*).*/$1\/$2/;
2488: my ($udom,$uname)=split(/\//,$author);
2489: my $home=homeserver($uname,$udom);
2490: unless ($home eq $perlvar{'lonHostID'}) {
1.8 www 2491: my @parts=split(/\//,$filename);
2492: my $path="/$parts[1]/$parts[2]/$parts[3]/$parts[4]";
1.1142 raeburn 2493: if ($path ne "$londocroot/res") {
1.8 www 2494: &logthis("Malconfiguration for replication: $filename");
1.607 raeburn 2495: return 'bad_request';
1.8 www 2496: }
2497: my $count;
2498: for ($count=5;$count<$#parts;$count++) {
2499: $path.="/$parts[$count]";
2500: if ((-e $path)!=1) {
2501: mkdir($path,0777);
2502: }
2503: }
2504: my $ua=new LWP::UserAgent;
2505: my $request=new HTTP::Request('GET',"$remoteurl");
2506: my $response=$ua->request($request,$transname);
2507: if ($response->is_error()) {
2508: unlink($transname);
2509: my $message=$response->status_line;
1.672 albertel 2510: &logthis("<font color=\"blue\">WARNING:"
1.12 www 2511: ." LWP get: $message: $filename</font>");
1.607 raeburn 2512: return 'unavailable';
1.8 www 2513: } else {
1.16 www 2514: if ($remoteurl!~/\.meta$/) {
2515: my $mrequest=new HTTP::Request('GET',$remoteurl.'.meta');
2516: my $mresponse=$ua->request($mrequest,$filename.'.meta');
2517: if ($mresponse->is_error()) {
2518: unlink($filename.'.meta');
2519: &logthis(
1.672 albertel 2520: "<font color=\"yellow\">INFO: No metadata: $filename</font>");
1.16 www 2521: }
2522: }
1.8 www 2523: rename($transname,$filename);
1.607 raeburn 2524: return 'ok';
1.8 www 2525: }
1.290 www 2526: }
1.8 www 2527: }
1.330 www 2528: }
2529:
2530: # ------------------------------------------------ Get server side include body
2531: sub ssi_body {
1.381 albertel 2532: my ($filelink,%form)=@_;
1.606 matthew 2533: if (! exists($form{'LONCAPA_INTERNAL_no_discussion'})) {
2534: $form{'LONCAPA_INTERNAL_no_discussion'}='true';
2535: }
1.953 www 2536: my $output='';
2537: my $response;
1.980 raeburn 2538: if ($filelink=~/^https?\:/) {
1.954 raeburn 2539: ($output,$response)=&externalssi($filelink);
1.953 www 2540: } else {
1.1004 droeschl 2541: $filelink .= $filelink=~/\?/ ? '&' : '?';
2542: $filelink .= 'inhibitmenu=yes';
1.953 www 2543: ($output,$response)=&ssi($filelink,%form);
2544: }
1.778 albertel 2545: $output=~s|//(\s*<!--)? BEGIN LON-CAPA Internal.+?// END LON-CAPA Internal\s*(-->)?\s||gs;
1.451 albertel 2546: $output=~s/^.*?\<body[^\>]*\>//si;
1.930 albertel 2547: $output=~s/\<\/body\s*\>.*?$//si;
1.953 www 2548: if (wantarray) {
2549: return ($output, $response);
2550: } else {
2551: return $output;
2552: }
1.8 www 2553: }
2554:
1.15 www 2555: # --------------------------------------------------------- Server Side Include
2556:
1.782 albertel 2557: sub absolute_url {
2558: my ($host_name) = @_;
2559: my $protocol = ($ENV{'SERVER_PORT'} == 443?'https://':'http://');
2560: if ($host_name eq '') {
2561: $host_name = $ENV{'SERVER_NAME'};
2562: }
2563: return $protocol.$host_name;
2564: }
2565:
1.942 foxr 2566: #
2567: # Server side include.
2568: # Parameters:
2569: # fn Possibly encrypted resource name/id.
2570: # form Hash that describes how the rendering should be done
2571: # and other things.
1.944 foxr 2572: # Returns:
1.950 raeburn 2573: # Scalar context: The content of the response.
2574: # Array context: 2 element list of the content and the full response object.
1.942 foxr 2575: #
1.15 www 2576: sub ssi {
2577:
1.944 foxr 2578: my ($fn,%form)=@_;
1.15 www 2579: my $ua=new LWP::UserAgent;
1.23 www 2580: my $request;
1.711 albertel 2581:
2582: $form{'no_update_last_known'}=1;
1.895 albertel 2583: &Apache::lonenc::check_encrypt(\$fn);
1.23 www 2584: if (%form) {
1.782 albertel 2585: $request=new HTTP::Request('POST',&absolute_url().$fn);
1.1000 raeburn 2586: $request->content(join('&',map { &escape($_).'='.&escape($form{$_}) } keys(%form)));
1.23 www 2587: } else {
1.782 albertel 2588: $request=new HTTP::Request('GET',&absolute_url().$fn);
1.23 www 2589: }
2590:
1.15 www 2591: $request->header(Cookie => $ENV{'HTTP_COOKIE'});
1.1173 foxr 2592: my $response= $ua->request($request);
1.1182 foxr 2593: my $content = $response->content;
2594:
2595:
1.944 foxr 2596: if (wantarray) {
1.1173 foxr 2597: return ($content, $response);
1.944 foxr 2598: } else {
1.1173 foxr 2599: return $content;
1.942 foxr 2600: }
1.324 www 2601: }
2602:
2603: sub externalssi {
2604: my ($url)=@_;
2605: my $ua=new LWP::UserAgent;
2606: my $request=new HTTP::Request('GET',$url);
2607: my $response=$ua->request($request);
1.954 raeburn 2608: if (wantarray) {
2609: return ($response->content, $response);
2610: } else {
2611: return $response->content;
2612: }
1.15 www 2613: }
1.254 www 2614:
1.492 albertel 2615: # -------------------------------- Allow a /uploaded/ URI to be vouched for
2616:
2617: sub allowuploaded {
2618: my ($srcurl,$url)=@_;
2619: $url=&clutter(&declutter($url));
2620: my $dir=$url;
2621: $dir=~s/\/[^\/]+$//;
2622: my %httpref=();
2623: my $httpurl=&hreflocation('',$url);
2624: $httpref{'httpref.'.$httpurl}=$srcurl;
1.949 raeburn 2625: &Apache::lonnet::appenv(\%httpref);
1.254 www 2626: }
1.477 raeburn 2627:
1.478 albertel 2628: # --------- File operations in /home/httpd/html/userfiles/$domain/1/2/3/$course
1.638 albertel 2629: # input: action, courseID, current domain, intended
1.637 raeburn 2630: # path to file, source of file, instruction to parse file for objects,
2631: # ref to hash for embedded objects,
2632: # ref to hash for codebase of java objects.
1.1095 raeburn 2633: # reference to scalar to accommodate mime type determined
2634: # from File::MMagic if $parser = parse.
1.637 raeburn 2635: #
1.485 raeburn 2636: # output: url to file (if action was uploaddoc),
2637: # ok if successful, or diagnostic message otherwise (if action was propagate or copy)
1.477 raeburn 2638: #
1.478 albertel 2639: # Allows directory structure to be used within lonUsers/../userfiles/ for a
2640: # course.
1.477 raeburn 2641: #
1.478 albertel 2642: # action = propagate - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2643: # will be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles in
2644: # course's home server.
1.477 raeburn 2645: #
1.478 albertel 2646: # action = copy - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file will
2647: # be copied from $source (current location) to
2648: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2649: # and will then be copied to
2650: # /home/httpd/lonUsers/$domain/1/2/3/$course/userfiles/$file in
2651: # course's home server.
1.485 raeburn 2652: #
1.481 raeburn 2653: # action = uploaddoc - /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
1.620 albertel 2654: # will be retrived from $env{form.uploaddoc} (from DOCS interface) to
1.481 raeburn 2655: # /home/httpd/html/userfiles/$domain/1/2/3/$course/$file
2656: # and will then be copied to /home/httpd/lonUsers/1/2/3/$course/userfiles/$file
2657: # in course's home server.
1.637 raeburn 2658: #
1.477 raeburn 2659:
2660: sub process_coursefile {
1.1095 raeburn 2661: my ($action,$docuname,$docudom,$file,$source,$parser,$allfiles,$codebase,
2662: $mimetype)=@_;
1.477 raeburn 2663: my $fetchresult;
1.638 albertel 2664: my $home=&homeserver($docuname,$docudom);
1.477 raeburn 2665: if ($action eq 'propagate') {
1.638 albertel 2666: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
2667: $home);
1.481 raeburn 2668: } else {
1.477 raeburn 2669: my $fpath = '';
2670: my $fname = $file;
1.478 albertel 2671: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
1.477 raeburn 2672: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
1.637 raeburn 2673: my $filepath = &build_filepath($fpath);
1.481 raeburn 2674: if ($action eq 'copy') {
2675: if ($source eq '') {
2676: $fetchresult = 'no source file';
2677: return $fetchresult;
2678: } else {
2679: my $destination = $filepath.'/'.$fname;
2680: rename($source,$destination);
2681: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2682: $home);
1.481 raeburn 2683: }
2684: } elsif ($action eq 'uploaddoc') {
2685: open(my $fh,'>'.$filepath.'/'.$fname);
1.620 albertel 2686: print $fh $env{'form.'.$source};
1.481 raeburn 2687: close($fh);
1.637 raeburn 2688: if ($parser eq 'parse') {
1.1024 raeburn 2689: my $mm = new File::MMagic;
1.1095 raeburn 2690: my $type = $mm->checktype_filename($filepath.'/'.$fname);
2691: if ($type eq 'text/html') {
1.1024 raeburn 2692: my $parse_result = &extract_embedded_items($filepath.'/'.$fname,$allfiles,$codebase);
2693: unless ($parse_result eq 'ok') {
2694: &logthis('Failed to parse '.$filepath.'/'.$fname.' for embedded media: '.$parse_result);
2695: }
1.637 raeburn 2696: }
1.1095 raeburn 2697: if (ref($mimetype)) {
2698: $$mimetype = $type;
2699: }
1.637 raeburn 2700: }
1.477 raeburn 2701: $fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2702: $home);
1.481 raeburn 2703: if ($fetchresult eq 'ok') {
2704: return '/uploaded/'.$fpath.'/'.$fname;
2705: } else {
2706: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2707: ' to host '.$home.': '.$fetchresult);
1.481 raeburn 2708: return '/adm/notfound.html';
2709: }
1.477 raeburn 2710: }
2711: }
1.485 raeburn 2712: unless ( $fetchresult eq 'ok') {
1.477 raeburn 2713: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
1.638 albertel 2714: ' to host '.$home.': '.$fetchresult);
1.477 raeburn 2715: }
2716: return $fetchresult;
2717: }
2718:
1.637 raeburn 2719: sub build_filepath {
2720: my ($fpath) = @_;
2721: my $filepath=$perlvar{'lonDocRoot'}.'/userfiles';
2722: unless ($fpath eq '') {
2723: my @parts=split('/',$fpath);
2724: foreach my $part (@parts) {
2725: $filepath.= '/'.$part;
2726: if ((-e $filepath)!=1) {
2727: mkdir($filepath,0777);
2728: }
2729: }
2730: }
2731: return $filepath;
2732: }
2733:
2734: sub store_edited_file {
1.638 albertel 2735: my ($primary_url,$content,$docudom,$docuname,$fetchresult) = @_;
1.637 raeburn 2736: my $file = $primary_url;
2737: $file =~ s#^/uploaded/$docudom/$docuname/##;
2738: my $fpath = '';
2739: my $fname = $file;
2740: ($fpath,$fname) = ($file =~ m|^(.*)/([^/]+)$|);
2741: $fpath=$docudom.'/'.$docuname.'/'.$fpath;
2742: my $filepath = &build_filepath($fpath);
2743: open(my $fh,'>'.$filepath.'/'.$fname);
2744: print $fh $content;
2745: close($fh);
1.638 albertel 2746: my $home=&homeserver($docuname,$docudom);
1.637 raeburn 2747: $$fetchresult= &reply('fetchuserfile:'.$docudom.'/'.$docuname.'/'.$file,
1.638 albertel 2748: $home);
1.637 raeburn 2749: if ($$fetchresult eq 'ok') {
2750: return '/uploaded/'.$fpath.'/'.$fname;
2751: } else {
1.638 albertel 2752: &logthis('Failed to transfer '.$docudom.'/'.$docuname.'/'.$file.
2753: ' to host '.$home.': '.$$fetchresult);
1.637 raeburn 2754: return '/adm/notfound.html';
2755: }
2756: }
2757:
1.531 albertel 2758: sub clean_filename {
1.831 albertel 2759: my ($fname,$args)=@_;
1.315 www 2760: # Replace Windows backslashes by forward slashes
1.257 www 2761: $fname=~s/\\/\//g;
1.831 albertel 2762: if (!$args->{'keep_path'}) {
2763: # Get rid of everything but the actual filename
2764: $fname=~s/^.*\/([^\/]+)$/$1/;
2765: }
1.315 www 2766: # Replace spaces by underscores
2767: $fname=~s/\s+/\_/g;
2768: # Replace all other weird characters by nothing
1.831 albertel 2769: $fname=~s{[^/\w\.\-]}{}g;
1.540 albertel 2770: # Replace all .\d. sequences with _\d. so they no longer look like version
2771: # numbers
2772: $fname=~s/\.(\d+)(?=\.)/_$1/g;
1.531 albertel 2773: return $fname;
2774: }
1.1051 raeburn 2775: # This Function checks if an Image's dimensions exceed either $resizewidth (width)
2776: # or $resizeheight (height) - both pixels. If so, the image is scaled to produce an
2777: # image with the same aspect ratio as the original, but with dimensions which do
2778: # not exceed $resizewidth and $resizeheight.
2779:
1.984 neumanie 2780: sub resizeImage {
1.1051 raeburn 2781: my ($img_path,$resizewidth,$resizeheight) = @_;
2782: my $ima = Image::Magick->new;
2783: my $resized;
2784: if (-e $img_path) {
2785: $ima->Read($img_path);
2786: if (($resizewidth =~ /^\d+$/) && ($resizeheight > 0)) {
2787: my $width = $ima->Get('width');
2788: my $height = $ima->Get('height');
2789: if ($width > $resizewidth) {
2790: my $factor = $width/$resizewidth;
2791: my $newheight = $height/$factor;
2792: $ima->Scale(width=>$resizewidth,height=>$newheight);
2793: $resized = 1;
2794: }
2795: }
2796: if (($resizeheight =~ /^\d+$/) && ($resizeheight > 0)) {
2797: my $width = $ima->Get('width');
2798: my $height = $ima->Get('height');
2799: if ($height > $resizeheight) {
2800: my $factor = $height/$resizeheight;
2801: my $newwidth = $width/$factor;
2802: $ima->Scale(width=>$newwidth,height=>$resizeheight);
2803: $resized = 1;
2804: }
2805: }
2806: if ($resized) {
2807: $ima->Write($img_path);
2808: }
2809: }
2810: return;
1.977 amueller 2811: }
2812:
1.608 albertel 2813: # --------------- Take an uploaded file and put it into the userfiles directory
1.686 albertel 2814: # input: $formname - the contents of the file are in $env{"form.$formname"}
1.1093 raeburn 2815: # the desired filename is in $env{"form.$formname.filename"}
1.1090 raeburn 2816: # $context - possible values: coursedoc, existingfile, overwrite,
2817: # canceloverwrite, or ''.
2818: # if 'coursedoc': upload to the current course
2819: # if 'existingfile': write file to tmp/overwrites directory
2820: # if 'canceloverwrite': delete file written to tmp/overwrites directory
2821: # $context is passed as argument to &finishuserfileupload
1.686 albertel 2822: # $subdir - directory in userfile to store the file into
1.858 raeburn 2823: # $parser - instruction to parse file for objects ($parser = parse)
2824: # $allfiles - reference to hash for embedded objects
2825: # $codebase - reference to hash for codebase of java objects
2826: # $desuname - username for permanent storage of uploaded file
2827: # $dsetudom - domain for permanaent storage of uploaded file
1.860 raeburn 2828: # $thumbwidth - width (pixels) of thumbnail to make for uploaded image
2829: # $thumbheight - height (pixels) of thumbnail to make for uploaded image
1.1051 raeburn 2830: # $resizewidth - width (pixels) to which to resize uploaded image
2831: # $resizeheight - height (pixels) to which to resize uploaded image
1.1095 raeburn 2832: # $mimetype - reference to scalar to accommodate mime type determined
1.1152 raeburn 2833: # from File::MMagic.
1.858 raeburn 2834: #
1.686 albertel 2835: # output: url of file in userspace, or error: <message>
2836: # or /adm/notfound.html if failure to upload occurse
1.608 albertel 2837:
1.531 albertel 2838: sub userfileupload {
1.1090 raeburn 2839: my ($formname,$context,$subdir,$parser,$allfiles,$codebase,$destuname,
1.1095 raeburn 2840: $destudom,$thumbwidth,$thumbheight,$resizewidth,$resizeheight,$mimetype)=@_;
1.531 albertel 2841: if (!defined($subdir)) { $subdir='unknown'; }
1.620 albertel 2842: my $fname=$env{'form.'.$formname.'.filename'};
1.531 albertel 2843: $fname=&clean_filename($fname);
1.1090 raeburn 2844: # See if there is anything left
1.257 www 2845: unless ($fname) { return 'error: no uploaded file'; }
1.1090 raeburn 2846: # Files uploaded to help request form, or uploaded to "create course" page are handled differently
2847: if ((($formname eq 'screenshot') && ($subdir eq 'helprequests')) ||
2848: (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) ||
2849: ($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
1.523 raeburn 2850: my $now = time;
1.1090 raeburn 2851: my $filepath;
1.1095 raeburn 2852: if (($formname eq 'screenshot') && ($subdir eq 'helprequests')) {
1.1090 raeburn 2853: $filepath = 'tmp/helprequests/'.$now;
2854: } elsif (($formname eq 'coursecreatorxml') && ($subdir eq 'batchupload')) {
2855: $filepath = 'tmp/addcourse/'.$destudom.'/web/'.$env{'user.name'}.
2856: '_'.$env{'user.domain'}.'/pending';
2857: } elsif (($context eq 'existingfile') || ($context eq 'canceloverwrite')) {
2858: my ($docuname,$docudom);
2859: if ($destudom) {
2860: $docudom = $destudom;
2861: } else {
2862: $docudom = $env{'user.domain'};
2863: }
2864: if ($destuname) {
2865: $docuname = $destuname;
2866: } else {
2867: $docuname = $env{'user.name'};
2868: }
2869: if (exists($env{'form.group'})) {
2870: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2871: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2872: }
2873: $filepath = 'tmp/overwrites/'.$docudom.'/'.$docuname.'/'.$subdir;
2874: if ($context eq 'canceloverwrite') {
2875: my $tempfile = $perlvar{'lonDaemons'}.'/'.$filepath.'/'.$fname;
2876: if (-e $tempfile) {
2877: my @info = stat($tempfile);
2878: if ($info[9] eq $env{'form.timestamp'}) {
2879: unlink($tempfile);
2880: }
2881: }
2882: return;
1.523 raeburn 2883: }
2884: }
1.1090 raeburn 2885: # Create the directory if not present
1.741 raeburn 2886: my @parts=split(/\//,$filepath);
2887: my $fullpath = $perlvar{'lonDaemons'};
2888: for (my $i=0;$i<@parts;$i++) {
2889: $fullpath .= '/'.$parts[$i];
2890: if ((-e $fullpath)!=1) {
2891: mkdir($fullpath,0777);
2892: }
2893: }
2894: open(my $fh,'>'.$fullpath.'/'.$fname);
2895: print $fh $env{'form.'.$formname};
2896: close($fh);
1.1090 raeburn 2897: if ($context eq 'existingfile') {
2898: my @info = stat($fullpath.'/'.$fname);
2899: return ($fullpath.'/'.$fname,$info[9]);
2900: } else {
2901: return $fullpath.'/'.$fname;
2902: }
1.523 raeburn 2903: }
1.995 raeburn 2904: if ($subdir eq 'scantron') {
2905: $fname = 'scantron_orig_'.$fname;
1.1093 raeburn 2906: } else {
1.995 raeburn 2907: $fname="$subdir/$fname";
2908: }
1.1090 raeburn 2909: if ($context eq 'coursedoc') {
1.638 albertel 2910: my $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2911: my $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.646 raeburn 2912: if ($env{'form.folder'} =~ m/^(default|supplemental)/) {
1.638 albertel 2913: return &finishuserfileupload($docuname,$docudom,
2914: $formname,$fname,$parser,$allfiles,
1.1051 raeburn 2915: $codebase,$thumbwidth,$thumbheight,
1.1095 raeburn 2916: $resizewidth,$resizeheight,$context,$mimetype);
1.481 raeburn 2917: } else {
1.620 albertel 2918: $fname=$env{'form.folder'}.'/'.$fname;
1.638 albertel 2919: return &process_coursefile('uploaddoc',$docuname,$docudom,
2920: $fname,$formname,$parser,
1.1095 raeburn 2921: $allfiles,$codebase,$mimetype);
1.481 raeburn 2922: }
1.719 banghart 2923: } elsif (defined($destuname)) {
2924: my $docuname=$destuname;
2925: my $docudom=$destudom;
1.860 raeburn 2926: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2927: $parser,$allfiles,$codebase,
1.1051 raeburn 2928: $thumbwidth,$thumbheight,
1.1095 raeburn 2929: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2930: } else {
1.638 albertel 2931: my $docuname=$env{'user.name'};
2932: my $docudom=$env{'user.domain'};
1.714 raeburn 2933: if (exists($env{'form.group'})) {
2934: $docuname=$env{'course.'.$env{'request.course.id'}.'.num'};
2935: $docudom=$env{'course.'.$env{'request.course.id'}.'.domain'};
2936: }
1.860 raeburn 2937: return &finishuserfileupload($docuname,$docudom,$formname,$fname,
2938: $parser,$allfiles,$codebase,
1.1051 raeburn 2939: $thumbwidth,$thumbheight,
1.1095 raeburn 2940: $resizewidth,$resizeheight,$context,$mimetype);
1.259 www 2941: }
1.271 www 2942: }
2943:
2944: sub finishuserfileupload {
1.860 raeburn 2945: my ($docuname,$docudom,$formname,$fname,$parser,$allfiles,$codebase,
1.1095 raeburn 2946: $thumbwidth,$thumbheight,$resizewidth,$resizeheight,$context,$mimetype) = @_;
1.477 raeburn 2947: my $path=$docudom.'/'.$docuname.'/';
1.258 www 2948: my $filepath=$perlvar{'lonDocRoot'};
1.984 neumanie 2949:
1.860 raeburn 2950: my ($fnamepath,$file,$fetchthumb);
1.494 albertel 2951: $file=$fname;
2952: if ($fname=~m|/|) {
2953: ($fnamepath,$file) = ($fname =~ m|^(.*)/([^/]+)$|);
2954: $path.=$fnamepath.'/';
2955: }
1.259 www 2956: my @parts=split(/\//,$filepath.'/userfiles/'.$path);
1.258 www 2957: my $count;
2958: for ($count=4;$count<=$#parts;$count++) {
2959: $filepath.="/$parts[$count]";
2960: if ((-e $filepath)!=1) {
2961: mkdir($filepath,0777);
2962: }
2963: }
1.984 neumanie 2964:
1.258 www 2965: # Save the file
2966: {
1.701 albertel 2967: if (!open(FH,'>'.$filepath.'/'.$file)) {
2968: &logthis('Failed to create '.$filepath.'/'.$file);
2969: print STDERR ('Failed to create '.$filepath.'/'.$file."\n");
2970: return '/adm/notfound.html';
2971: }
1.1090 raeburn 2972: if ($context eq 'overwrite') {
1.1117 foxr 2973: my $source = LONCAPA::tempdir().'/overwrites/'.$docudom.'/'.$docuname.'/'.$fname;
1.1090 raeburn 2974: my $target = $filepath.'/'.$file;
2975: if (-e $source) {
2976: my @info = stat($source);
2977: if ($info[9] eq $env{'form.timestamp'}) {
2978: unless (&File::Copy::move($source,$target)) {
2979: &logthis('Failed to overwrite '.$filepath.'/'.$file);
2980: return "Moving from $source failed";
2981: }
2982: } else {
2983: return "Temporary file: $source had unexpected date/time for last modification";
2984: }
2985: } else {
2986: return "Temporary file: $source missing";
2987: }
2988: } elsif (!print FH ($env{'form.'.$formname})) {
1.701 albertel 2989: &logthis('Failed to write to '.$filepath.'/'.$file);
2990: print STDERR ('Failed to write to '.$filepath.'/'.$file."\n");
2991: return '/adm/notfound.html';
2992: }
1.570 albertel 2993: close(FH);
1.1051 raeburn 2994: if ($resizewidth && $resizeheight) {
2995: my $mm = new File::MMagic;
2996: my $mime_type = $mm->checktype_filename($filepath.'/'.$file);
2997: if ($mime_type =~ m{^image/}) {
2998: &resizeImage($filepath.'/'.$file,$resizewidth,$resizeheight);
2999: }
1.977 amueller 3000: }
1.258 www 3001: }
1.1152 raeburn 3002: if (($context eq 'coursedoc') || ($parser eq 'parse')) {
3003: if (ref($mimetype)) {
3004: if ($$mimetype eq '') {
3005: my $mm = new File::MMagic;
3006: my $type = $mm->checktype_filename($filepath.'/'.$file);
3007: $$mimetype = $type;
3008: }
3009: }
3010: }
1.637 raeburn 3011: if ($parser eq 'parse') {
1.1152 raeburn 3012: if ((ref($mimetype)) && ($$mimetype eq 'text/html')) {
1.1024 raeburn 3013: my $parse_result = &extract_embedded_items($filepath.'/'.$file,
3014: $allfiles,$codebase);
3015: unless ($parse_result eq 'ok') {
3016: &logthis('Failed to parse '.$filepath.$file.
3017: ' for embedded media: '.$parse_result);
3018: }
1.637 raeburn 3019: }
3020: }
1.860 raeburn 3021: if (($thumbwidth =~ /^\d+$/) && ($thumbheight =~ /^\d+$/)) {
3022: my $input = $filepath.'/'.$file;
3023: my $output = $filepath.'/'.'tn-'.$file;
3024: my $thumbsize = $thumbwidth.'x'.$thumbheight;
3025: system("convert -sample $thumbsize $input $output");
3026: if (-e $filepath.'/'.'tn-'.$file) {
3027: $fetchthumb = 1;
3028: }
3029: }
1.858 raeburn 3030:
1.259 www 3031: # Notify homeserver to grep it
3032: #
1.984 neumanie 3033: my $docuhome=&homeserver($docuname,$docudom);
1.494 albertel 3034: my $fetchresult= &reply('fetchuserfile:'.$path.$file,$docuhome);
1.295 www 3035: if ($fetchresult eq 'ok') {
1.860 raeburn 3036: if ($fetchthumb) {
3037: my $thumbresult= &reply('fetchuserfile:'.$path.'tn-'.$file,$docuhome);
3038: if ($thumbresult ne 'ok') {
3039: &logthis('Failed to transfer '.$path.'tn-'.$file.' to host '.
3040: $docuhome.': '.$thumbresult);
3041: }
3042: }
1.259 www 3043: #
1.258 www 3044: # Return the URL to it
1.494 albertel 3045: return '/uploaded/'.$path.$file;
1.263 www 3046: } else {
1.494 albertel 3047: &logthis('Failed to transfer '.$path.$file.' to host '.$docuhome.
3048: ': '.$fetchresult);
1.263 www 3049: return '/adm/notfound.html';
1.858 raeburn 3050: }
1.493 albertel 3051: }
3052:
1.637 raeburn 3053: sub extract_embedded_items {
1.961 raeburn 3054: my ($fullpath,$allfiles,$codebase,$content) = @_;
1.637 raeburn 3055: my @state = ();
1.1164 raeburn 3056: my (%lastids,%related,%shockwave,%flashvars);
1.637 raeburn 3057: my %javafiles = (
3058: codebase => '',
3059: code => '',
3060: archive => ''
3061: );
3062: my %mediafiles = (
3063: src => '',
3064: movie => '',
3065: );
1.648 raeburn 3066: my $p;
3067: if ($content) {
3068: $p = HTML::LCParser->new($content);
3069: } else {
1.961 raeburn 3070: $p = HTML::LCParser->new($fullpath);
1.648 raeburn 3071: }
1.641 albertel 3072: while (my $t=$p->get_token()) {
1.640 albertel 3073: if ($t->[0] eq 'S') {
3074: my ($tagname, $attr) = ($t->[1],$t->[2]);
1.886 albertel 3075: push(@state, $tagname);
1.648 raeburn 3076: if (lc($tagname) eq 'allow') {
3077: &add_filetype($allfiles,$attr->{'src'},'src');
3078: }
1.640 albertel 3079: if (lc($tagname) eq 'img') {
3080: &add_filetype($allfiles,$attr->{'src'},'src');
3081: }
1.886 albertel 3082: if (lc($tagname) eq 'a') {
3083: &add_filetype($allfiles,$attr->{'href'},'href');
3084: }
1.645 raeburn 3085: if (lc($tagname) eq 'script') {
1.1164 raeburn 3086: my $src;
1.645 raeburn 3087: if ($attr->{'archive'} =~ /\.jar$/i) {
3088: &add_filetype($allfiles,$attr->{'archive'},'archive');
3089: } else {
1.1164 raeburn 3090: if ($attr->{'src'} ne '') {
3091: $src = $attr->{'src'};
3092: &add_filetype($allfiles,$src,'src');
3093: }
3094: }
3095: my $text = $p->get_trimmed_text();
3096: if ($text =~ /\Qswfobject.registerObject(\E([^\)]+)\)/) {
3097: my @swfargs = split(/,/,$1);
3098: foreach my $item (@swfargs) {
3099: $item =~ s/["']//g;
3100: $item =~ s/^\s+//;
3101: $item =~ s/\s+$//;
3102: }
3103: if (($swfargs[0] ne'') && ($swfargs[2] ne '')) {
3104: if (ref($related{$swfargs[0]}) eq 'ARRAY') {
3105: push(@{$related{$swfargs[0]}},$swfargs[2]);
3106: } else {
3107: $related{$swfargs[0]} = [$swfargs[2]];
3108: }
3109: }
1.645 raeburn 3110: }
3111: }
3112: if (lc($tagname) eq 'link') {
3113: if (lc($attr->{'rel'}) eq 'stylesheet') {
3114: &add_filetype($allfiles,$attr->{'href'},'href');
3115: }
3116: }
1.640 albertel 3117: if (lc($tagname) eq 'object' ||
3118: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')) {
3119: foreach my $item (keys(%javafiles)) {
3120: $javafiles{$item} = '';
3121: }
1.1164 raeburn 3122: if ((lc($tagname) eq 'object') && (lc($state[-2]) ne 'object')) {
3123: $lastids{lc($tagname)} = $attr->{'id'};
3124: }
1.640 albertel 3125: }
3126: if (lc($state[-2]) eq 'object' && lc($tagname) eq 'param') {
3127: my $name = lc($attr->{'name'});
3128: foreach my $item (keys(%javafiles)) {
3129: if ($name eq $item) {
3130: $javafiles{$item} = $attr->{'value'};
3131: last;
3132: }
3133: }
1.1164 raeburn 3134: my $pathfrom;
1.640 albertel 3135: foreach my $item (keys(%mediafiles)) {
3136: if ($name eq $item) {
1.1164 raeburn 3137: $pathfrom = $attr->{'value'};
3138: $shockwave{$lastids{lc($state[-2])}} = $pathfrom;
3139: &add_filetype($allfiles,$pathfrom,$name);
1.640 albertel 3140: last;
3141: }
3142: }
1.1164 raeburn 3143: if ($name eq 'flashvars') {
3144: $flashvars{$lastids{lc($state[-2])}} = $attr->{'value'};
3145: }
3146: if ($pathfrom ne '') {
3147: &embedded_dependency($allfiles,\%related,$lastids{lc($state[-2])},
3148: $pathfrom);
3149: }
1.640 albertel 3150: }
3151: if (lc($tagname) eq 'embed' || lc($tagname) eq 'applet') {
3152: foreach my $item (keys(%javafiles)) {
3153: if ($attr->{$item}) {
3154: $javafiles{$item} = $attr->{$item};
3155: last;
3156: }
3157: }
3158: foreach my $item (keys(%mediafiles)) {
3159: if ($attr->{$item}) {
3160: &add_filetype($allfiles,$attr->{$item},$item);
3161: last;
3162: }
3163: }
1.1164 raeburn 3164: if (lc($tagname) eq 'embed') {
3165: if (($attr->{'name'} ne '') && ($attr->{'src'} ne '')) {
3166: &embedded_dependency($allfiles,\%related,$attr->{'name'},
3167: $attr->{'src'});
3168: }
3169: }
1.640 albertel 3170: }
1.1164 raeburn 3171: if ($t->[4] =~ m{/>$}) {
3172: pop(@state);
3173: }
1.640 albertel 3174: } elsif ($t->[0] eq 'E') {
3175: my ($tagname) = ($t->[1]);
3176: if ($javafiles{'codebase'} ne '') {
3177: $javafiles{'codebase'} .= '/';
3178: }
3179: if (lc($tagname) eq 'applet' ||
3180: lc($tagname) eq 'object' ||
3181: (lc($tagname) eq 'embed' && lc($state[-2]) ne 'object')
3182: ) {
3183: foreach my $item (keys(%javafiles)) {
3184: if ($item ne 'codebase' && $javafiles{$item} ne '') {
3185: my $file=$javafiles{'codebase'}.$javafiles{$item};
3186: &add_filetype($allfiles,$file,$item);
3187: }
3188: }
3189: }
3190: pop @state;
3191: }
3192: }
1.1164 raeburn 3193: foreach my $id (sort(keys(%flashvars))) {
3194: if ($shockwave{$id} ne '') {
3195: my @pairs = split(/\&/,$flashvars{$id});
3196: foreach my $pair (@pairs) {
3197: my ($key,$value) = split(/\=/,$pair);
3198: if ($key eq 'thumb') {
3199: &add_filetype($allfiles,$value,$key);
3200: } elsif ($key eq 'content') {
3201: my ($path) = ($shockwave{$id} =~ m{^(.+/)[^/]+$});
3202: my ($ext) = ($value =~ /\.([^.]+)$/);
3203: if ($ext ne '') {
3204: &add_filetype($allfiles,$path.$value,$ext);
3205: }
3206: }
3207: }
3208: }
3209: }
1.637 raeburn 3210: return 'ok';
3211: }
3212:
1.639 albertel 3213: sub add_filetype {
3214: my ($allfiles,$file,$type)=@_;
3215: if (exists($allfiles->{$file})) {
3216: unless (grep/^\Q$type\E$/, @{$allfiles->{$file}}) {
3217: push(@{$allfiles->{$file}}, &escape($type));
3218: }
3219: } else {
3220: @{$allfiles->{$file}} = (&escape($type));
1.637 raeburn 3221: }
3222: }
3223:
1.1164 raeburn 3224: sub embedded_dependency {
3225: my ($allfiles,$related,$identifier,$pathfrom) = @_;
3226: if ((ref($allfiles) eq 'HASH') && (ref($related) eq 'HASH')) {
3227: if (($identifier ne '') &&
3228: (ref($related->{$identifier}) eq 'ARRAY') &&
3229: ($pathfrom ne '')) {
3230: my ($path) = ($pathfrom =~ m{^(.+/)[^/]+$});
3231: foreach my $dep (@{$related->{$identifier}}) {
3232: &add_filetype($allfiles,$path.$dep,'object');
3233: }
3234: }
3235: }
3236: return;
3237: }
3238:
1.493 albertel 3239: sub removeuploadedurl {
1.984 neumanie 3240: my ($url)=@_;
3241: my (undef,undef,$udom,$uname,$fname)=split('/',$url,5);
1.613 albertel 3242: return &removeuserfile($uname,$udom,$fname);
1.490 albertel 3243: }
3244:
3245: sub removeuserfile {
3246: my ($docuname,$docudom,$fname)=@_;
1.984 neumanie 3247: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3248: my $result = &reply("removeuserfile:$docudom/$docuname/$fname",$home);
1.984 neumanie 3249: if ($result eq 'ok') {
1.798 raeburn 3250: if (($fname !~ /\.meta$/) && (&is_portfolio_file($fname))) {
3251: my $metafile = $fname.'.meta';
3252: my $metaresult = &removeuserfile($docuname,$docudom,$metafile);
1.823 albertel 3253: my $url = "/uploaded/$docudom/$docuname/$fname";
1.984 neumanie 3254: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3255: my $sqlresult =
1.823 albertel 3256: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3257: 'portfolio_metadata',$group,
3258: 'delete');
1.798 raeburn 3259: }
3260: }
3261: return $result;
1.257 www 3262: }
1.15 www 3263:
1.530 albertel 3264: sub mkdiruserfile {
3265: my ($docuname,$docudom,$dir)=@_;
3266: my $home=&homeserver($docuname,$docudom);
3267: return &reply("mkdiruserfile:".&escape("$docudom/$docuname/$dir"),$home);
3268: }
3269:
1.531 albertel 3270: sub renameuserfile {
3271: my ($docuname,$docudom,$old,$new)=@_;
3272: my $home=&homeserver($docuname,$docudom);
1.798 raeburn 3273: my $result = &reply("renameuserfile:$docudom:$docuname:".
3274: &escape("$old").':'.&escape("$new"),$home);
3275: if ($result eq 'ok') {
3276: if (($old !~ /\.meta$/) && (&is_portfolio_file($old))) {
3277: my $oldmeta = $old.'.meta';
3278: my $newmeta = $new.'.meta';
3279: my $metaresult =
3280: &renameuserfile($docuname,$docudom,$oldmeta,$newmeta);
1.823 albertel 3281: my $url = "/uploaded/$docudom/$docuname/$old";
3282: my ($file,$group) = (&parse_portfolio_url($url))[3,4];
1.821 raeburn 3283: my $sqlresult =
1.823 albertel 3284: &update_portfolio_table($docuname,$docudom,$file,
1.821 raeburn 3285: 'portfolio_metadata',$group,
3286: 'delete');
1.798 raeburn 3287: }
3288: }
3289: return $result;
1.531 albertel 3290: }
3291:
1.14 www 3292: # ------------------------------------------------------------------------- Log
3293:
3294: sub log {
3295: my ($dom,$nam,$hom,$what)=@_;
1.47 www 3296: return critical("log:$dom:$nam:$what",$hom);
1.157 www 3297: }
3298:
3299: # ------------------------------------------------------------------ Course Log
1.352 www 3300: #
3301: # This routine flushes several buffers of non-mission-critical nature
3302: #
1.157 www 3303:
3304: sub flushcourselogs {
1.352 www 3305: &logthis('Flushing log buffers');
3306: #
3307: # course logs
3308: # This is a log of all transactions in a course, which can be used
3309: # for data mining purposes
3310: #
3311: # It also collects the courseid database, which lists last transaction
3312: # times and course titles for all courseids
3313: #
3314: my %courseidbuffer=();
1.921 raeburn 3315: foreach my $crsid (keys(%courselogs)) {
1.352 www 3316: if (&reply('log:'.$coursedombuf{$crsid}.':'.$coursenumbuf{$crsid}.':'.
1.188 www 3317: &escape($courselogs{$crsid}),
3318: $coursehombuf{$crsid}) eq 'ok') {
1.157 www 3319: delete $courselogs{$crsid};
3320: } else {
3321: &logthis('Failed to flush log buffer for '.$crsid);
3322: if (length($courselogs{$crsid})>40000) {
1.672 albertel 3323: &logthis("<font color=\"blue\">WARNING: Buffer for ".$crsid.
1.157 www 3324: " exceeded maximum size, deleting.</font>");
3325: delete $courselogs{$crsid};
3326: }
1.352 www 3327: }
1.920 raeburn 3328: $courseidbuffer{$coursehombuf{$crsid}}{$crsid} = {
1.936 raeburn 3329: 'description' => $coursedescrbuf{$crsid},
3330: 'inst_code' => $courseinstcodebuf{$crsid},
3331: 'type' => $coursetypebuf{$crsid},
3332: 'owner' => $courseownerbuf{$crsid},
1.920 raeburn 3333: };
1.191 harris41 3334: }
1.352 www 3335: #
3336: # Write course id database (reverse lookup) to homeserver of courses
3337: # Is used in pickcourse
3338: #
1.840 albertel 3339: foreach my $crs_home (keys(%courseidbuffer)) {
1.918 raeburn 3340: my $response = &courseidput(&host_domain($crs_home),
1.921 raeburn 3341: $courseidbuffer{$crs_home},
3342: $crs_home,'timeonly');
1.352 www 3343: }
3344: #
3345: # File accesses
3346: # Writes to the dynamic metadata of resources to get hit counts, etc.
3347: #
1.449 matthew 3348: foreach my $entry (keys(%accesshash)) {
1.458 matthew 3349: if ($entry =~ /___count$/) {
3350: my ($dom,$name);
1.807 albertel 3351: ($dom,$name,undef)=
1.811 albertel 3352: ($entry=~m{___($match_domain)/($match_name)/(.*)___count$});
1.458 matthew 3353: if (! defined($dom) || $dom eq '' ||
3354: ! defined($name) || $name eq '') {
1.620 albertel 3355: my $cid = $env{'request.course.id'};
3356: $dom = $env{'request.'.$cid.'.domain'};
3357: $name = $env{'request.'.$cid.'.num'};
1.458 matthew 3358: }
1.450 matthew 3359: my $value = $accesshash{$entry};
3360: my (undef,$url,undef) = ($entry =~ /^(.*)___(.*)___count$/);
3361: my %temphash=($url => $value);
1.449 matthew 3362: my $result = &inc('nohist_accesscount',\%temphash,$dom,$name);
3363: if ($result eq 'ok') {
3364: delete $accesshash{$entry};
3365: }
3366: } else {
1.811 albertel 3367: my ($dom,$name) = ($entry=~m{___($match_domain)/($match_name)/(.*)___(\w+)$});
1.1159 www 3368: if (($dom eq 'uploaded') || ($dom eq 'adm')) { next; }
1.450 matthew 3369: my %temphash=($entry => $accesshash{$entry});
1.449 matthew 3370: if (&put('nohist_resevaldata',\%temphash,$dom,$name) eq 'ok') {
3371: delete $accesshash{$entry};
3372: }
1.185 www 3373: }
1.191 harris41 3374: }
1.352 www 3375: #
3376: # Roles
3377: # Reverse lookup of user roles for course faculty/staff and co-authorship
3378: #
1.800 albertel 3379: foreach my $entry (keys(%userrolehash)) {
1.351 www 3380: my ($role,$uname,$udom,$runame,$rudom,$rsec)=
1.349 www 3381: split(/\:/,$entry);
3382: if (&Apache::lonnet::put('nohist_userroles',
1.351 www 3383: { $role.':'.$uname.':'.$udom.':'.$rsec => $userrolehash{$entry} },
1.349 www 3384: $rudom,$runame) eq 'ok') {
3385: delete $userrolehash{$entry};
3386: }
3387: }
1.662 raeburn 3388: #
3389: # Reverse lookup of domain roles (dc, ad, li, sc, au)
3390: #
3391: my %domrolebuffer = ();
1.1000 raeburn 3392: foreach my $entry (keys(%domainrolehash)) {
1.901 albertel 3393: my ($role,$uname,$udom,$runame,$rudom,$rsec)=split(/:/,$entry);
1.662 raeburn 3394: if ($domrolebuffer{$rudom}) {
3395: $domrolebuffer{$rudom}.='&'.&escape($entry).
3396: '='.&escape($domainrolehash{$entry});
3397: } else {
3398: $domrolebuffer{$rudom}.=&escape($entry).
3399: '='.&escape($domainrolehash{$entry});
3400: }
3401: delete $domainrolehash{$entry};
3402: }
3403: foreach my $dom (keys(%domrolebuffer)) {
1.841 albertel 3404: my %servers = &get_servers($dom,'library');
3405: foreach my $tryserver (keys(%servers)) {
3406: unless (&reply('domroleput:'.$dom.':'.
3407: $domrolebuffer{$dom},$tryserver) eq 'ok') {
3408: &logthis('Put of domain roles failed for '.$dom.' and '.$tryserver);
3409: }
1.662 raeburn 3410: }
3411: }
1.186 www 3412: $dumpcount++;
1.157 www 3413: }
3414:
3415: sub courselog {
3416: my $what=shift;
1.158 www 3417: $what=time.':'.$what;
1.620 albertel 3418: unless ($env{'request.course.id'}) { return ''; }
3419: $coursedombuf{$env{'request.course.id'}}=
3420: $env{'course.'.$env{'request.course.id'}.'.domain'};
3421: $coursenumbuf{$env{'request.course.id'}}=
3422: $env{'course.'.$env{'request.course.id'}.'.num'};
3423: $coursehombuf{$env{'request.course.id'}}=
3424: $env{'course.'.$env{'request.course.id'}.'.home'};
3425: $coursedescrbuf{$env{'request.course.id'}}=
3426: $env{'course.'.$env{'request.course.id'}.'.description'};
3427: $courseinstcodebuf{$env{'request.course.id'}}=
3428: $env{'course.'.$env{'request.course.id'}.'.internal.coursecode'};
3429: $courseownerbuf{$env{'request.course.id'}}=
3430: $env{'course.'.$env{'request.course.id'}.'.internal.courseowner'};
1.741 raeburn 3431: $coursetypebuf{$env{'request.course.id'}}=
3432: $env{'course.'.$env{'request.course.id'}.'.type'};
1.620 albertel 3433: if (defined $courselogs{$env{'request.course.id'}}) {
3434: $courselogs{$env{'request.course.id'}}.='&'.$what;
1.157 www 3435: } else {
1.620 albertel 3436: $courselogs{$env{'request.course.id'}}.=$what;
1.157 www 3437: }
1.620 albertel 3438: if (length($courselogs{$env{'request.course.id'}})>4048) {
1.157 www 3439: &flushcourselogs();
3440: }
1.158 www 3441: }
3442:
3443: sub courseacclog {
3444: my $fnsymb=shift;
1.620 albertel 3445: unless ($env{'request.course.id'}) { return ''; }
3446: my $what=$fnsymb.':'.$env{'user.name'}.':'.$env{'user.domain'};
1.1144 www 3447: if ($fnsymb=~/$LONCAPA::assess_re/) {
1.187 www 3448: $what.=':POST';
1.583 matthew 3449: # FIXME: Probably ought to escape things....
1.800 albertel 3450: foreach my $key (keys(%env)) {
3451: if ($key=~/^form\.(.*)/) {
1.975 raeburn 3452: my $formitem = $1;
3453: if ($formitem =~ /^HWFILE(?:SIZE|TOOBIG)/) {
3454: $what.=':'.$formitem.'='.$env{$key};
3455: } elsif ($formitem !~ /^HWFILE(?:[^.]+)$/) {
3456: $what.=':'.$formitem.'='.$env{$key};
3457: }
1.158 www 3458: }
1.191 harris41 3459: }
1.583 matthew 3460: } elsif ($fnsymb =~ m:^/adm/searchcat:) {
3461: # FIXME: We should not be depending on a form parameter that someone
3462: # editing lonsearchcat.pm might change in the future.
1.620 albertel 3463: if ($env{'form.phase'} eq 'course_search') {
1.583 matthew 3464: $what.= ':POST';
3465: # FIXME: Probably ought to escape things....
3466: foreach my $element ('courseexp','crsfulltext','crsrelated',
3467: 'crsdiscuss') {
1.620 albertel 3468: $what.=':'.$element.'='.$env{'form.'.$element};
1.583 matthew 3469: }
3470: }
1.158 www 3471: }
3472: &courselog($what);
1.149 www 3473: }
3474:
1.185 www 3475: sub countacc {
3476: my $url=&declutter(shift);
1.458 matthew 3477: return if (! defined($url) || $url eq '');
1.620 albertel 3478: unless ($env{'request.course.id'}) { return ''; }
1.1158 www 3479: #
3480: # Mark that this url was used in this course
3481: #
1.620 albertel 3482: $accesshash{$env{'request.course.id'}.'___'.$url.'___course'}=1;
1.1158 www 3483: #
3484: # Increase the access count for this resource in this child process
3485: #
1.281 www 3486: my $key=$$.$processmarker.'_'.$dumpcount.'___'.$url.'___count';
1.450 matthew 3487: $accesshash{$key}++;
1.185 www 3488: }
1.349 www 3489:
1.361 www 3490: sub linklog {
3491: my ($from,$to)=@_;
3492: $from=&declutter($from);
3493: $to=&declutter($to);
3494: $accesshash{$from.'___'.$to.'___comefrom'}=1;
3495: $accesshash{$to.'___'.$from.'___goto'}=1;
3496: }
1.1160 www 3497:
3498: sub statslog {
3499: my ($symb,$part,$users,$av_attempts,$degdiff)=@_;
3500: if ($users<2) { return; }
3501: my %dynstore=&LONCAPA::lonmetadata::dynamic_metadata_storage({
3502: 'course' => $env{'request.course.id'},
3503: 'sections' => '"all"',
3504: 'num_students' => $users,
3505: 'part' => $part,
3506: 'symb' => $symb,
3507: 'mean_tries' => $av_attempts,
3508: 'deg_of_diff' => $degdiff});
3509: foreach my $key (keys(%dynstore)) {
3510: $accesshash{$key}=$dynstore{$key};
3511: }
3512: }
1.361 www 3513:
1.349 www 3514: sub userrolelog {
3515: my ($trole,$username,$domain,$area,$tstart,$tend)=@_;
1.1169 droeschl 3516: if ( $trole =~ /^(ca|aa|in|cc|ep|cr|ta|co)/ ) {
1.350 www 3517: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3518: $userrolehash
3519: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
1.349 www 3520: =$tend.':'.$tstart;
1.662 raeburn 3521: }
1.1169 droeschl 3522: if ($env{'request.role'} =~ /dc\./ && $trole =~ /^(au|in|cc|ep|cr|ta|co)/) {
1.898 albertel 3523: $userrolehash
3524: {$trole.':'.$username.':'.$domain.':'.$env{'user.name'}.':'.$env{'user.domain'}.':'}
3525: =$tend.':'.$tstart;
3526: }
1.1169 droeschl 3527: if ($trole =~ /^(dc|ad|li|au|dg|sc)/ ) {
1.662 raeburn 3528: my (undef,$rudom,$runame,$rsec)=split(/\//,$area);
3529: $domainrolehash
3530: {$trole.':'.$username.':'.$domain.':'.$runame.':'.$rudom.':'.$rsec}
3531: = $tend.':'.$tstart;
3532: }
1.351 www 3533: }
3534:
1.957 raeburn 3535: sub courserolelog {
3536: my ($trole,$username,$domain,$area,$tstart,$tend,$delflag,$selfenroll,$context)=@_;
3537: if (($trole eq 'cc') || ($trole eq 'in') ||
3538: ($trole eq 'ep') || ($trole eq 'ad') ||
3539: ($trole eq 'ta') || ($trole eq 'st') ||
1.1044 raeburn 3540: ($trole=~/^cr/) || ($trole eq 'gr') ||
3541: ($trole eq 'co')) {
1.957 raeburn 3542: if ($area =~ m-^/($match_domain)/($match_courseid)/?([^/]*)-) {
3543: my $cdom = $1;
3544: my $cnum = $2;
3545: my $sec = $3;
3546: my $namespace = 'rolelog';
3547: my %storehash = (
3548: role => $trole,
3549: start => $tstart,
3550: end => $tend,
3551: selfenroll => $selfenroll,
3552: context => $context,
3553: );
3554: if ($trole eq 'gr') {
3555: $namespace = 'groupslog';
3556: $storehash{'group'} = $sec;
3557: } else {
3558: $storehash{'section'} = $sec;
3559: }
3560: &instructor_log($namespace,\%storehash,$delflag,$username,$domain,$cnum,$cdom);
1.996 raeburn 3561: if (($trole ne 'st') || ($sec ne '')) {
3562: &devalidate_cache_new('getcourseroles',$cdom.'_'.$cnum);
3563: }
1.957 raeburn 3564: }
3565: }
3566: return;
3567: }
3568:
1.351 www 3569: sub get_course_adv_roles {
1.948 raeburn 3570: my ($cid,$codes) = @_;
1.620 albertel 3571: $cid=$env{'request.course.id'} unless (defined($cid));
1.351 www 3572: my %coursehash=&coursedescription($cid);
1.988 raeburn 3573: my $crstype = &Apache::loncommon::course_type($cid);
1.470 www 3574: my %nothide=();
1.800 albertel 3575: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
1.937 raeburn 3576: if ($user !~ /:/) {
3577: $nothide{join(':',split(/[\@]/,$user))}=1;
3578: } else {
3579: $nothide{$user}=1;
3580: }
1.470 www 3581: }
1.351 www 3582: my %returnhash=();
3583: my %dumphash=
3584: &dump('nohist_userroles',$coursehash{'domain'},$coursehash{'num'});
3585: my $now=time;
1.997 raeburn 3586: my %privileged;
1.1000 raeburn 3587: foreach my $entry (keys(%dumphash)) {
1.800 albertel 3588: my ($tend,$tstart)=split(/\:/,$dumphash{$entry});
1.351 www 3589: if (($tstart) && ($tstart<0)) { next; }
3590: if (($tend) && ($tend<$now)) { next; }
3591: if (($tstart) && ($now<$tstart)) { next; }
1.800 albertel 3592: my ($role,$username,$domain,$section)=split(/\:/,$entry);
1.576 albertel 3593: if ($username eq '' || $domain eq '') { next; }
1.997 raeburn 3594: unless (ref($privileged{$domain}) eq 'HASH') {
3595: my %dompersonnel =
1.998 raeburn 3596: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
1.997 raeburn 3597: $privileged{$domain} = {};
3598: foreach my $server (keys(%dompersonnel)) {
1.999 raeburn 3599: if (ref($dompersonnel{$server}) eq 'HASH') {
1.997 raeburn 3600: foreach my $user (keys(%{$dompersonnel{$server}})) {
3601: my ($trole,$uname,$udom) = split(/:/,$user);
3602: $privileged{$udom}{$uname} = 1;
3603: }
3604: }
3605: }
3606: }
3607: if ((exists($privileged{$domain}{$username})) &&
3608: (!$nothide{$username.':'.$domain})) { next; }
1.656 albertel 3609: if ($role eq 'cr') { next; }
1.948 raeburn 3610: if ($codes) {
3611: if ($section) { $role .= ':'.$section; }
3612: if ($returnhash{$role}) {
3613: $returnhash{$role}.=','.$username.':'.$domain;
3614: } else {
3615: $returnhash{$role}=$username.':'.$domain;
3616: }
1.351 www 3617: } else {
1.988 raeburn 3618: my $key=&plaintext($role,$crstype);
1.973 bisitz 3619: if ($section) { $key.=' ('.&Apache::lonlocal::mt('Section [_1]',$section).')'; }
1.948 raeburn 3620: if ($returnhash{$key}) {
3621: $returnhash{$key}.=','.$username.':'.$domain;
3622: } else {
3623: $returnhash{$key}=$username.':'.$domain;
3624: }
1.351 www 3625: }
1.948 raeburn 3626: }
1.400 www 3627: return %returnhash;
3628: }
3629:
3630: sub get_my_roles {
1.937 raeburn 3631: my ($uname,$udom,$context,$types,$roles,$roledoms,$withsec,$hidepriv)=@_;
1.620 albertel 3632: unless (defined($uname)) { $uname=$env{'user.name'}; }
3633: unless (defined($udom)) { $udom=$env{'user.domain'}; }
1.937 raeburn 3634: my (%dumphash,%nothide);
1.1086 raeburn 3635: if ($context eq 'userroles') {
1.1166 raeburn 3636: %dumphash = &dump('roles',$udom,$uname);
1.858 raeburn 3637: } else {
3638: %dumphash=
1.400 www 3639: &dump('nohist_userroles',$udom,$uname);
1.937 raeburn 3640: if ($hidepriv) {
3641: my %coursehash=&coursedescription($udom.'_'.$uname);
3642: foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
3643: if ($user !~ /:/) {
3644: $nothide{join(':',split(/[\@]/,$user))} = 1;
3645: } else {
3646: $nothide{$user} = 1;
3647: }
3648: }
3649: }
1.858 raeburn 3650: }
1.400 www 3651: my %returnhash=();
3652: my $now=time;
1.999 raeburn 3653: my %privileged;
1.800 albertel 3654: foreach my $entry (keys(%dumphash)) {
1.867 raeburn 3655: my ($role,$tend,$tstart);
3656: if ($context eq 'userroles') {
1.1149 raeburn 3657: next if ($entry =~ /^rolesdef/);
1.867 raeburn 3658: ($role,$tend,$tstart)=split(/_/,$dumphash{$entry});
3659: } else {
3660: ($tend,$tstart)=split(/\:/,$dumphash{$entry});
3661: }
1.400 www 3662: if (($tstart) && ($tstart<0)) { next; }
1.832 raeburn 3663: my $status = 'active';
1.939 raeburn 3664: if (($tend) && ($tend<=$now)) {
1.832 raeburn 3665: $status = 'previous';
3666: }
3667: if (($tstart) && ($now<$tstart)) {
3668: $status = 'future';
3669: }
3670: if (ref($types) eq 'ARRAY') {
3671: if (!grep(/^\Q$status\E$/,@{$types})) {
3672: next;
3673: }
3674: } else {
3675: if ($status ne 'active') {
3676: next;
3677: }
3678: }
1.867 raeburn 3679: my ($rolecode,$username,$domain,$section,$area);
3680: if ($context eq 'userroles') {
3681: ($area,$rolecode) = split(/_/,$entry);
3682: (undef,$domain,$username,$section) = split(/\//,$area);
3683: } else {
3684: ($role,$username,$domain,$section) = split(/\:/,$entry);
3685: }
1.832 raeburn 3686: if (ref($roledoms) eq 'ARRAY') {
3687: if (!grep(/^\Q$domain\E$/,@{$roledoms})) {
3688: next;
3689: }
3690: }
3691: if (ref($roles) eq 'ARRAY') {
3692: if (!grep(/^\Q$role\E$/,@{$roles})) {
1.922 raeburn 3693: if ($role =~ /^cr\//) {
3694: if (!grep(/^cr$/,@{$roles})) {
3695: next;
3696: }
1.1104 raeburn 3697: } elsif ($role =~ /^gr\//) {
3698: if (!grep(/^gr$/,@{$roles})) {
3699: next;
3700: }
1.922 raeburn 3701: } else {
3702: next;
3703: }
1.832 raeburn 3704: }
1.867 raeburn 3705: }
1.937 raeburn 3706: if ($hidepriv) {
1.999 raeburn 3707: if ($context eq 'userroles') {
3708: if ((&privileged($username,$domain)) &&
3709: (!$nothide{$username.':'.$domain})) {
3710: next;
3711: }
3712: } else {
3713: unless (ref($privileged{$domain}) eq 'HASH') {
3714: my %dompersonnel =
3715: &Apache::lonnet::get_domain_roles($domain,['dc'],$now,$now);
3716: $privileged{$domain} = {};
3717: if (keys(%dompersonnel)) {
3718: foreach my $server (keys(%dompersonnel)) {
3719: if (ref($dompersonnel{$server}) eq 'HASH') {
3720: foreach my $user (keys(%{$dompersonnel{$server}})) {
3721: my ($trole,$uname,$udom) = split(/:/,$user);
3722: $privileged{$udom}{$uname} = $trole;
3723: }
3724: }
3725: }
3726: }
3727: }
3728: if (exists($privileged{$domain}{$username})) {
3729: if (!$nothide{$username.':'.$domain}) {
3730: next;
3731: }
3732: }
1.937 raeburn 3733: }
3734: }
1.933 raeburn 3735: if ($withsec) {
3736: $returnhash{$username.':'.$domain.':'.$role.':'.$section} =
3737: $tstart.':'.$tend;
3738: } else {
3739: $returnhash{$username.':'.$domain.':'.$role}=$tstart.':'.$tend;
3740: }
1.832 raeburn 3741: }
1.373 www 3742: return %returnhash;
1.399 www 3743: }
3744:
3745: # ----------------------------------------------------- Frontpage Announcements
3746: #
3747: #
3748:
3749: sub postannounce {
3750: my ($server,$text)=@_;
1.844 albertel 3751: unless (&allowed('psa',&host_domain($server))) { return 'refused'; }
1.399 www 3752: unless ($text=~/\w/) { $text=''; }
3753: return &reply('setannounce:'.&escape($text),$server);
3754: }
3755:
3756: sub getannounce {
1.448 albertel 3757:
3758: if (open(my $fh,$perlvar{'lonDocRoot'}.'/announcement.txt')) {
1.399 www 3759: my $announcement='';
1.800 albertel 3760: while (my $line = <$fh>) { $announcement .= $line; }
1.448 albertel 3761: close($fh);
1.399 www 3762: if ($announcement=~/\w/) {
3763: return
3764: '<table bgcolor="#FF5555" cellpadding="5" cellspacing="3">'.
1.518 albertel 3765: '<tr><td bgcolor="#FFFFFF"><tt>'.$announcement.'</tt></td></tr></table>';
1.399 www 3766: } else {
3767: return '';
3768: }
3769: } else {
3770: return '';
3771: }
1.351 www 3772: }
1.353 www 3773:
3774: # ---------------------------------------------------------- Course ID routines
3775: # Deal with domain's nohist_courseid.db files
3776: #
3777:
3778: sub courseidput {
1.921 raeburn 3779: my ($domain,$storehash,$coursehome,$caller) = @_;
1.1054 raeburn 3780: return unless (ref($storehash) eq 'HASH');
1.921 raeburn 3781: my $outcome;
3782: if ($caller eq 'timeonly') {
3783: my $cids = '';
3784: foreach my $item (keys(%$storehash)) {
3785: $cids.=&escape($item).'&';
3786: }
3787: $cids=~s/\&$//;
3788: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$cids,
3789: $coursehome);
3790: } else {
3791: my $items = '';
3792: foreach my $item (keys(%$storehash)) {
3793: $items.= &escape($item).'='.
3794: &freeze_escape($$storehash{$item}).'&';
3795: }
3796: $items=~s/\&$//;
3797: $outcome = &reply('courseidputhash:'.$domain.':'.$caller.':'.$items,
3798: $coursehome);
1.918 raeburn 3799: }
3800: if ($outcome eq 'unknown_cmd') {
3801: my $what;
3802: foreach my $cid (keys(%$storehash)) {
3803: $what .= &escape($cid).'=';
1.921 raeburn 3804: foreach my $item ('description','inst_code','owner','type') {
1.936 raeburn 3805: $what .= &escape($storehash->{$cid}{$item}).':';
1.918 raeburn 3806: }
3807: $what =~ s/\:$/&/;
3808: }
3809: $what =~ s/\&$//;
3810: return &reply('courseidput:'.$domain.':'.$what,$coursehome);
3811: } else {
3812: return $outcome;
3813: }
1.353 www 3814: }
3815:
3816: sub courseiddump {
1.921 raeburn 3817: my ($domfilter,$descfilter,$sincefilter,$instcodefilter,$ownerfilter,
1.947 raeburn 3818: $coursefilter,$hostidflag,$hostidref,$typefilter,$regexp_ok,
1.1029 raeburn 3819: $selfenrollonly,$catfilter,$showhidden,$caller,$cloner,$cc_clone,
1.1071 raeburn 3820: $cloneonly,$createdbefore,$createdafter,$creationcontext,$domcloner)=@_;
1.918 raeburn 3821: my $as_hash = 1;
3822: my %returnhash;
3823: if (!$domfilter) { $domfilter=''; }
1.845 albertel 3824: my %libserv = &all_library();
3825: foreach my $tryserver (keys(%libserv)) {
3826: if ( ( $hostidflag == 1
3827: && grep(/^\Q$tryserver\E$/,@{$hostidref}) )
3828: || (!defined($hostidflag)) ) {
3829:
1.918 raeburn 3830: if (($domfilter eq '') ||
3831: (&host_domain($tryserver) eq $domfilter)) {
1.1180 droeschl 3832: my $rep;
3833: if (grep { $_ eq $tryserver } current_machine_ids()) {
3834: $rep = LONCAPA::Lond::dump_course_id_handler(
3835: join(":", (&host_domain($tryserver), $sincefilter,
3836: &escape($descfilter), &escape($instcodefilter),
3837: &escape($ownerfilter), &escape($coursefilter),
3838: &escape($typefilter), &escape($regexp_ok),
3839: $as_hash, &escape($selfenrollonly),
3840: &escape($catfilter), $showhidden, $caller,
3841: &escape($cloner), &escape($cc_clone), $cloneonly,
3842: &escape($createdbefore), &escape($createdafter),
3843: &escape($creationcontext), $domcloner)));
3844: } else {
3845: $rep = &reply('courseiddump:'.&host_domain($tryserver).':'.
3846: $sincefilter.':'.&escape($descfilter).':'.
3847: &escape($instcodefilter).':'.&escape($ownerfilter).
3848: ':'.&escape($coursefilter).':'.&escape($typefilter).
3849: ':'.&escape($regexp_ok).':'.$as_hash.':'.
3850: &escape($selfenrollonly).':'.&escape($catfilter).':'.
3851: $showhidden.':'.$caller.':'.&escape($cloner).':'.
3852: &escape($cc_clone).':'.$cloneonly.':'.
3853: &escape($createdbefore).':'.&escape($createdafter).':'.
3854: &escape($creationcontext).':'.$domcloner,
3855: $tryserver);
3856: }
3857:
1.918 raeburn 3858: my @pairs=split(/\&/,$rep);
3859: foreach my $item (@pairs) {
3860: my ($key,$value)=split(/\=/,$item,2);
3861: $key = &unescape($key);
3862: next if ($key =~ /^error: 2 /);
3863: my $result = &thaw_unescape($value);
3864: if (ref($result) eq 'HASH') {
3865: $returnhash{$key}=$result;
3866: } else {
1.921 raeburn 3867: my @responses = split(/:/,$value);
3868: my @items = ('description','inst_code','owner','type');
1.918 raeburn 3869: for (my $i=0; $i<@responses; $i++) {
1.921 raeburn 3870: $returnhash{$key}{$items[$i]} = &unescape($responses[$i]);
1.918 raeburn 3871: }
1.1008 raeburn 3872: }
1.353 www 3873: }
3874: }
3875: }
3876: }
3877: return %returnhash;
3878: }
3879:
1.1055 raeburn 3880: sub courselastaccess {
3881: my ($cdom,$cnum,$hostidref) = @_;
3882: my %returnhash;
3883: if ($cdom && $cnum) {
3884: my $chome = &homeserver($cnum,$cdom);
3885: if ($chome ne 'no_host') {
3886: my $rep = &reply('courselastaccess:'.$cdom.':'.$cnum,$chome);
3887: &extract_lastaccess(\%returnhash,$rep);
3888: }
3889: } else {
3890: if (!$cdom) { $cdom=''; }
3891: my %libserv = &all_library();
3892: foreach my $tryserver (keys(%libserv)) {
3893: if (ref($hostidref) eq 'ARRAY') {
3894: next unless (grep(/^\Q$tryserver\E$/,@{$hostidref}));
3895: }
3896: if (($cdom eq '') || (&host_domain($tryserver) eq $cdom)) {
3897: my $rep = &reply('courselastaccess:'.&host_domain($tryserver).':',$tryserver);
3898: &extract_lastaccess(\%returnhash,$rep);
3899: }
3900: }
3901: }
3902: return %returnhash;
3903: }
3904:
3905: sub extract_lastaccess {
3906: my ($returnhash,$rep) = @_;
3907: if (ref($returnhash) eq 'HASH') {
3908: unless ($rep eq 'unknown_command' || $rep eq 'no_such_host' ||
3909: $rep eq 'con_lost' || $rep eq 'rejected' || $rep eq 'refused' ||
3910: $rep eq '') {
3911: my @pairs=split(/\&/,$rep);
3912: foreach my $item (@pairs) {
3913: my ($key,$value)=split(/\=/,$item,2);
3914: $key = &unescape($key);
3915: next if ($key =~ /^error: 2 /);
3916: $returnhash->{$key} = &thaw_unescape($value);
3917: }
3918: }
3919: }
3920: return;
3921: }
3922:
1.658 raeburn 3923: # ---------------------------------------------------------- DC e-mail
1.662 raeburn 3924:
3925: sub dcmailput {
1.685 raeburn 3926: my ($domain,$msgid,$message,$server)=@_;
1.662 raeburn 3927: my $status = &Apache::lonnet::critical(
1.740 www 3928: 'dcmailput:'.$domain.':'.&escape($msgid).'='.
3929: &escape($message),$server);
1.662 raeburn 3930: return $status;
3931: }
3932:
1.658 raeburn 3933: sub dcmaildump {
3934: my ($dom,$startdate,$enddate,$senders) = @_;
1.685 raeburn 3935: my %returnhash=();
1.846 albertel 3936:
3937: if (defined(&domain($dom,'primary'))) {
1.685 raeburn 3938: my $cmd='dcmaildump:'.$dom.':'.&escape($startdate).':'.
3939: &escape($enddate).':';
3940: my @esc_senders=map { &escape($_)} @$senders;
3941: $cmd.=&escape(join('&',@esc_senders));
1.846 albertel 3942: foreach my $line (split(/\&/,&reply($cmd,&domain($dom,'primary')))) {
1.800 albertel 3943: my ($key,$value) = split(/\=/,$line,2);
1.685 raeburn 3944: if (($key) && ($value)) {
3945: $returnhash{&unescape($key)} = &unescape($value);
1.658 raeburn 3946: }
3947: }
3948: }
3949: return %returnhash;
3950: }
1.662 raeburn 3951: # ---------------------------------------------------------- Domain roles
3952:
3953: sub get_domain_roles {
3954: my ($dom,$roles,$startdate,$enddate)=@_;
1.1018 raeburn 3955: if ((!defined($startdate)) || ($startdate eq '')) {
1.662 raeburn 3956: $startdate = '.';
3957: }
1.1018 raeburn 3958: if ((!defined($enddate)) || ($enddate eq '')) {
1.662 raeburn 3959: $enddate = '.';
3960: }
1.922 raeburn 3961: my $rolelist;
3962: if (ref($roles) eq 'ARRAY') {
3963: $rolelist = join(':',@{$roles});
3964: }
1.662 raeburn 3965: my %personnel = ();
1.841 albertel 3966:
3967: my %servers = &get_servers($dom,'library');
3968: foreach my $tryserver (keys(%servers)) {
3969: %{$personnel{$tryserver}}=();
3970: foreach my $line (split(/\&/,&reply('domrolesdump:'.$dom.':'.
3971: &escape($startdate).':'.
3972: &escape($enddate).':'.
3973: &escape($rolelist), $tryserver))) {
3974: my ($key,$value) = split(/\=/,$line,2);
3975: if (($key) && ($value)) {
3976: $personnel{$tryserver}{&unescape($key)} = &unescape($value);
3977: }
3978: }
1.662 raeburn 3979: }
3980: return %personnel;
3981: }
1.658 raeburn 3982:
1.1057 www 3983: # ----------------------------------------------------------- Interval timing
1.149 www 3984:
1.1153 www 3985: {
3986: # Caches needed for speedup of navmaps
3987: # We don't want to cache this for very long at all (5 seconds at most)
3988: #
3989: # The user for whom we cache
3990: my $cachedkey='';
3991: # The cached times for this user
3992: my %cachedtimes=();
3993: # When this was last done
3994: my $cachedtime=();
3995:
3996: sub load_all_first_access {
1.1154 raeburn 3997: my ($uname,$udom)=@_;
1.1156 www 3998: if (($cachedkey eq $uname.':'.$udom) &&
1.1174 raeburn 3999: (abs($cachedtime-time)<5) && (!$env{'form.markaccess'})) {
1.1154 raeburn 4000: return;
4001: }
4002: $cachedtime=time;
4003: $cachedkey=$uname.':'.$udom;
4004: %cachedtimes=&dump('firstaccesstimes',$udom,$uname);
1.1153 www 4005: }
4006:
1.504 albertel 4007: sub get_first_access {
1.1162 raeburn 4008: my ($type,$argsymb,$argmap)=@_;
1.790 albertel 4009: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4010: if ($argsymb) { $symb=$argsymb; }
4011: my ($map,$id,$res)=&decode_symb($symb);
1.1162 raeburn 4012: if ($argmap) { $map = $argmap; }
1.926 albertel 4013: if ($type eq 'course') {
4014: $res='course';
4015: } elsif ($type eq 'map') {
1.588 albertel 4016: $res=&symbread($map);
4017: } else {
4018: $res=$symb;
4019: }
1.1153 www 4020: &load_all_first_access($uname,$udom);
4021: return $cachedtimes{"$courseid\0$res"};
1.504 albertel 4022: }
4023:
4024: sub set_first_access {
1.1162 raeburn 4025: my ($type,$interval)=@_;
1.790 albertel 4026: my ($symb,$courseid,$udom,$uname)=&whichuser();
1.504 albertel 4027: my ($map,$id,$res)=&decode_symb($symb);
1.928 albertel 4028: if ($type eq 'course') {
4029: $res='course';
4030: } elsif ($type eq 'map') {
1.588 albertel 4031: $res=&symbread($map);
4032: } else {
4033: $res=$symb;
4034: }
1.1153 www 4035: $cachedkey='';
1.1162 raeburn 4036: my $firstaccess=&get_first_access($type,$symb,$map);
1.505 albertel 4037: if (!$firstaccess) {
1.1162 raeburn 4038: my $start = time;
4039: my $putres = &put('firstaccesstimes',{"$courseid\0$res"=>$start},
4040: $udom,$uname);
4041: if ($putres eq 'ok') {
4042: &put('timerinterval',{"$courseid\0$res"=>$interval},
4043: $udom,$uname);
4044: &appenv(
4045: {
4046: 'course.'.$courseid.'.firstaccess.'.$res => $start,
4047: 'course.'.$courseid.'.timerinterval.'.$res => $interval,
4048: }
4049: );
4050: }
4051: return $putres;
1.505 albertel 4052: }
4053: return 'already_set';
1.504 albertel 4054: }
1.1153 www 4055: }
1.110 www 4056: # --------------------------------------------- Set Expire Date for Spreadsheet
4057:
4058: sub expirespread {
4059: my ($uname,$udom,$stype,$usymb)=@_;
1.620 albertel 4060: my $cid=$env{'request.course.id'};
1.110 www 4061: if ($cid) {
4062: my $now=time;
4063: my $key=$uname.':'.$udom.':'.$stype.':'.$usymb;
1.620 albertel 4064: return &reply('put:'.$env{'course.'.$cid.'.domain'}.':'.
4065: $env{'course.'.$cid.'.num'}.
1.110 www 4066: ':nohist_expirationdates:'.
4067: &escape($key).'='.$now,
1.620 albertel 4068: $env{'course.'.$cid.'.home'})
1.110 www 4069: }
4070: return 'ok';
1.14 www 4071: }
4072:
1.109 www 4073: # ----------------------------------------------------- Devalidate Spreadsheets
4074:
4075: sub devalidate {
1.325 www 4076: my ($symb,$uname,$udom)=@_;
1.620 albertel 4077: my $cid=$env{'request.course.id'};
1.109 www 4078: if ($cid) {
1.391 matthew 4079: # delete the stored spreadsheets for
4080: # - the student level sheet of this user in course's homespace
4081: # - the assessment level sheet for this resource
4082: # for this user in user's homespace
1.553 albertel 4083: # - current conditional state info
1.325 www 4084: my $key=$uname.':'.$udom.':';
1.109 www 4085: my $status=
1.299 matthew 4086: &del('nohist_calculatedsheets',
1.391 matthew 4087: [$key.'studentcalc:'],
1.620 albertel 4088: $env{'course.'.$cid.'.domain'},
4089: $env{'course.'.$cid.'.num'})
1.133 albertel 4090: .' '.
4091: &del('nohist_calculatedsheets_'.$cid,
1.391 matthew 4092: [$key.'assesscalc:'.$symb],$udom,$uname);
1.109 www 4093: unless ($status eq 'ok ok') {
4094: &logthis('Could not devalidate spreadsheet '.
1.325 www 4095: $uname.' at '.$udom.' for '.
1.109 www 4096: $symb.': '.$status);
1.133 albertel 4097: }
1.553 albertel 4098: &delenv('user.state.'.$cid);
1.109 www 4099: }
4100: }
4101:
1.265 albertel 4102: sub get_scalar {
4103: my ($string,$end) = @_;
4104: my $value;
4105: if ($$string =~ s/^([^&]*?)($end)/$2/) {
4106: $value = $1;
4107: } elsif ($$string =~ s/^([^&]*?)&//) {
4108: $value = $1;
4109: }
4110: return &unescape($value);
4111: }
4112:
4113: sub array2str {
4114: my (@array) = @_;
4115: my $result=&arrayref2str(\@array);
4116: $result=~s/^__ARRAY_REF__//;
4117: $result=~s/__END_ARRAY_REF__$//;
4118: return $result;
4119: }
4120:
1.204 albertel 4121: sub arrayref2str {
4122: my ($arrayref) = @_;
1.265 albertel 4123: my $result='__ARRAY_REF__';
1.204 albertel 4124: foreach my $elem (@$arrayref) {
1.265 albertel 4125: if(ref($elem) eq 'ARRAY') {
4126: $result.=&arrayref2str($elem).'&';
4127: } elsif(ref($elem) eq 'HASH') {
4128: $result.=&hashref2str($elem).'&';
4129: } elsif(ref($elem)) {
4130: #print("Got a ref of ".(ref($elem))." skipping.");
1.204 albertel 4131: } else {
4132: $result.=&escape($elem).'&';
4133: }
4134: }
4135: $result=~s/\&$//;
1.265 albertel 4136: $result .= '__END_ARRAY_REF__';
1.204 albertel 4137: return $result;
4138: }
4139:
1.168 albertel 4140: sub hash2str {
1.204 albertel 4141: my (%hash) = @_;
4142: my $result=&hashref2str(\%hash);
1.265 albertel 4143: $result=~s/^__HASH_REF__//;
4144: $result=~s/__END_HASH_REF__$//;
1.204 albertel 4145: return $result;
4146: }
4147:
4148: sub hashref2str {
4149: my ($hashref)=@_;
1.265 albertel 4150: my $result='__HASH_REF__';
1.800 albertel 4151: foreach my $key (sort(keys(%$hashref))) {
4152: if (ref($key) eq 'ARRAY') {
4153: $result.=&arrayref2str($key).'=';
4154: } elsif (ref($key) eq 'HASH') {
4155: $result.=&hashref2str($key).'=';
4156: } elsif (ref($key)) {
1.265 albertel 4157: $result.='=';
1.800 albertel 4158: #print("Got a ref of ".(ref($key))." skipping.");
1.204 albertel 4159: } else {
1.1132 raeburn 4160: if (defined($key)) {$result.=&escape($key).'=';} else { last; }
1.204 albertel 4161: }
4162:
1.800 albertel 4163: if(ref($hashref->{$key}) eq 'ARRAY') {
4164: $result.=&arrayref2str($hashref->{$key}).'&';
4165: } elsif(ref($hashref->{$key}) eq 'HASH') {
4166: $result.=&hashref2str($hashref->{$key}).'&';
4167: } elsif(ref($hashref->{$key})) {
1.265 albertel 4168: $result.='&';
1.800 albertel 4169: #print("Got a ref of ".(ref($hashref->{$key}))." skipping.");
1.204 albertel 4170: } else {
1.800 albertel 4171: $result.=&escape($hashref->{$key}).'&';
1.204 albertel 4172: }
4173: }
1.168 albertel 4174: $result=~s/\&$//;
1.265 albertel 4175: $result .= '__END_HASH_REF__';
1.168 albertel 4176: return $result;
4177: }
4178:
4179: sub str2hash {
1.265 albertel 4180: my ($string)=@_;
4181: my ($hash)=&str2hashref('__HASH_REF__'.$string.'__END_HASH_REF__');
4182: return %$hash;
4183: }
4184:
4185: sub str2hashref {
1.168 albertel 4186: my ($string) = @_;
1.265 albertel 4187:
4188: my %hash;
4189:
4190: if($string !~ /^__HASH_REF__/) {
4191: if (! ($string eq '' || !defined($string))) {
4192: $hash{'error'}='Not hash reference';
4193: }
4194: return (\%hash, $string);
4195: }
4196:
4197: $string =~ s/^__HASH_REF__//;
4198:
4199: while($string !~ /^__END_HASH_REF__/) {
4200: #key
4201: my $key='';
4202: if($string =~ /^__HASH_REF__/) {
4203: ($key, $string)=&str2hashref($string);
4204: if(defined($key->{'error'})) {
4205: $hash{'error'}='Bad data';
4206: return (\%hash, $string);
4207: }
4208: } elsif($string =~ /^__ARRAY_REF__/) {
4209: ($key, $string)=&str2arrayref($string);
4210: if($key->[0] eq 'Array reference error') {
4211: $hash{'error'}='Bad data';
4212: return (\%hash, $string);
4213: }
4214: } else {
4215: $string =~ s/^(.*?)=//;
1.267 albertel 4216: $key=&unescape($1);
1.265 albertel 4217: }
4218: $string =~ s/^=//;
4219:
4220: #value
4221: my $value='';
4222: if($string =~ /^__HASH_REF__/) {
4223: ($value, $string)=&str2hashref($string);
4224: if(defined($value->{'error'})) {
4225: $hash{'error'}='Bad data';
4226: return (\%hash, $string);
4227: }
4228: } elsif($string =~ /^__ARRAY_REF__/) {
4229: ($value, $string)=&str2arrayref($string);
4230: if($value->[0] eq 'Array reference error') {
4231: $hash{'error'}='Bad data';
4232: return (\%hash, $string);
4233: }
4234: } else {
4235: $value=&get_scalar(\$string,'__END_HASH_REF__');
4236: }
4237: $string =~ s/^&//;
4238:
4239: $hash{$key}=$value;
1.204 albertel 4240: }
1.265 albertel 4241:
4242: $string =~ s/^__END_HASH_REF__//;
4243:
4244: return (\%hash, $string);
1.204 albertel 4245: }
4246:
4247: sub str2array {
1.265 albertel 4248: my ($string)=@_;
4249: my ($array)=&str2arrayref('__ARRAY_REF__'.$string.'__END_ARRAY_REF__');
4250: return @$array;
4251: }
4252:
4253: sub str2arrayref {
1.204 albertel 4254: my ($string) = @_;
1.265 albertel 4255: my @array;
4256:
4257: if($string !~ /^__ARRAY_REF__/) {
4258: if (! ($string eq '' || !defined($string))) {
4259: $array[0]='Array reference error';
4260: }
4261: return (\@array, $string);
4262: }
4263:
4264: $string =~ s/^__ARRAY_REF__//;
4265:
4266: while($string !~ /^__END_ARRAY_REF__/) {
4267: my $value='';
4268: if($string =~ /^__HASH_REF__/) {
4269: ($value, $string)=&str2hashref($string);
4270: if(defined($value->{'error'})) {
4271: $array[0] ='Array reference error';
4272: return (\@array, $string);
4273: }
4274: } elsif($string =~ /^__ARRAY_REF__/) {
4275: ($value, $string)=&str2arrayref($string);
4276: if($value->[0] eq 'Array reference error') {
4277: $array[0] ='Array reference error';
4278: return (\@array, $string);
4279: }
4280: } else {
4281: $value=&get_scalar(\$string,'__END_ARRAY_REF__');
4282: }
4283: $string =~ s/^&//;
4284:
4285: push(@array, $value);
1.191 harris41 4286: }
1.265 albertel 4287:
4288: $string =~ s/^__END_ARRAY_REF__//;
4289:
4290: return (\@array, $string);
1.168 albertel 4291: }
4292:
1.167 albertel 4293: # -------------------------------------------------------------------Temp Store
4294:
1.168 albertel 4295: sub tmpreset {
4296: my ($symb,$namespace,$domain,$stuname) = @_;
4297: if (!$symb) {
4298: $symb=&symbread();
1.620 albertel 4299: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4300: }
4301: $symb=escape($symb);
4302:
1.620 albertel 4303: if (!$namespace) { $namespace=$env{'request.state'}; }
1.168 albertel 4304: $namespace=~s/\//\_/g;
4305: $namespace=~s/\W//g;
4306:
1.620 albertel 4307: if (!$domain) { $domain=$env{'user.domain'}; }
4308: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4309: if ($domain eq 'public' && $stuname eq 'public') {
4310: $stuname=$ENV{'REMOTE_ADDR'};
4311: }
1.1117 foxr 4312: my $path=LONCAPA::tempdir();
1.168 albertel 4313: my %hash;
4314: if (tie(%hash,'GDBM_File',
4315: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4316: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 4317: foreach my $key (keys(%hash)) {
1.180 albertel 4318: if ($key=~ /:$symb/) {
1.168 albertel 4319: delete($hash{$key});
4320: }
4321: }
4322: }
4323: }
4324:
1.167 albertel 4325: sub tmpstore {
1.168 albertel 4326: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4327:
4328: if (!$symb) {
4329: $symb=&symbread();
1.620 albertel 4330: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4331: }
4332: $symb=escape($symb);
4333:
4334: if (!$namespace) {
4335: # I don't think we would ever want to store this for a course.
4336: # it seems this will only be used if we don't have a course.
1.620 albertel 4337: #$namespace=$env{'request.course.id'};
1.168 albertel 4338: #if (!$namespace) {
1.620 albertel 4339: $namespace=$env{'request.state'};
1.168 albertel 4340: #}
4341: }
4342: $namespace=~s/\//\_/g;
4343: $namespace=~s/\W//g;
1.620 albertel 4344: if (!$domain) { $domain=$env{'user.domain'}; }
4345: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4346: if ($domain eq 'public' && $stuname eq 'public') {
4347: $stuname=$ENV{'REMOTE_ADDR'};
4348: }
1.168 albertel 4349: my $now=time;
4350: my %hash;
1.1117 foxr 4351: my $path=LONCAPA::tempdir();
1.168 albertel 4352: if (tie(%hash,'GDBM_File',
4353: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4354: &GDBM_WRCREAT(),0640)) {
1.168 albertel 4355: $hash{"version:$symb"}++;
4356: my $version=$hash{"version:$symb"};
4357: my $allkeys='';
4358: foreach my $key (keys(%$storehash)) {
4359: $allkeys.=$key.':';
1.591 albertel 4360: $hash{"$version:$symb:$key"}=&freeze_escape($$storehash{$key});
1.168 albertel 4361: }
4362: $hash{"$version:$symb:timestamp"}=$now;
4363: $allkeys.='timestamp';
4364: $hash{"$version:keys:$symb"}=$allkeys;
4365: if (untie(%hash)) {
4366: return 'ok';
4367: } else {
4368: return "error:$!";
4369: }
4370: } else {
4371: return "error:$!";
4372: }
4373: }
1.167 albertel 4374:
1.168 albertel 4375: # -----------------------------------------------------------------Temp Restore
1.167 albertel 4376:
1.168 albertel 4377: sub tmprestore {
4378: my ($symb,$namespace,$domain,$stuname) = @_;
1.167 albertel 4379:
1.168 albertel 4380: if (!$symb) {
4381: $symb=&symbread();
1.620 albertel 4382: if (!$symb) { $symb= $env{'request.url'}; }
1.168 albertel 4383: }
4384: $symb=escape($symb);
4385:
1.620 albertel 4386: if (!$namespace) { $namespace=$env{'request.state'}; }
1.591 albertel 4387:
1.620 albertel 4388: if (!$domain) { $domain=$env{'user.domain'}; }
4389: if (!$stuname) { $stuname=$env{'user.name'}; }
1.591 albertel 4390: if ($domain eq 'public' && $stuname eq 'public') {
4391: $stuname=$ENV{'REMOTE_ADDR'};
4392: }
1.168 albertel 4393: my %returnhash;
4394: $namespace=~s/\//\_/g;
4395: $namespace=~s/\W//g;
4396: my %hash;
1.1117 foxr 4397: my $path=LONCAPA::tempdir();
1.168 albertel 4398: if (tie(%hash,'GDBM_File',
4399: $path.'/tmpstore_'.$stuname.'_'.$domain.'_'.$namespace.'.db',
1.256 albertel 4400: &GDBM_READER(),0640)) {
1.168 albertel 4401: my $version=$hash{"version:$symb"};
4402: $returnhash{'version'}=$version;
4403: my $scope;
4404: for ($scope=1;$scope<=$version;$scope++) {
4405: my $vkeys=$hash{"$scope:keys:$symb"};
4406: my @keys=split(/:/,$vkeys);
4407: my $key;
4408: $returnhash{"$scope:keys"}=$vkeys;
4409: foreach $key (@keys) {
1.591 albertel 4410: $returnhash{"$scope:$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
4411: $returnhash{"$key"}=&thaw_unescape($hash{"$scope:$symb:$key"});
1.167 albertel 4412: }
4413: }
1.168 albertel 4414: if (!(untie(%hash))) {
4415: return "error:$!";
4416: }
4417: } else {
4418: return "error:$!";
4419: }
4420: return %returnhash;
1.167 albertel 4421: }
4422:
1.9 www 4423: # ----------------------------------------------------------------------- Store
4424:
4425: sub store {
1.124 www 4426: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4427: my $home='';
4428:
1.168 albertel 4429: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4430:
1.213 www 4431: $symb=&symbclean($symb);
1.122 albertel 4432: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4433:
1.620 albertel 4434: if (!$domain) { $domain=$env{'user.domain'}; }
4435: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4436:
4437: &devalidate($symb,$stuname,$domain);
1.109 www 4438:
4439: $symb=escape($symb);
1.187 www 4440: if (!$namespace) {
1.620 albertel 4441: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4442: return '';
4443: }
4444: }
1.620 albertel 4445: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4446:
4447: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4448: $$storehash{'host'}=$perlvar{'lonHostID'};
4449:
1.12 www 4450: my $namevalue='';
1.800 albertel 4451: foreach my $key (keys(%$storehash)) {
4452: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4453: }
1.12 www 4454: $namevalue=~s/\&$//;
1.187 www 4455: &courselog($symb.':'.$stuname.':'.$domain.':STORE:'.$namevalue);
1.124 www 4456: return reply("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.9 www 4457: }
4458:
1.47 www 4459: # -------------------------------------------------------------- Critical Store
4460:
4461: sub cstore {
1.124 www 4462: my ($storehash,$symb,$namespace,$domain,$stuname) = @_;
4463: my $home='';
4464:
1.168 albertel 4465: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4466:
1.213 www 4467: $symb=&symbclean($symb);
1.122 albertel 4468: if (!$symb) { unless ($symb=&symbread()) { return ''; } }
1.109 www 4469:
1.620 albertel 4470: if (!$domain) { $domain=$env{'user.domain'}; }
4471: if (!$stuname) { $stuname=$env{'user.name'}; }
1.325 www 4472:
4473: &devalidate($symb,$stuname,$domain);
1.109 www 4474:
4475: $symb=escape($symb);
1.187 www 4476: if (!$namespace) {
1.620 albertel 4477: unless ($namespace=$env{'request.course.id'}) {
1.187 www 4478: return '';
4479: }
4480: }
1.620 albertel 4481: if (!$home) { $home=$env{'user.home'}; }
1.447 www 4482:
4483: $$storehash{'ip'}=$ENV{'REMOTE_ADDR'};
4484: $$storehash{'host'}=$perlvar{'lonHostID'};
1.122 albertel 4485:
1.47 www 4486: my $namevalue='';
1.800 albertel 4487: foreach my $key (keys(%$storehash)) {
4488: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
1.191 harris41 4489: }
1.47 www 4490: $namevalue=~s/\&$//;
1.187 www 4491: &courselog($symb.':'.$stuname.':'.$domain.':CSTORE:'.$namevalue);
1.188 www 4492: return critical
4493: ("store:$domain:$stuname:$namespace:$symb:$namevalue","$home");
1.47 www 4494: }
4495:
1.9 www 4496: # --------------------------------------------------------------------- Restore
4497:
4498: sub restore {
1.124 www 4499: my ($symb,$namespace,$domain,$stuname) = @_;
4500: my $home='';
4501:
1.168 albertel 4502: if ($stuname) { $home=&homeserver($stuname,$domain); }
1.124 www 4503:
1.122 albertel 4504: if (!$symb) {
4505: unless ($symb=escape(&symbread())) { return ''; }
4506: } else {
1.213 www 4507: $symb=&escape(&symbclean($symb));
1.122 albertel 4508: }
1.188 www 4509: if (!$namespace) {
1.620 albertel 4510: unless ($namespace=$env{'request.course.id'}) {
1.188 www 4511: return '';
4512: }
4513: }
1.620 albertel 4514: if (!$domain) { $domain=$env{'user.domain'}; }
4515: if (!$stuname) { $stuname=$env{'user.name'}; }
4516: if (!$home) { $home=$env{'user.home'}; }
1.122 albertel 4517: my $answer=&reply("restore:$domain:$stuname:$namespace:$symb","$home");
4518:
1.12 www 4519: my %returnhash=();
1.800 albertel 4520: foreach my $line (split(/\&/,$answer)) {
4521: my ($name,$value)=split(/\=/,$line);
1.591 albertel 4522: $returnhash{&unescape($name)}=&thaw_unescape($value);
1.191 harris41 4523: }
1.75 www 4524: my $version;
4525: for ($version=1;$version<=$returnhash{'version'};$version++) {
1.800 albertel 4526: foreach my $item (split(/\:/,$returnhash{$version.':keys'})) {
4527: $returnhash{$item}=$returnhash{$version.':'.$item};
1.191 harris41 4528: }
1.75 www 4529: }
1.13 www 4530: return %returnhash;
1.34 www 4531: }
4532:
4533: # ---------------------------------------------------------- Course Description
1.1118 foxr 4534: #
4535: #
1.34 www 4536:
4537: sub coursedescription {
1.731 albertel 4538: my ($courseid,$args)=@_;
1.34 www 4539: $courseid=~s/^\///;
1.49 www 4540: $courseid=~s/\_/\//g;
1.34 www 4541: my ($cdomain,$cnum)=split(/\//,$courseid);
1.129 albertel 4542: my $chome=&homeserver($cnum,$cdomain);
1.302 albertel 4543: my $normalid=$cdomain.'_'.$cnum;
4544: # need to always cache even if we get errors otherwise we keep
4545: # trying and trying and trying to get the course description.
4546: my %envhash=();
4547: my %returnhash=();
1.731 albertel 4548:
4549: my $expiretime=600;
4550: if ($env{'request.course.id'} eq $normalid) {
4551: $expiretime=120;
4552: }
4553:
4554: my $prefix='course.'.$cdomain.'_'.$cnum.'.';
4555: if (!$args->{'freshen_cache'}
4556: && ((time-$env{$prefix.'last_cache'}) < $expiretime) ) {
4557: foreach my $key (keys(%env)) {
4558: next if ($key !~ /^\Q$prefix\E(.*)/);
4559: my ($setting) = $1;
4560: $returnhash{$setting} = $env{$key};
4561: }
4562: return %returnhash;
4563: }
4564:
1.1118 foxr 4565: # get the data again
4566:
1.731 albertel 4567: if (!$args->{'one_time'}) {
4568: $envhash{'course.'.$normalid.'.last_cache'}=time;
4569: }
1.811 albertel 4570:
1.34 www 4571: if ($chome ne 'no_host') {
1.302 albertel 4572: %returnhash=&dump('environment',$cdomain,$cnum);
1.129 albertel 4573: if (!exists($returnhash{'con_lost'})) {
1.1118 foxr 4574: my $username = $env{'user.name'}; # Defult username
4575: if(defined $args->{'user'}) {
4576: $username = $args->{'user'};
4577: }
1.129 albertel 4578: $returnhash{'home'}= $chome;
4579: $returnhash{'domain'} = $cdomain;
4580: $returnhash{'num'} = $cnum;
1.741 raeburn 4581: if (!defined($returnhash{'type'})) {
4582: $returnhash{'type'} = 'Course';
4583: }
1.130 albertel 4584: while (my ($name,$value) = each %returnhash) {
1.53 www 4585: $envhash{'course.'.$normalid.'.'.$name}=$value;
1.129 albertel 4586: }
1.270 www 4587: $returnhash{'url'}=&clutter($returnhash{'url'});
1.1117 foxr 4588: $returnhash{'fn'}=LONCAPA::tempdir() .
1.1118 foxr 4589: $username.'_'.$cdomain.'_'.$cnum;
1.60 www 4590: $envhash{'course.'.$normalid.'.home'}=$chome;
4591: $envhash{'course.'.$normalid.'.domain'}=$cdomain;
4592: $envhash{'course.'.$normalid.'.num'}=$cnum;
1.34 www 4593: }
4594: }
1.731 albertel 4595: if (!$args->{'one_time'}) {
1.949 raeburn 4596: &appenv(\%envhash);
1.731 albertel 4597: }
1.302 albertel 4598: return %returnhash;
1.461 www 4599: }
4600:
1.1080 raeburn 4601: sub update_released_required {
4602: my ($needsrelease,$cdom,$cnum,$chome,$cid) = @_;
4603: if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
4604: $cid = $env{'request.course.id'};
4605: $cdom = $env{'course.'.$cid.'.domain'};
4606: $cnum = $env{'course.'.$cid.'.num'};
4607: $chome = $env{'course.'.$cid.'.home'};
4608: }
4609: if ($needsrelease) {
4610: my %curr_reqd_hash = &userenvironment($cdom,$cnum,'internal.releaserequired');
4611: my $needsupdate;
4612: if ($curr_reqd_hash{'internal.releaserequired'} eq '') {
4613: $needsupdate = 1;
4614: } else {
4615: my ($currmajor,$currminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
4616: my ($needsmajor,$needsminor) = split(/\./,$needsrelease);
4617: if (($currmajor < $needsmajor) || ($currmajor == $needsmajor && $currminor < $needsminor)) {
4618: $needsupdate = 1;
4619: }
4620: }
4621: if ($needsupdate) {
4622: my %needshash = (
4623: 'internal.releaserequired' => $needsrelease,
4624: );
4625: my $putresult = &put('environment',\%needshash,$cdom,$cnum);
4626: if ($putresult eq 'ok') {
4627: &appenv({'course.'.$cid.'.internal.releaserequired' => $needsrelease});
4628: my %crsinfo = &courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
4629: if (ref($crsinfo{$cid}) eq 'HASH') {
4630: $crsinfo{$cid}{'releaserequired'} = $needsrelease;
4631: &courseidput($cdom,\%crsinfo,$chome,'notime');
4632: }
4633: }
4634: }
4635: }
4636: return;
4637: }
4638:
1.461 www 4639: # -------------------------------------------------See if a user is privileged
4640:
4641: sub privileged {
4642: my ($username,$domain)=@_;
1.1170 droeschl 4643:
4644: my %rolesdump = &dump("roles", $domain, $username) or return 0;
4645: my $now = time;
4646:
4647: for my $role (@rolesdump{grep { ! /^rolesdef_/ } keys %rolesdump}) {
4648: my ($trole, $tend, $tstart) = split(/_/, $role);
4649: if (($trole eq 'dc') || ($trole eq 'su')) {
4650: return 1 unless ($tend && $tend < $now)
4651: or ($tstart && $tstart > $now);
4652: }
1.461 www 4653: }
1.1170 droeschl 4654:
1.461 www 4655: return 0;
1.9 www 4656: }
1.1 albertel 4657:
1.103 harris41 4658: # -------------------------------------------------------- Get user privileges
1.11 www 4659:
4660: sub rolesinit {
1.1169 droeschl 4661: my ($domain, $username) = @_;
4662: my %userroles = ('user.login.time' => time);
4663: my %rolesdump = &dump("roles", $domain, $username) or return \%userroles;
4664:
4665: # firstaccess and timerinterval are related to timed maps/resources.
4666: # also, blocking can be triggered by an activating timer
4667: # it's saved in the user's %env.
4668: my %firstaccess = &dump('firstaccesstimes', $domain, $username);
4669: my %timerinterval = &dump('timerinterval', $domain, $username);
4670: my (%coursetimerstarts, %firstaccchk, %firstaccenv, %coursetimerintervals,
4671: %timerintchk, %timerintenv);
4672:
1.1162 raeburn 4673: foreach my $key (keys(%firstaccess)) {
1.1169 droeschl 4674: my ($cid, $rest) = split(/\0/, $key);
1.1162 raeburn 4675: $coursetimerstarts{$cid}{$rest} = $firstaccess{$key};
4676: }
1.1169 droeschl 4677:
1.1162 raeburn 4678: foreach my $key (keys(%timerinterval)) {
4679: my ($cid,$rest) = split(/\0/,$key);
4680: $coursetimerintervals{$cid}{$rest} = $timerinterval{$key};
4681: }
1.1169 droeschl 4682:
1.11 www 4683: my %allroles=();
1.1162 raeburn 4684: my %allgroups=();
1.11 www 4685:
1.1169 droeschl 4686: for my $area (grep { ! /^rolesdef_/ } keys %rolesdump) {
4687: my $role = $rolesdump{$area};
4688: $area =~ s/\_\w\w$//;
4689:
4690: my ($trole, $tend, $tstart, $group_privs);
4691:
4692: if ($role =~ /^cr/) {
4693: # Custom role, defined by a user
4694: # e.g., user.role.cr/msu/smith/mynewrole
4695: if ($role =~ m|^(cr/$match_domain/$match_username/[a-zA-Z0-9]+)_(.*)$|) {
4696: $trole = $1;
4697: ($tend, $tstart) = split('_', $2);
4698: } else {
4699: $trole = $role;
4700: }
4701: } elsif ($role =~ m|^gr/|) {
4702: # Role of member in a group, defined within a course/community
4703: # e.g., user.role.gr/msu/04935610a19ee4a5fmsul1/leopards
4704: ($trole, $tend, $tstart) = split(/_/, $role);
4705: next if $tstart eq '-1';
4706: ($trole, $group_privs) = split(/\//, $trole);
4707: $group_privs = &unescape($group_privs);
4708: } else {
4709: # Just a normal role, defined in roles.tab
4710: ($trole, $tend, $tstart) = split(/_/,$role);
4711: }
4712:
4713: my %new_role = &set_arearole($trole,$area,$tstart,$tend,$domain,
4714: $username);
4715: @userroles{keys(%new_role)} = @new_role{keys(%new_role)};
4716:
4717: # role expired or not available yet?
4718: $trole = '' if ($tend != 0 && $tend < $userroles{'user.login.time'}) or
4719: ($tstart != 0 && $tstart > $userroles{'user.login.time'});
4720:
4721: next if $area eq '' or $trole eq '';
4722:
4723: my $spec = "$trole.$area";
4724: my ($tdummy, $tdomain, $trest) = split(/\//, $area);
4725:
4726: if ($trole =~ /^cr\//) {
4727: # Custom role, defined by a user
4728: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
4729: } elsif ($trole eq 'gr') {
4730: # Role of a member in a group, defined within a course/community
4731: &group_roleprivs(\%allgroups,$area,$group_privs,$tend,$tstart);
4732: next;
4733: } else {
4734: # Normal role, defined in roles.tab
4735: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
4736: }
4737:
4738: my $cid = $tdomain.'_'.$trest;
4739: unless ($firstaccchk{$cid}) {
4740: if (ref($coursetimerstarts{$cid}) eq 'HASH') {
4741: foreach my $item (keys(%{$coursetimerstarts{$cid}})) {
4742: $firstaccenv{'course.'.$cid.'.firstaccess.'.$item} =
4743: $coursetimerstarts{$cid}{$item};
4744: }
4745: }
4746: $firstaccchk{$cid} = 1;
4747: }
4748: unless ($timerintchk{$cid}) {
4749: if (ref($coursetimerintervals{$cid}) eq 'HASH') {
4750: foreach my $item (keys(%{$coursetimerintervals{$cid}})) {
4751: $timerintenv{'course.'.$cid.'.timerinterval.'.$item} =
4752: $coursetimerintervals{$cid}{$item};
1.1162 raeburn 4753: }
1.12 www 4754: }
1.1169 droeschl 4755: $timerintchk{$cid} = 1;
1.191 harris41 4756: }
1.11 www 4757: }
1.1169 droeschl 4758:
4759: @userroles{'user.author', 'user.adv'} = &set_userprivs(\%userroles,
4760: \%allroles, \%allgroups);
4761: $env{'user.adv'} = $userroles{'user.adv'};
4762:
1.1162 raeburn 4763: return (\%userroles,\%firstaccenv,\%timerintenv);
1.11 www 4764: }
4765:
1.567 raeburn 4766: sub set_arearole {
4767: my ($trole,$area,$tstart,$tend,$domain,$username) = @_;
4768: # log the associated role with the area
4769: &userrolelog($trole,$username,$domain,$area,$tstart,$tend);
1.743 albertel 4770: return ('user.role.'.$trole.'.'.$area => $tstart.'.'.$tend);
1.567 raeburn 4771: }
4772:
4773: sub custom_roleprivs {
4774: my ($allroles,$trole,$tdomain,$trest,$spec,$area) = @_;
4775: my ($rdummy,$rdomain,$rauthor,$rrole)=split(/\//,$trole);
4776: my $homsvr=homeserver($rauthor,$rdomain);
1.838 albertel 4777: if (&hostname($homsvr) ne '') {
1.567 raeburn 4778: my ($rdummy,$roledef)=
4779: &get('roles',["rolesdef_$rrole"],$rdomain,$rauthor);
4780: if (($rdummy ne 'con_lost') && ($roledef ne '')) {
4781: my ($syspriv,$dompriv,$coursepriv)=split(/\_/,$roledef);
4782: if (defined($syspriv)) {
1.1043 raeburn 4783: if ($trest =~ /^$match_community$/) {
4784: $syspriv =~ s/bre\&S//;
4785: }
1.567 raeburn 4786: $$allroles{'cm./'}.=':'.$syspriv;
4787: $$allroles{$spec.'./'}.=':'.$syspriv;
4788: }
4789: if ($tdomain ne '') {
4790: if (defined($dompriv)) {
4791: $$allroles{'cm./'.$tdomain.'/'}.=':'.$dompriv;
4792: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$dompriv;
4793: }
4794: if (($trest ne '') && (defined($coursepriv))) {
4795: $$allroles{'cm.'.$area}.=':'.$coursepriv;
4796: $$allroles{$spec.'.'.$area}.=':'.$coursepriv;
4797: }
4798: }
4799: }
4800: }
4801: }
4802:
1.678 raeburn 4803: sub group_roleprivs {
4804: my ($allgroups,$area,$group_privs,$tend,$tstart) = @_;
4805: my $access = 1;
4806: my $now = time;
4807: if (($tend!=0) && ($tend<$now)) { $access = 0; }
4808: if (($tstart!=0) && ($tstart>$now)) { $access=0; }
4809: if ($access) {
1.811 albertel 4810: my ($course,$group) = ($area =~ m|(/$match_domain/$match_courseid)/([^/]+)$|);
1.678 raeburn 4811: $$allgroups{$course}{$group} .=':'.$group_privs;
4812: }
4813: }
1.567 raeburn 4814:
4815: sub standard_roleprivs {
4816: my ($allroles,$trole,$tdomain,$spec,$trest,$area) = @_;
4817: if (defined($pr{$trole.':s'})) {
4818: $$allroles{'cm./'}.=':'.$pr{$trole.':s'};
4819: $$allroles{$spec.'./'}.=':'.$pr{$trole.':s'};
4820: }
4821: if ($tdomain ne '') {
4822: if (defined($pr{$trole.':d'})) {
4823: $$allroles{'cm./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4824: $$allroles{$spec.'./'.$tdomain.'/'}.=':'.$pr{$trole.':d'};
4825: }
4826: if (($trest ne '') && (defined($pr{$trole.':c'}))) {
4827: $$allroles{'cm.'.$area}.=':'.$pr{$trole.':c'};
4828: $$allroles{$spec.'.'.$area}.=':'.$pr{$trole.':c'};
4829: }
4830: }
4831: }
4832:
4833: sub set_userprivs {
1.1064 raeburn 4834: my ($userroles,$allroles,$allgroups,$groups_roles) = @_;
1.567 raeburn 4835: my $author=0;
4836: my $adv=0;
1.678 raeburn 4837: my %grouproles = ();
4838: if (keys(%{$allgroups}) > 0) {
1.1064 raeburn 4839: my @groupkeys;
1.1000 raeburn 4840: foreach my $role (keys(%{$allroles})) {
1.1064 raeburn 4841: push(@groupkeys,$role);
4842: }
4843: if (ref($groups_roles) eq 'HASH') {
4844: foreach my $key (keys(%{$groups_roles})) {
4845: unless (grep(/^\Q$key\E$/,@groupkeys)) {
4846: push(@groupkeys,$key);
4847: }
4848: }
4849: }
4850: if (@groupkeys > 0) {
4851: foreach my $role (@groupkeys) {
4852: my ($trole,$area,$sec,$extendedarea);
4853: if ($role =~ m-^(\w+|cr/$match_domain/$match_username/\w+)\.(/$match_domain/$match_courseid)(/?\w*)\.-) {
4854: $trole = $1;
4855: $area = $2;
4856: $sec = $3;
4857: $extendedarea = $area.$sec;
4858: if (exists($$allgroups{$area})) {
4859: foreach my $group (keys(%{$$allgroups{$area}})) {
4860: my $spec = $trole.'.'.$extendedarea;
4861: $grouproles{$spec.'.'.$area.'/'.$group} =
1.681 raeburn 4862: $$allgroups{$area}{$group};
1.1064 raeburn 4863: }
1.678 raeburn 4864: }
4865: }
4866: }
4867: }
4868: }
1.800 albertel 4869: foreach my $group (keys(%grouproles)) {
4870: $$allroles{$group} = $grouproles{$group};
1.678 raeburn 4871: }
1.800 albertel 4872: foreach my $role (keys(%{$allroles})) {
4873: my %thesepriv;
1.941 raeburn 4874: if (($role=~/^au/) || ($role=~/^ca/) || ($role=~/^aa/)) { $author=1; }
1.800 albertel 4875: foreach my $item (split(/:/,$$allroles{$role})) {
4876: if ($item ne '') {
4877: my ($privilege,$restrictions)=split(/&/,$item);
1.567 raeburn 4878: if ($restrictions eq '') {
4879: $thesepriv{$privilege}='F';
4880: } elsif ($thesepriv{$privilege} ne 'F') {
4881: $thesepriv{$privilege}.=$restrictions;
4882: }
4883: if ($thesepriv{'adv'} eq 'F') { $adv=1; }
4884: }
4885: }
4886: my $thesestr='';
1.1104 raeburn 4887: foreach my $priv (sort(keys(%thesepriv))) {
1.800 albertel 4888: $thesestr.=':'.$priv.'&'.$thesepriv{$priv};
4889: }
4890: $userroles->{'user.priv.'.$role} = $thesestr;
1.567 raeburn 4891: }
4892: return ($author,$adv);
4893: }
4894:
1.994 raeburn 4895: sub role_status {
1.1104 raeburn 4896: my ($rolekey,$update,$refresh,$now,$role,$where,$trolecode,$tstatus,$tstart,$tend) = @_;
1.994 raeburn 4897: my @pwhere = ();
4898: if (exists($env{$rolekey}) && $env{$rolekey} ne '') {
4899: (undef,undef,$$role,@pwhere)=split(/\./,$rolekey);
4900: unless (!defined($$role) || $$role eq '') {
4901: $$where=join('.',@pwhere);
4902: $$trolecode=$$role.'.'.$$where;
4903: ($$tstart,$$tend)=split(/\./,$env{$rolekey});
4904: $$tstatus='is';
1.1104 raeburn 4905: if ($$tstart && $$tstart>$update) {
1.994 raeburn 4906: $$tstatus='future';
1.1034 raeburn 4907: if ($$tstart<$now) {
4908: if ($$tstart && $$tstart>$refresh) {
1.1002 raeburn 4909: if (($$where ne '') && ($$role ne '')) {
1.1064 raeburn 4910: my (%allroles,%allgroups,$group_privs,
4911: %groups_roles,@rolecodes);
1.1002 raeburn 4912: my %userroles = (
4913: 'user.role.'.$$role.'.'.$$where => $$tstart.'.'.$$tend
4914: );
1.1064 raeburn 4915: @rolecodes = ('cm');
1.1002 raeburn 4916: my $spec=$$role.'.'.$$where;
4917: my ($tdummy,$tdomain,$trest)=split(/\//,$$where);
4918: if ($$role =~ /^cr\//) {
4919: &custom_roleprivs(\%allroles,$$role,$tdomain,$trest,$spec,$$where);
1.1064 raeburn 4920: push(@rolecodes,'cr');
1.1002 raeburn 4921: } elsif ($$role eq 'gr') {
1.1064 raeburn 4922: push(@rolecodes,$$role);
1.1002 raeburn 4923: my %rolehash = &get('roles',[$$where.'_'.$$role],$env{'user.domain'},
4924: $env{'user.name'});
1.1064 raeburn 4925: my ($trole) = split('_',$rolehash{$$where.'_'.$$role},2);
1.1002 raeburn 4926: (undef,my $group_privs) = split(/\//,$trole);
4927: $group_privs = &unescape($group_privs);
4928: &group_roleprivs(\%allgroups,$$where,$group_privs,$$tend,$$tstart);
1.1064 raeburn 4929: 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 4930: &get_groups_roles($tdomain,$trest,
4931: \%course_roles,\@rolecodes,
4932: \%groups_roles);
1.1002 raeburn 4933: } else {
1.1064 raeburn 4934: push(@rolecodes,$$role);
1.1002 raeburn 4935: &standard_roleprivs(\%allroles,$$role,$tdomain,$spec,$trest,$$where);
4936: }
1.1064 raeburn 4937: my ($author,$adv)= &set_userprivs(\%userroles,\%allroles,\%allgroups,\%groups_roles);
4938: &appenv(\%userroles,\@rolecodes);
1.1002 raeburn 4939: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
4940: }
4941: }
1.1034 raeburn 4942: $$tstatus = 'is';
1.1002 raeburn 4943: }
1.994 raeburn 4944: }
4945: if ($$tend) {
1.1104 raeburn 4946: if ($$tend<$update) {
1.994 raeburn 4947: $$tstatus='expired';
4948: } elsif ($$tend<$now) {
4949: $$tstatus='will_not';
4950: }
4951: }
4952: }
4953: }
4954: }
4955:
1.1104 raeburn 4956: sub get_groups_roles {
4957: my ($cdom,$rest,$cdom_courseroles,$rolecodes,$groups_roles) = @_;
4958: return unless((ref($cdom_courseroles) eq 'HASH') &&
4959: (ref($rolecodes) eq 'ARRAY') &&
4960: (ref($groups_roles) eq 'HASH'));
4961: if (keys(%{$cdom_courseroles}) > 0) {
4962: my ($cnum) = ($rest =~ /^($match_courseid)/);
4963: if ($cdom ne '' && $cnum ne '') {
4964: foreach my $key (keys(%{$cdom_courseroles})) {
4965: if ($key =~ /^\Q$cnum\E:\Q$cdom\E:([^:]+):?([^:]*)/) {
4966: my $crsrole = $1;
4967: my $crssec = $2;
4968: if ($crsrole =~ /^cr/) {
4969: unless (grep(/^cr$/,@{$rolecodes})) {
4970: push(@{$rolecodes},'cr');
4971: }
4972: } else {
4973: unless(grep(/^\Q$crsrole\E$/,@{$rolecodes})) {
4974: push(@{$rolecodes},$crsrole);
4975: }
4976: }
4977: my $rolekey = "$crsrole./$cdom/$cnum";
4978: if ($crssec ne '') {
4979: $rolekey .= "/$crssec";
4980: }
4981: $rolekey .= './';
4982: $groups_roles->{$rolekey} = $rolecodes;
4983: }
4984: }
4985: }
4986: }
4987: return;
4988: }
4989:
4990: sub delete_env_groupprivs {
4991: my ($where,$courseroles,$possroles) = @_;
4992: return unless((ref($courseroles) eq 'HASH') && (ref($possroles) eq 'ARRAY'));
4993: my ($dummy,$udom,$uname,$group) = split(/\//,$where);
4994: unless (ref($courseroles->{$udom}) eq 'HASH') {
4995: %{$courseroles->{$udom}} =
4996: &get_my_roles('','','userroles',['active'],
4997: $possroles,[$udom],1);
4998: }
4999: if (ref($courseroles->{$udom}) eq 'HASH') {
5000: foreach my $item (keys(%{$courseroles->{$udom}})) {
5001: my ($cnum,$cdom,$crsrole,$crssec) = split(/:/,$item);
5002: my $area = '/'.$cdom.'/'.$cnum;
5003: my $privkey = "user.priv.$crsrole.$area";
5004: if ($crssec ne '') {
5005: $privkey .= '/'.$crssec;
5006: }
5007: $privkey .= ".$area/$group";
5008: &Apache::lonnet::delenv($privkey,undef,[$crsrole]);
5009: }
5010: }
5011: return;
5012: }
5013:
1.994 raeburn 5014: sub check_adhoc_privs {
1.1104 raeburn 5015: my ($cdom,$cnum,$update,$refresh,$now,$checkrole,$caller) = @_;
1.994 raeburn 5016: my $cckey = 'user.role.'.$checkrole.'./'.$cdom.'/'.$cnum;
5017: if ($env{$cckey}) {
5018: my ($role,$where,$trolecode,$tstart,$tend,$tremark,$tstatus,$tpstart,$tpend);
1.1104 raeburn 5019: &role_status($cckey,$update,$refresh,$now,\$role,\$where,\$trolecode,\$tstatus,\$tstart,\$tend);
1.994 raeburn 5020: unless (($tstatus eq 'is') || ($tstatus eq 'will_not')) {
1.1088 raeburn 5021: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5022: }
5023: } else {
1.1088 raeburn 5024: &set_adhoc_privileges($cdom,$cnum,$checkrole,$caller);
1.994 raeburn 5025: }
5026: }
5027:
5028: sub set_adhoc_privileges {
5029: # role can be cc or ca
1.1088 raeburn 5030: my ($dcdom,$pickedcourse,$role,$caller) = @_;
1.994 raeburn 5031: my $area = '/'.$dcdom.'/'.$pickedcourse;
5032: my $spec = $role.'.'.$area;
5033: my %userroles = &set_arearole($role,$area,'','',$env{'user.domain'},
5034: $env{'user.name'});
5035: my %ccrole = ();
5036: &standard_roleprivs(\%ccrole,$role,$dcdom,$spec,$pickedcourse,$area);
5037: my ($author,$adv)= &set_userprivs(\%userroles,\%ccrole);
5038: &appenv(\%userroles,[$role,'cm']);
5039: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},"Role ".$role);
1.1088 raeburn 5040: unless ($caller eq 'constructaccess' && $env{'request.course.id'}) {
5041: &appenv( {'request.role' => $spec,
5042: 'request.role.domain' => $dcdom,
5043: 'request.course.sec' => ''
5044: }
5045: );
5046: my $tadv=0;
5047: if (&allowed('adv') eq 'F') { $tadv=1; }
5048: &appenv({'request.role.adv' => $tadv});
5049: }
1.994 raeburn 5050: }
5051:
1.12 www 5052: # --------------------------------------------------------------- get interface
5053:
5054: sub get {
1.131 albertel 5055: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5056: my $items='';
1.800 albertel 5057: foreach my $item (@$storearr) {
5058: $items.=&escape($item).'&';
1.191 harris41 5059: }
1.12 www 5060: $items=~s/\&$//;
1.620 albertel 5061: if (!$udomain) { $udomain=$env{'user.domain'}; }
5062: if (!$uname) { $uname=$env{'user.name'}; }
1.131 albertel 5063: my $uhome=&homeserver($uname,$udomain);
5064:
1.133 albertel 5065: my $rep=&reply("get:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5066: my @pairs=split(/\&/,$rep);
1.273 albertel 5067: if ( $#pairs==0 && $pairs[0] =~ /^(con_lost|error|no_such_host)/i) {
5068: return @pairs;
5069: }
1.15 www 5070: my %returnhash=();
1.42 www 5071: my $i=0;
1.800 albertel 5072: foreach my $item (@$storearr) {
5073: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5074: $i++;
1.191 harris41 5075: }
1.15 www 5076: return %returnhash;
1.27 www 5077: }
5078:
5079: # --------------------------------------------------------------- del interface
5080:
5081: sub del {
1.133 albertel 5082: my ($namespace,$storearr,$udomain,$uname)=@_;
1.27 www 5083: my $items='';
1.800 albertel 5084: foreach my $item (@$storearr) {
5085: $items.=&escape($item).'&';
1.191 harris41 5086: }
1.984 neumanie 5087:
1.27 www 5088: $items=~s/\&$//;
1.620 albertel 5089: if (!$udomain) { $udomain=$env{'user.domain'}; }
5090: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5091: my $uhome=&homeserver($uname,$udomain);
5092: return &reply("del:$udomain:$uname:$namespace:$items",$uhome);
1.15 www 5093: }
5094:
5095: # -------------------------------------------------------------- dump interface
5096:
1.1180 droeschl 5097: sub unserialize {
5098: my ($rep, $escapedkeys) = @_;
5099:
5100: return {} if $rep =~ /^error/;
5101:
5102: my %returnhash=();
5103: foreach my $item (split /\&/, $rep) {
5104: my ($key, $value) = split(/=/, $item, 2);
5105: $key = unescape($key) unless $escapedkeys;
5106: next if $key =~ /^error: 2 /;
5107: $returnhash{$key} = Apache::lonnet::thaw_unescape($value);
5108: }
5109: #return %returnhash;
5110: return \%returnhash;
5111: }
5112:
5113: # see Lond::dump_with_regexp
5114: # if $escapedkeys hash keys won't get unescaped.
1.15 www 5115: sub dump {
1.1180 droeschl 5116: my ($namespace,$udomain,$uname,$regexp,$range,$escapedkeys)=@_;
1.755 albertel 5117: if (!$udomain) { $udomain=$env{'user.domain'}; }
5118: if (!$uname) { $uname=$env{'user.name'}; }
5119: my $uhome=&homeserver($uname,$udomain);
1.1167 droeschl 5120:
1.1180 droeschl 5121: my $reply;
5122: if (grep { $_ eq $uhome } current_machine_ids()) {
5123: # user is hosted on this machine
5124: $reply = LONCAPA::Lond::dump_with_regexp(join(":", ($udomain,
5125: $uname, $namespace, $regexp, $range)), $loncaparevs{$uhome});
5126: return %{unserialize($reply, $escapedkeys)};
5127: }
1.755 albertel 5128: if ($regexp) {
5129: $regexp=&escape($regexp);
5130: } else {
5131: $regexp='.';
5132: }
1.1166 raeburn 5133: my $rep=&reply("dump:$udomain:$uname:$namespace:$regexp:$range",$uhome);
1.755 albertel 5134: my @pairs=split(/\&/,$rep);
5135: my %returnhash=();
1.1098 foxr 5136: if (!($rep =~ /^error/ )) {
5137: foreach my $item (@pairs) {
5138: my ($key,$value)=split(/=/,$item,2);
1.1180 droeschl 5139: $key = unescape($key) unless $escapedkeys;
5140: #$key = &unescape($key);
1.1098 foxr 5141: next if ($key =~ /^error: 2 /);
5142: $returnhash{$key}=&thaw_unescape($value);
5143: }
1.755 albertel 5144: }
5145: return %returnhash;
1.407 www 5146: }
5147:
1.1098 foxr 5148:
1.717 albertel 5149: # --------------------------------------------------------- dumpstore interface
5150:
5151: sub dumpstore {
5152: my ($namespace,$udomain,$uname,$regexp,$range)=@_;
1.1180 droeschl 5153: # same as dump but keys must be escaped. They may contain colon separated
5154: # lists of values that may themself contain colons (e.g. symbs).
5155: return &dump($namespace, $udomain, $uname, $regexp, $range, 1);
1.717 albertel 5156: }
5157:
1.407 www 5158: # -------------------------------------------------------------- keys interface
5159:
5160: sub getkeys {
5161: my ($namespace,$udomain,$uname)=@_;
1.620 albertel 5162: if (!$udomain) { $udomain=$env{'user.domain'}; }
5163: if (!$uname) { $uname=$env{'user.name'}; }
1.407 www 5164: my $uhome=&homeserver($uname,$udomain);
5165: my $rep=reply("keys:$udomain:$uname:$namespace",$uhome);
5166: my @keyarray=();
1.800 albertel 5167: foreach my $key (split(/\&/,$rep)) {
1.812 raeburn 5168: next if ($key =~ /^error: 2 /);
1.800 albertel 5169: push(@keyarray,&unescape($key));
1.407 www 5170: }
5171: return @keyarray;
1.318 matthew 5172: }
5173:
1.319 matthew 5174: # --------------------------------------------------------------- currentdump
5175: sub currentdump {
1.328 matthew 5176: my ($courseid,$sdom,$sname)=@_;
1.620 albertel 5177: $courseid = $env{'request.course.id'} if (! defined($courseid));
5178: $sdom = $env{'user.domain'} if (! defined($sdom));
5179: $sname = $env{'user.name'} if (! defined($sname));
1.326 matthew 5180: my $uhome = &homeserver($sname,$sdom);
1.1180 droeschl 5181: my $rep;
5182:
5183: if (grep { $_ eq $uhome } current_machine_ids()) {
5184: $rep = LONCAPA::Lond::dump_profile_database(join(":", ($sdom, $sname,
5185: $courseid)));
5186: } else {
5187: $rep = reply('currentdump:'.$sdom.':'.$sname.':'.$courseid,$uhome);
5188: }
5189:
1.318 matthew 5190: return if ($rep =~ /^(error:|no_such_host)/);
1.319 matthew 5191: #
1.318 matthew 5192: my %returnhash=();
1.319 matthew 5193: #
5194: if ($rep eq "unknown_cmd") {
5195: # an old lond will not know currentdump
5196: # Do a dump and make it look like a currentdump
1.822 albertel 5197: my @tmp = &dumpstore($courseid,$sdom,$sname,'.');
1.319 matthew 5198: return if ($tmp[0] =~ /^(error:|no_such_host)/);
5199: my %hash = @tmp;
5200: @tmp=();
1.424 matthew 5201: %returnhash = %{&convert_dump_to_currentdump(\%hash)};
1.319 matthew 5202: } else {
5203: my @pairs=split(/\&/,$rep);
1.800 albertel 5204: foreach my $pair (@pairs) {
5205: my ($key,$value)=split(/=/,$pair,2);
1.319 matthew 5206: my ($symb,$param) = split(/:/,$key);
5207: $returnhash{&unescape($symb)}->{&unescape($param)} =
1.557 albertel 5208: &thaw_unescape($value);
1.319 matthew 5209: }
1.191 harris41 5210: }
1.12 www 5211: return %returnhash;
1.424 matthew 5212: }
5213:
5214: sub convert_dump_to_currentdump{
5215: my %hash = %{shift()};
5216: my %returnhash;
5217: # Code ripped from lond, essentially. The only difference
5218: # here is the unescaping done by lonnet::dump(). Conceivably
5219: # we might run in to problems with parameter names =~ /^v\./
5220: while (my ($key,$value) = each(%hash)) {
5221: my ($v,$symb,$param) = split(/:/,$key);
1.822 albertel 5222: $symb = &unescape($symb);
5223: $param = &unescape($param);
1.424 matthew 5224: next if ($v eq 'version' || $symb eq 'keys');
5225: next if (exists($returnhash{$symb}) &&
5226: exists($returnhash{$symb}->{$param}) &&
5227: $returnhash{$symb}->{'v.'.$param} > $v);
5228: $returnhash{$symb}->{$param}=$value;
5229: $returnhash{$symb}->{'v.'.$param}=$v;
5230: }
5231: #
5232: # Remove all of the keys in the hashes which keep track of
5233: # the version of the parameter.
5234: while (my ($symb,$param_hash) = each(%returnhash)) {
5235: # use a foreach because we are going to delete from the hash.
5236: foreach my $key (keys(%$param_hash)) {
5237: delete($param_hash->{$key}) if ($key =~ /^v\./);
5238: }
5239: }
5240: return \%returnhash;
1.12 www 5241: }
5242:
1.627 albertel 5243: # ------------------------------------------------------ critical inc interface
5244:
5245: sub cinc {
5246: return &inc(@_,'critical');
5247: }
5248:
1.449 matthew 5249: # --------------------------------------------------------------- inc interface
5250:
5251: sub inc {
1.627 albertel 5252: my ($namespace,$store,$udomain,$uname,$critical) = @_;
1.620 albertel 5253: if (!$udomain) { $udomain=$env{'user.domain'}; }
5254: if (!$uname) { $uname=$env{'user.name'}; }
1.449 matthew 5255: my $uhome=&homeserver($uname,$udomain);
5256: my $items='';
5257: if (! ref($store)) {
5258: # got a single value, so use that instead
5259: $items = &escape($store).'=&';
5260: } elsif (ref($store) eq 'SCALAR') {
5261: $items = &escape($$store).'=&';
5262: } elsif (ref($store) eq 'ARRAY') {
5263: $items = join('=&',map {&escape($_);} @{$store});
5264: } elsif (ref($store) eq 'HASH') {
5265: while (my($key,$value) = each(%{$store})) {
5266: $items.= &escape($key).'='.&escape($value).'&';
5267: }
5268: }
5269: $items=~s/\&$//;
1.627 albertel 5270: if ($critical) {
5271: return &critical("inc:$udomain:$uname:$namespace:$items",$uhome);
5272: } else {
5273: return &reply("inc:$udomain:$uname:$namespace:$items",$uhome);
5274: }
1.449 matthew 5275: }
5276:
1.12 www 5277: # --------------------------------------------------------------- put interface
5278:
5279: sub put {
1.134 albertel 5280: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5281: if (!$udomain) { $udomain=$env{'user.domain'}; }
5282: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5283: my $uhome=&homeserver($uname,$udomain);
1.12 www 5284: my $items='';
1.800 albertel 5285: foreach my $item (keys(%$storehash)) {
5286: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5287: }
1.12 www 5288: $items=~s/\&$//;
1.134 albertel 5289: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.47 www 5290: }
5291:
1.631 albertel 5292: # ------------------------------------------------------------ newput interface
5293:
5294: sub newput {
5295: my ($namespace,$storehash,$udomain,$uname)=@_;
5296: if (!$udomain) { $udomain=$env{'user.domain'}; }
5297: if (!$uname) { $uname=$env{'user.name'}; }
5298: my $uhome=&homeserver($uname,$udomain);
5299: my $items='';
5300: foreach my $key (keys(%$storehash)) {
5301: $items.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
5302: }
5303: $items=~s/\&$//;
5304: return &reply("newput:$udomain:$uname:$namespace:$items",$uhome);
5305: }
5306:
5307: # --------------------------------------------------------- putstore interface
5308:
1.524 raeburn 5309: sub putstore {
1.715 albertel 5310: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
1.620 albertel 5311: if (!$udomain) { $udomain=$env{'user.domain'}; }
5312: if (!$uname) { $uname=$env{'user.name'}; }
1.524 raeburn 5313: my $uhome=&homeserver($uname,$udomain);
5314: my $items='';
1.715 albertel 5315: foreach my $key (keys(%$storehash)) {
5316: $items.= &escape($key).'='.&freeze_escape($storehash->{$key}).'&';
1.524 raeburn 5317: }
1.715 albertel 5318: $items=~s/\&$//;
1.716 albertel 5319: my $esc_symb=&escape($symb);
5320: my $esc_v=&escape($version);
1.715 albertel 5321: my $reply =
1.716 albertel 5322: &reply("putstore:$udomain:$uname:$namespace:$esc_symb:$esc_v:$items",
1.715 albertel 5323: $uhome);
5324: if ($reply eq 'unknown_cmd') {
1.716 albertel 5325: # gfall back to way things use to be done
1.715 albertel 5326: return &old_putstore($namespace,$symb,$version,$storehash,$udomain,
5327: $uname);
1.524 raeburn 5328: }
1.715 albertel 5329: return $reply;
5330: }
5331:
5332: sub old_putstore {
1.716 albertel 5333: my ($namespace,$symb,$version,$storehash,$udomain,$uname)=@_;
5334: if (!$udomain) { $udomain=$env{'user.domain'}; }
5335: if (!$uname) { $uname=$env{'user.name'}; }
5336: my $uhome=&homeserver($uname,$udomain);
5337: my %newstorehash;
1.800 albertel 5338: foreach my $item (keys(%$storehash)) {
5339: my $key = $version.':'.&escape($symb).':'.$item;
5340: $newstorehash{$key} = $storehash->{$item};
1.716 albertel 5341: }
5342: my $items='';
5343: my %allitems = ();
1.800 albertel 5344: foreach my $item (keys(%newstorehash)) {
5345: if ($item =~ m/^([^\:]+):([^\:]+):([^\:]+)$/) {
1.716 albertel 5346: my $key = $1.':keys:'.$2;
5347: $allitems{$key} .= $3.':';
5348: }
1.800 albertel 5349: $items.=$item.'='.&freeze_escape($newstorehash{$item}).'&';
1.716 albertel 5350: }
1.800 albertel 5351: foreach my $item (keys(%allitems)) {
5352: $allitems{$item} =~ s/\:$//;
5353: $items.= $item.'='.$allitems{$item}.'&';
1.716 albertel 5354: }
5355: $items=~s/\&$//;
5356: return &reply("put:$udomain:$uname:$namespace:$items",$uhome);
1.524 raeburn 5357: }
5358:
1.47 www 5359: # ------------------------------------------------------ critical put interface
5360:
5361: sub cput {
1.134 albertel 5362: my ($namespace,$storehash,$udomain,$uname)=@_;
1.620 albertel 5363: if (!$udomain) { $udomain=$env{'user.domain'}; }
5364: if (!$uname) { $uname=$env{'user.name'}; }
1.134 albertel 5365: my $uhome=&homeserver($uname,$udomain);
1.47 www 5366: my $items='';
1.800 albertel 5367: foreach my $item (keys(%$storehash)) {
5368: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.191 harris41 5369: }
1.47 www 5370: $items=~s/\&$//;
1.134 albertel 5371: return &critical("put:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5372: }
5373:
5374: # -------------------------------------------------------------- eget interface
5375:
5376: sub eget {
1.133 albertel 5377: my ($namespace,$storearr,$udomain,$uname)=@_;
1.12 www 5378: my $items='';
1.800 albertel 5379: foreach my $item (@$storearr) {
5380: $items.=&escape($item).'&';
1.191 harris41 5381: }
1.12 www 5382: $items=~s/\&$//;
1.620 albertel 5383: if (!$udomain) { $udomain=$env{'user.domain'}; }
5384: if (!$uname) { $uname=$env{'user.name'}; }
1.133 albertel 5385: my $uhome=&homeserver($uname,$udomain);
5386: my $rep=&reply("eget:$udomain:$uname:$namespace:$items",$uhome);
1.12 www 5387: my @pairs=split(/\&/,$rep);
5388: my %returnhash=();
1.42 www 5389: my $i=0;
1.800 albertel 5390: foreach my $item (@$storearr) {
5391: $returnhash{$item}=&thaw_unescape($pairs[$i]);
1.42 www 5392: $i++;
1.191 harris41 5393: }
1.12 www 5394: return %returnhash;
5395: }
5396:
1.667 albertel 5397: # ------------------------------------------------------------ tmpput interface
5398: sub tmpput {
1.802 raeburn 5399: my ($storehash,$server,$context)=@_;
1.667 albertel 5400: my $items='';
1.800 albertel 5401: foreach my $item (keys(%$storehash)) {
5402: $items.=&escape($item).'='.&freeze_escape($$storehash{$item}).'&';
1.667 albertel 5403: }
5404: $items=~s/\&$//;
1.802 raeburn 5405: if (defined($context)) {
5406: $items .= ':'.&escape($context);
5407: }
1.667 albertel 5408: return &reply("tmpput:$items",$server);
5409: }
5410:
5411: # ------------------------------------------------------------ tmpget interface
5412: sub tmpget {
1.688 albertel 5413: my ($token,$server)=@_;
5414: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5415: my $rep=&reply("tmpget:$token",$server);
1.667 albertel 5416: my %returnhash;
5417: foreach my $item (split(/\&/,$rep)) {
5418: my ($key,$value)=split(/=/,$item);
1.951 raeburn 5419: next if ($key =~ /^error: 2 /);
1.667 albertel 5420: $returnhash{&unescape($key)}=&thaw_unescape($value);
5421: }
5422: return %returnhash;
5423: }
5424:
1.1113 raeburn 5425: # ------------------------------------------------------------ tmpdel interface
1.688 albertel 5426: sub tmpdel {
5427: my ($token,$server)=@_;
5428: if (!defined($server)) { $server = $perlvar{'lonHostID'}; }
5429: return &reply("tmpdel:$token",$server);
5430: }
5431:
1.765 albertel 5432: # -------------------------------------------------- portfolio access checking
5433:
5434: sub portfolio_access {
1.766 albertel 5435: my ($requrl) = @_;
1.765 albertel 5436: my (undef,$udom,$unum,$file_name,$group) = &parse_portfolio_url($requrl);
5437: my $result = &get_portfolio_access($udom,$unum,$file_name,$group);
1.814 raeburn 5438: if ($result) {
5439: my %setters;
5440: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5441: my ($startblock,$endblock) =
5442: &Apache::loncommon::blockcheck(\%setters,'port',$unum,$udom);
5443: if ($startblock && $endblock) {
5444: return 'B';
5445: }
5446: } else {
5447: my ($startblock,$endblock) =
5448: &Apache::loncommon::blockcheck(\%setters,'port');
5449: if ($startblock && $endblock) {
5450: return 'B';
5451: }
5452: }
5453: }
1.765 albertel 5454: if ($result eq 'ok') {
1.766 albertel 5455: return 'F';
1.765 albertel 5456: } elsif ($result =~ /^[^:]+:guest_/) {
1.766 albertel 5457: return 'A';
1.765 albertel 5458: }
1.766 albertel 5459: return '';
1.765 albertel 5460: }
5461:
5462: sub get_portfolio_access {
1.767 albertel 5463: my ($udom,$unum,$file_name,$group,$access_hash) = @_;
5464:
5465: if (!ref($access_hash)) {
5466: my $current_perms = &get_portfile_permissions($udom,$unum);
5467: my %access_controls = &get_access_controls($current_perms,$group,
5468: $file_name);
5469: $access_hash = $access_controls{$file_name};
5470: }
5471:
1.765 albertel 5472: my ($public,$guest,@domains,@users,@courses,@groups);
5473: my $now = time;
5474: if (ref($access_hash) eq 'HASH') {
5475: foreach my $key (keys(%{$access_hash})) {
5476: my ($num,$scope,$end,$start) = ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
5477: if ($start > $now) {
5478: next;
5479: }
5480: if ($end && $end<$now) {
5481: next;
5482: }
5483: if ($scope eq 'public') {
5484: $public = $key;
5485: last;
5486: } elsif ($scope eq 'guest') {
5487: $guest = $key;
5488: } elsif ($scope eq 'domains') {
5489: push(@domains,$key);
5490: } elsif ($scope eq 'users') {
5491: push(@users,$key);
5492: } elsif ($scope eq 'course') {
5493: push(@courses,$key);
5494: } elsif ($scope eq 'group') {
5495: push(@groups,$key);
5496: }
5497: }
5498: if ($public) {
5499: return 'ok';
5500: }
5501: if ($env{'user.name'} eq 'public' && $env{'user.domain'} eq 'public') {
5502: if ($guest) {
5503: return $guest;
5504: }
5505: } else {
5506: if (@domains > 0) {
5507: foreach my $domkey (@domains) {
5508: if (ref($access_hash->{$domkey}{'dom'}) eq 'ARRAY') {
5509: if (grep(/^\Q$env{'user.domain'}\E$/,@{$access_hash->{$domkey}{'dom'}})) {
5510: return 'ok';
5511: }
5512: }
5513: }
5514: }
5515: if (@users > 0) {
5516: foreach my $userkey (@users) {
1.865 raeburn 5517: if (ref($access_hash->{$userkey}{'users'}) eq 'ARRAY') {
5518: foreach my $item (@{$access_hash->{$userkey}{'users'}}) {
5519: if (ref($item) eq 'HASH') {
5520: if (($item->{'uname'} eq $env{'user.name'}) &&
5521: ($item->{'udom'} eq $env{'user.domain'})) {
5522: return 'ok';
5523: }
5524: }
5525: }
5526: }
1.765 albertel 5527: }
5528: }
5529: my %roleshash;
5530: my @courses_and_groups = @courses;
5531: push(@courses_and_groups,@groups);
5532: if (@courses_and_groups > 0) {
5533: my (%allgroups,%allroles);
5534: my ($start,$end,$role,$sec,$group);
5535: foreach my $envkey (%env) {
1.1060 raeburn 5536: if ($envkey =~ m-^user\.role\.(gr|cc|co|in|ta|ep|ad|st)\./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5537: my $cid = $2.'_'.$3;
5538: if ($1 eq 'gr') {
5539: $group = $4;
5540: $allgroups{$cid}{$group} = $env{$envkey};
5541: } else {
5542: if ($4 eq '') {
5543: $sec = 'none';
5544: } else {
5545: $sec = $4;
5546: }
5547: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5548: }
1.811 albertel 5549: } elsif ($envkey =~ m-^user\.role\./cr/($match_domain/$match_username/\w*)./($match_domain)/($match_courseid)/?([^/]*)$-) {
1.765 albertel 5550: my $cid = $2.'_'.$3;
5551: if ($4 eq '') {
5552: $sec = 'none';
5553: } else {
5554: $sec = $4;
5555: }
5556: $allroles{$cid}{$1}{$sec} = $env{$envkey};
5557: }
5558: }
5559: if (keys(%allroles) == 0) {
5560: return;
5561: }
5562: foreach my $key (@courses_and_groups) {
5563: my %content = %{$$access_hash{$key}};
5564: my $cnum = $content{'number'};
5565: my $cdom = $content{'domain'};
5566: my $cid = $cdom.'_'.$cnum;
5567: if (!exists($allroles{$cid})) {
5568: next;
5569: }
5570: foreach my $role_id (keys(%{$content{'roles'}})) {
5571: my @sections = @{$content{'roles'}{$role_id}{'section'}};
5572: my @groups = @{$content{'roles'}{$role_id}{'group'}};
5573: my @status = @{$content{'roles'}{$role_id}{'access'}};
5574: my @roles = @{$content{'roles'}{$role_id}{'role'}};
5575: foreach my $role (keys(%{$allroles{$cid}})) {
5576: if ((grep/^all$/,@roles) || (grep/^\Q$role\E$/,@roles)) {
5577: foreach my $sec (keys(%{$allroles{$cid}{$role}})) {
5578: if (&course_group_datechecker($allroles{$cid}{$role}{$sec},$now,\@status) eq 'ok') {
5579: if (grep/^all$/,@sections) {
5580: return 'ok';
5581: } else {
5582: if (grep/^$sec$/,@sections) {
5583: return 'ok';
5584: }
5585: }
5586: }
5587: }
5588: if (keys(%{$allgroups{$cid}}) == 0) {
5589: if (grep/^none$/,@groups) {
5590: return 'ok';
5591: }
5592: } else {
5593: if (grep/^all$/,@groups) {
5594: return 'ok';
5595: }
5596: foreach my $group (keys(%{$allgroups{$cid}})) {
5597: if (grep/^$group$/,@groups) {
5598: return 'ok';
5599: }
5600: }
5601: }
5602: }
5603: }
5604: }
5605: }
5606: }
5607: if ($guest) {
5608: return $guest;
5609: }
5610: }
5611: }
5612: return;
5613: }
5614:
5615: sub course_group_datechecker {
5616: my ($dates,$now,$status) = @_;
5617: my ($start,$end) = split(/\./,$dates);
5618: if (!$start && !$end) {
5619: return 'ok';
5620: }
5621: if (grep/^active$/,@{$status}) {
5622: if (((!$start) || ($start && $start <= $now)) && ((!$end) || ($end && $end >= $now))) {
5623: return 'ok';
5624: }
5625: }
5626: if (grep/^previous$/,@{$status}) {
5627: if ($end > $now ) {
5628: return 'ok';
5629: }
5630: }
5631: if (grep/^future$/,@{$status}) {
5632: if ($start > $now) {
5633: return 'ok';
5634: }
5635: }
5636: return;
5637: }
5638:
5639: sub parse_portfolio_url {
5640: my ($url) = @_;
5641:
5642: my ($type,$udom,$unum,$group,$file_name);
5643:
1.823 albertel 5644: if ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_username)/portfolio(/.+)$-) {
1.765 albertel 5645: $type = 1;
5646: $udom = $1;
5647: $unum = $2;
5648: $file_name = $3;
1.823 albertel 5649: } elsif ($url =~ m-^/*(?:uploaded|editupload)/($match_domain)/($match_courseid)/groups/([^/]+)/portfolio/(.+)$-) {
1.765 albertel 5650: $type = 2;
5651: $udom = $1;
5652: $unum = $2;
5653: $group = $3;
5654: $file_name = $3.'/'.$4;
5655: }
5656: if (wantarray) {
5657: return ($type,$udom,$unum,$file_name,$group);
5658: }
5659: return $type;
5660: }
5661:
5662: sub is_portfolio_url {
5663: my ($url) = @_;
5664: return scalar(&parse_portfolio_url($url));
5665: }
5666:
1.798 raeburn 5667: sub is_portfolio_file {
5668: my ($file) = @_;
1.820 raeburn 5669: if (($file =~ /^portfolio/) || ($file =~ /^groups\/\w+\/portfolio/)) {
1.798 raeburn 5670: return 1;
5671: }
5672: return;
5673: }
5674:
1.976 raeburn 5675: sub usertools_access {
1.1084 raeburn 5676: my ($uname,$udom,$tool,$action,$context,$userenvref,$domdefref,$is_advref)=@_;
1.985 raeburn 5677: my ($access,%tools);
5678: if ($context eq '') {
5679: $context = 'tools';
5680: }
5681: if ($context eq 'requestcourses') {
5682: %tools = (
5683: official => 1,
5684: unofficial => 1,
1.1006 raeburn 5685: community => 1,
1.985 raeburn 5686: );
1.1183 ! raeburn 5687: } elsif ($context eq 'requestauthor') {
! 5688: %tools = (
! 5689: requestauthor => 1,
! 5690: );
1.985 raeburn 5691: } else {
5692: %tools = (
5693: aboutme => 1,
5694: blog => 1,
1.1177 raeburn 5695: webdav => 1,
1.985 raeburn 5696: portfolio => 1,
5697: );
5698: }
1.976 raeburn 5699: return if (!defined($tools{$tool}));
5700:
5701: if ((!defined($udom)) || (!defined($uname))) {
5702: $udom = $env{'user.domain'};
5703: $uname = $env{'user.name'};
5704: }
5705:
1.978 raeburn 5706: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
5707: if ($action ne 'reload') {
1.985 raeburn 5708: if ($context eq 'requestcourses') {
5709: return $env{'environment.canrequest.'.$tool};
1.1183 ! raeburn 5710: } elsif ($context eq 'requestauthor') {
! 5711: return $env{'environment.canrequest.author'};
1.985 raeburn 5712: } else {
5713: return $env{'environment.availabletools.'.$tool};
5714: }
5715: }
1.976 raeburn 5716: }
5717:
1.1183 ! raeburn 5718: my ($toolstatus,$inststatus,$envkey);
! 5719: if ($context eq 'requestauthor') {
! 5720: $envkey = $context;
! 5721: } else {
! 5722: $envkey = $context.'.'.$tool;
! 5723: }
1.976 raeburn 5724:
1.985 raeburn 5725: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
5726: ($action ne 'reload')) {
1.1183 ! raeburn 5727: $toolstatus = $env{'environment.'.$envkey};
1.976 raeburn 5728: $inststatus = $env{'environment.inststatus'};
5729: } else {
1.1084 raeburn 5730: if (ref($userenvref) eq 'HASH') {
1.1183 ! raeburn 5731: $toolstatus = $userenvref->{$envkey};
1.1084 raeburn 5732: $inststatus = $userenvref->{'inststatus'};
5733: } else {
1.1183 ! raeburn 5734: my %userenv = &userenvironment($udom,$uname,$envkey,'inststatus');
! 5735: $toolstatus = $userenv{$envkey};
1.1084 raeburn 5736: $inststatus = $userenv{'inststatus'};
5737: }
1.976 raeburn 5738: }
5739:
5740: if ($toolstatus ne '') {
5741: if ($toolstatus) {
5742: $access = 1;
5743: } else {
5744: $access = 0;
5745: }
5746: return $access;
5747: }
5748:
1.1084 raeburn 5749: my ($is_adv,%domdef);
5750: if (ref($is_advref) eq 'HASH') {
5751: $is_adv = $is_advref->{'is_adv'};
5752: } else {
5753: $is_adv = &is_advanced_user($udom,$uname);
5754: }
5755: if (ref($domdefref) eq 'HASH') {
5756: %domdef = %{$domdefref};
5757: } else {
5758: %domdef = &get_domain_defaults($udom);
5759: }
1.976 raeburn 5760: if (ref($domdef{$tool}) eq 'HASH') {
5761: if ($is_adv) {
5762: if ($domdef{$tool}{'_LC_adv'} ne '') {
5763: if ($domdef{$tool}{'_LC_adv'}) {
5764: $access = 1;
5765: } else {
5766: $access = 0;
5767: }
5768: return $access;
5769: }
5770: }
5771: if ($inststatus ne '') {
5772: my ($hasaccess,$hasnoaccess);
5773: foreach my $affiliation (split(/:/,$inststatus)) {
5774: if ($domdef{$tool}{$affiliation} ne '') {
5775: if ($domdef{$tool}{$affiliation}) {
5776: $hasaccess = 1;
5777: } else {
5778: $hasnoaccess = 1;
5779: }
5780: }
5781: }
5782: if ($hasaccess || $hasnoaccess) {
5783: if ($hasaccess) {
5784: $access = 1;
5785: } elsif ($hasnoaccess) {
5786: $access = 0;
5787: }
5788: return $access;
5789: }
5790: } else {
5791: if ($domdef{$tool}{'default'} ne '') {
5792: if ($domdef{$tool}{'default'}) {
5793: $access = 1;
5794: } elsif ($domdef{$tool}{'default'} == 0) {
5795: $access = 0;
5796: }
5797: return $access;
5798: }
5799: }
5800: } else {
1.1177 raeburn 5801: if (($context eq 'tools') && ($tool ne 'webdav')) {
1.985 raeburn 5802: $access = 1;
5803: } else {
5804: $access = 0;
5805: }
1.976 raeburn 5806: return $access;
5807: }
5808: }
5809:
1.1050 raeburn 5810: sub is_course_owner {
5811: my ($cdom,$cnum,$udom,$uname) = @_;
5812: if (($udom eq '') || ($uname eq '')) {
5813: $udom = $env{'user.domain'};
5814: $uname = $env{'user.name'};
5815: }
5816: unless (($udom eq '') || ($uname eq '')) {
5817: if (exists($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'})) {
5818: if ($env{'course.'.$cdom.'_'.$cnum.'.internal.courseowner'} eq $uname.':'.$udom) {
5819: return 1;
5820: } else {
5821: my %courseinfo = &Apache::lonnet::coursedescription($cdom.'/'.$cnum);
5822: if ($courseinfo{'internal.courseowner'} eq $uname.':'.$udom) {
5823: return 1;
5824: }
5825: }
5826: }
5827: }
5828: return;
5829: }
5830:
1.976 raeburn 5831: sub is_advanced_user {
5832: my ($udom,$uname) = @_;
1.1085 raeburn 5833: if ($udom ne '' && $uname ne '') {
5834: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.1128 raeburn 5835: if (wantarray) {
5836: return ($env{'user.adv'},$env{'user.author'});
5837: } else {
5838: return $env{'user.adv'};
5839: }
1.1085 raeburn 5840: }
5841: }
1.976 raeburn 5842: my %roleshash = &get_my_roles($uname,$udom,'userroles',undef,undef,undef,1);
5843: my %allroles;
1.1128 raeburn 5844: my ($is_adv,$is_author);
1.976 raeburn 5845: foreach my $role (keys(%roleshash)) {
5846: my ($trest,$tdomain,$trole,$sec) = split(/:/,$role);
5847: my $area = '/'.$tdomain.'/'.$trest;
5848: if ($sec ne '') {
5849: $area .= '/'.$sec;
5850: }
5851: if (($area ne '') && ($trole ne '')) {
5852: my $spec=$trole.'.'.$area;
5853: if ($trole =~ /^cr\//) {
5854: &custom_roleprivs(\%allroles,$trole,$tdomain,$trest,$spec,$area);
5855: } elsif ($trole ne 'gr') {
5856: &standard_roleprivs(\%allroles,$trole,$tdomain,$spec,$trest,$area);
5857: }
1.1128 raeburn 5858: if ($trole eq 'au') {
5859: $is_author = 1;
5860: }
1.976 raeburn 5861: }
5862: }
5863: foreach my $role (keys(%allroles)) {
5864: last if ($is_adv);
5865: foreach my $item (split(/:/,$allroles{$role})) {
5866: if ($item ne '') {
5867: my ($privilege,$restrictions)=split(/&/,$item);
5868: if ($privilege eq 'adv') {
5869: $is_adv = 1;
5870: last;
5871: }
5872: }
5873: }
5874: }
1.1128 raeburn 5875: if (wantarray) {
5876: return ($is_adv,$is_author);
5877: }
1.976 raeburn 5878: return $is_adv;
5879: }
1.798 raeburn 5880:
1.1035 raeburn 5881: sub check_can_request {
1.1036 raeburn 5882: my ($dom,$can_request,$request_domains) = @_;
1.1035 raeburn 5883: my $canreq = 0;
5884: my ($types,$typename) = &Apache::loncommon::course_types();
5885: my @options = ('approval','validate','autolimit');
5886: my $optregex = join('|',@options);
5887: if ((ref($can_request) eq 'HASH') && (ref($types) eq 'ARRAY')) {
5888: foreach my $type (@{$types}) {
5889: if (&usertools_access($env{'user.name'},
5890: $env{'user.domain'},
5891: $type,undef,'requestcourses')) {
5892: $canreq ++;
1.1036 raeburn 5893: if (ref($request_domains) eq 'HASH') {
5894: push(@{$request_domains->{$type}},$env{'user.domain'});
5895: }
1.1035 raeburn 5896: if ($dom eq $env{'user.domain'}) {
5897: $can_request->{$type} = 1;
5898: }
5899: }
5900: if ($env{'environment.reqcrsotherdom.'.$type} ne '') {
5901: my @curr = split(',',$env{'environment.reqcrsotherdom.'.$type});
5902: if (@curr > 0) {
1.1036 raeburn 5903: foreach my $item (@curr) {
5904: if (ref($request_domains) eq 'HASH') {
5905: my ($otherdom) = ($item =~ /^($match_domain):($optregex)(=?\d*)$/);
5906: if ($otherdom ne '') {
5907: if (ref($request_domains->{$type}) eq 'ARRAY') {
5908: unless (grep(/^\Q$otherdom\E$/,@{$request_domains->{$type}})) {
5909: push(@{$request_domains->{$type}},$otherdom);
5910: }
5911: } else {
5912: push(@{$request_domains->{$type}},$otherdom);
5913: }
5914: }
5915: }
5916: }
5917: unless($dom eq $env{'user.domain'}) {
5918: $canreq ++;
1.1035 raeburn 5919: if (grep(/^\Q$dom\E:($optregex)(=?\d*)$/,@curr)) {
5920: $can_request->{$type} = 1;
5921: }
5922: }
5923: }
5924: }
5925: }
5926: }
5927: return $canreq;
5928: }
5929:
1.341 www 5930: # ---------------------------------------------- Custom access rule evaluation
5931:
5932: sub customaccess {
5933: my ($priv,$uri)=@_;
1.807 albertel 5934: my ($urole,$urealm)=split(/\./,$env{'request.role'},2);
1.819 www 5935: my (undef,$udom,$ucrs,$usec)=split(/\//,$urealm);
1.807 albertel 5936: $udom = &LONCAPA::clean_domain($udom);
5937: $ucrs = &LONCAPA::clean_username($ucrs);
1.341 www 5938: my $access=0;
1.800 albertel 5939: foreach my $right (split(/\s*\,\s*/,&metadata($uri,'rule_rights'))) {
1.893 albertel 5940: my ($effect,$realm,$role,$type)=split(/\:/,$right);
5941: if ($type eq 'user') {
5942: foreach my $scope (split(/\s*\,\s*/,$realm)) {
1.896 albertel 5943: my ($tdom,$tuname)=split(m{/},$scope);
1.893 albertel 5944: if ($tdom) {
5945: if ($tdom ne $env{'user.domain'}) { next; }
5946: }
1.896 albertel 5947: if ($tuname) {
5948: if ($tuname ne $env{'user.name'}) { next; }
1.893 albertel 5949: }
5950: $access=($effect eq 'allow');
5951: last;
5952: }
5953: } else {
5954: if ($role) {
5955: if ($role ne $urole) { next; }
5956: }
5957: foreach my $scope (split(/\s*\,\s*/,$realm)) {
5958: my ($tdom,$tcrs,$tsec)=split(/\_/,$scope);
5959: if ($tdom) {
5960: if ($tdom ne $udom) { next; }
5961: }
5962: if ($tcrs) {
5963: if ($tcrs ne $ucrs) { next; }
5964: }
5965: if ($tsec) {
5966: if ($tsec ne $usec) { next; }
5967: }
5968: $access=($effect eq 'allow');
5969: last;
5970: }
5971: if ($realm eq '' && $role eq '') {
5972: $access=($effect eq 'allow');
5973: }
1.402 bowersj2 5974: }
1.341 www 5975: }
5976: return $access;
5977: }
5978:
1.103 harris41 5979: # ------------------------------------------------- Check for a user privilege
1.12 www 5980:
5981: sub allowed {
1.810 raeburn 5982: my ($priv,$uri,$symb,$role)=@_;
1.705 albertel 5983: my $ver_orguri=$uri;
1.439 www 5984: $uri=&deversion($uri);
1.152 www 5985: my $orguri=$uri;
1.52 www 5986: $uri=&declutter($uri);
1.809 raeburn 5987:
1.810 raeburn 5988: if ($priv eq 'evb') {
5989: # Evade communication block restrictions for specified role in a course
5990: if ($env{'user.priv.'.$role} =~/evb\&([^\:]*)/) {
5991: return $1;
5992: } else {
5993: return;
5994: }
5995: }
5996:
1.620 albertel 5997: if (defined($env{'allowed.'.$priv})) { return $env{'allowed.'.$priv}; }
1.54 www 5998: # Free bre access to adm and meta resources
1.775 albertel 5999: if (((($uri=~/^adm\//) && ($uri !~ m{/(?:smppg|bulletinboard)$}))
1.769 albertel 6000: || (($uri=~/\.meta$/) && ($uri!~m|^uploaded/|) ))
6001: && ($priv eq 'bre')) {
1.14 www 6002: return 'F';
1.159 www 6003: }
6004:
1.545 banghart 6005: # Free bre access to user's own portfolio contents
1.714 raeburn 6006: my ($space,$domain,$name,@dir)=split('/',$uri);
1.647 raeburn 6007: if (($space=~/^(uploaded|editupload)$/) && ($env{'user.name'} eq $name) &&
1.714 raeburn 6008: ($env{'user.domain'} eq $domain) && ('portfolio' eq $dir[0])) {
1.814 raeburn 6009: my %setters;
6010: my ($startblock,$endblock) =
6011: &Apache::loncommon::blockcheck(\%setters,'port');
6012: if ($startblock && $endblock) {
6013: return 'B';
6014: } else {
6015: return 'F';
6016: }
1.545 banghart 6017: }
6018:
1.762 raeburn 6019: # bre access to group portfolio for rgf priv in group, or mdg or vcg in course.
1.714 raeburn 6020: if (($space=~/^(uploaded|editupload)$/) && ($dir[0] eq 'groups')
6021: && ($dir[2] eq 'portfolio') && ($priv eq 'bre')) {
6022: if (exists($env{'request.course.id'})) {
6023: my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6024: my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6025: if (($domain eq $cdom) && ($name eq $cnum)) {
6026: my $courseprivid=$env{'request.course.id'};
6027: $courseprivid=~s/\_/\//;
6028: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid
6029: .'/'.$dir[1]} =~/rgf\&([^\:]*)/) {
6030: return $1;
1.762 raeburn 6031: } else {
6032: if ($env{'request.course.sec'}) {
6033: $courseprivid.='/'.$env{'request.course.sec'};
6034: }
6035: if ($env{'user.priv.'.$env{'request.role'}.'./'.
6036: $courseprivid} =~/(mdg|vcg)\&([^\:]*)/) {
6037: return $2;
6038: }
1.714 raeburn 6039: }
6040: }
6041: }
6042: }
6043:
1.159 www 6044: # Free bre to public access
6045:
6046: if ($priv eq 'bre') {
1.238 www 6047: my $copyright=&metadata($uri,'copyright');
1.620 albertel 6048: if (($copyright eq 'public') && (!$env{'request.course.id'})) {
1.301 www 6049: return 'F';
6050: }
1.238 www 6051: if ($copyright eq 'priv') {
6052: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6053: unless (($env{'user.name'} eq $2) && ($env{'user.domain'} eq $1)) {
1.238 www 6054: return '';
6055: }
6056: }
6057: if ($copyright eq 'domain') {
6058: $uri=~/([^\/]+)\/([^\/]+)\//;
1.620 albertel 6059: unless (($env{'user.domain'} eq $1) ||
6060: ($env{'course.'.$env{'request.course.id'}.'.domain'} eq $1)) {
1.238 www 6061: return '';
6062: }
1.262 matthew 6063: }
1.620 albertel 6064: if ($env{'request.role'}=~ /li\.\//) {
1.262 matthew 6065: # Library role, so allow browsing of resources in this domain.
6066: return 'F';
1.238 www 6067: }
1.341 www 6068: if ($copyright eq 'custom') {
6069: unless (&customaccess($priv,$uri)) { return ''; }
6070: }
1.14 www 6071: }
1.264 matthew 6072: # Domain coordinator is trying to create a course
1.620 albertel 6073: if (($priv eq 'ccc') && ($env{'request.role'} =~ /^dc\./)) {
1.264 matthew 6074: # uri is the requested domain in this case.
6075: # comparison to 'request.role.domain' shows if the user has selected
1.678 raeburn 6076: # a role of dc for the domain in question.
1.620 albertel 6077: return 'F' if ($uri eq $env{'request.role.domain'});
1.264 matthew 6078: }
1.29 www 6079:
1.52 www 6080: my $thisallowed='';
6081: my $statecond=0;
6082: my $courseprivid='';
6083:
1.1039 raeburn 6084: my $ownaccess;
1.1043 raeburn 6085: # Community Coordinator or Assistant Co-author browsing resource space.
1.1039 raeburn 6086: if (($priv eq 'bro') && ($env{'user.author'})) {
6087: if ($uri eq '') {
6088: $ownaccess = 1;
6089: } else {
6090: if (($env{'user.domain'} ne '') && ($env{'user.name'} ne '')) {
6091: my $udom = $env{'user.domain'};
6092: my $uname = $env{'user.name'};
6093: if ($uri =~ m{^\Q$udom\E/?$}) {
6094: $ownaccess = 1;
1.1040 raeburn 6095: } elsif ($uri =~ m{^\Q$udom\E/\Q$uname\E/?}) {
1.1039 raeburn 6096: unless ($uri =~ m{\.\./}) {
6097: $ownaccess = 1;
6098: }
6099: } elsif (($udom ne 'public') && ($uname ne 'public')) {
6100: my $now = time;
6101: if ($uri =~ m{^([^/]+)/?$}) {
6102: my $adom = $1;
6103: foreach my $key (keys(%env)) {
1.1042 raeburn 6104: if ($key =~ m{^user\.role\.(ca|aa)/\Q$adom\E}) {
1.1039 raeburn 6105: my ($start,$end) = split('.',$env{$key});
6106: if (($now >= $start) && (!$end || $end < $now)) {
6107: $ownaccess = 1;
6108: last;
6109: }
6110: }
6111: }
6112: } elsif ($uri =~ m{^([^/]+)/([^/]+)/?}) {
6113: my $adom = $1;
6114: my $aname = $2;
1.1042 raeburn 6115: foreach my $role ('ca','aa') {
6116: if ($env{"user.role.$role./$adom/$aname"}) {
6117: my ($start,$end) =
6118: split('.',$env{"user.role.$role./$adom/$aname"});
6119: if (($now >= $start) && (!$end || $end < $now)) {
6120: $ownaccess = 1;
6121: last;
6122: }
1.1039 raeburn 6123: }
6124: }
6125: }
6126: }
6127: }
6128: }
6129: }
6130:
1.52 www 6131: # Course
6132:
1.620 albertel 6133: if ($env{'user.priv.'.$env{'request.role'}.'./'}=~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6134: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6135: $thisallowed.=$1;
6136: }
1.52 www 6137: }
1.29 www 6138:
1.52 www 6139: # Domain
6140:
1.620 albertel 6141: if ($env{'user.priv.'.$env{'request.role'}.'./'.(split(/\//,$uri))[0].'/'}
1.479 albertel 6142: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6143: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6144: $thisallowed.=$1;
6145: }
1.12 www 6146: }
1.52 www 6147:
1.1141 raeburn 6148: # User who is not author or co-author might still be able to edit
6149: # resource of an author in the domain (e.g., if Domain Coordinator).
6150: if (($priv eq 'eco') && ($thisallowed eq '') && ($env{'request.course.id'}) &&
6151: (&allowed('mdc',$env{'request.course.id'}))) {
6152: if ($env{"user.priv.cm./$uri/"}=~/\Q$priv\E\&([^\:]*)/) {
6153: $thisallowed.=$1;
6154: }
6155: }
6156:
1.52 www 6157: # Course: uri itself is a course
1.66 www 6158: my $courseuri=$uri;
6159: $courseuri=~s/\_(\d)/\/$1/;
1.83 www 6160: $courseuri=~s/^([^\/])/\/$1/;
1.81 www 6161:
1.620 albertel 6162: if ($env{'user.priv.'.$env{'request.role'}.'.'.$courseuri}
1.479 albertel 6163: =~/\Q$priv\E\&([^\:]*)/) {
1.1043 raeburn 6164: unless (($priv eq 'bro') && (!$ownaccess)) {
1.1039 raeburn 6165: $thisallowed.=$1;
6166: }
1.12 www 6167: }
1.29 www 6168:
1.665 albertel 6169: # URI is an uploaded document for this course, default permissions don't matter
1.611 albertel 6170: # not allowing 'edit' access (editupload) to uploaded course docs
1.492 albertel 6171: if (($priv eq 'bre') && ($uri=~m|^uploaded/|)) {
1.665 albertel 6172: $thisallowed='';
1.671 raeburn 6173: my ($match)=&is_on_map($uri);
6174: if ($match) {
6175: if ($env{'user.priv.'.$env{'request.role'}.'./'}
6176: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6177: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6178: if (@blockers > 0) {
6179: $thisallowed = 'B';
6180: } else {
6181: $thisallowed.=$1;
6182: }
1.671 raeburn 6183: }
6184: } else {
1.705 albertel 6185: my $refuri = $env{'httpref.'.$orguri} || $env{'httpref.'.$ver_orguri};
1.671 raeburn 6186: if ($refuri) {
6187: if ($refuri =~ m|^/adm/|) {
1.669 raeburn 6188: $thisallowed='F';
1.671 raeburn 6189: } else {
6190: $refuri=&declutter($refuri);
6191: my ($match) = &is_on_map($refuri);
6192: if ($match) {
1.1162 raeburn 6193: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6194: if (@blockers > 0) {
6195: $thisallowed = 'B';
6196: } else {
6197: $thisallowed='F';
6198: }
1.671 raeburn 6199: }
1.669 raeburn 6200: }
1.671 raeburn 6201: }
6202: }
1.314 www 6203: }
1.492 albertel 6204:
1.766 albertel 6205: if ($priv eq 'bre'
6206: && $thisallowed ne 'F'
6207: && $thisallowed ne '2'
6208: && &is_portfolio_url($uri)) {
6209: $thisallowed = &portfolio_access($uri);
6210: }
6211:
1.52 www 6212: # Full access at system, domain or course-wide level? Exit.
1.29 www 6213: if ($thisallowed=~/F/) {
6214: return 'F';
6215: }
6216:
1.52 www 6217: # If this is generating or modifying users, exit with special codes
1.29 www 6218:
1.643 www 6219: if (':csu:cdc:ccc:cin:cta:cep:ccr:cst:cad:cli:cau:cdg:cca:caa:'=~/\:\Q$priv\E\:/) {
6220: if (($priv eq 'cca') || ($priv eq 'caa')) {
1.642 albertel 6221: my ($audom,$auname)=split('/',$uri);
1.643 www 6222: # no author name given, so this just checks on the general right to make a co-author in this domain
6223: unless ($auname) { return $thisallowed; }
6224: # an author name is given, so we are about to actually make a co-author for a certain account
1.642 albertel 6225: if (($auname ne $env{'user.name'} && $env{'request.role'} !~ /^dc\./) ||
6226: (($audom ne $env{'user.domain'} && $env{'request.role'} !~ /^dc\./) &&
6227: ($audom ne $env{'request.role.domain'}))) { return ''; }
6228: }
1.52 www 6229: return $thisallowed;
6230: }
6231: #
1.103 harris41 6232: # Gathered so far: system, domain and course wide privileges
1.52 www 6233: #
6234: # Course: See if uri or referer is an individual resource that is part of
6235: # the course
6236:
1.620 albertel 6237: if ($env{'request.course.id'}) {
1.232 www 6238:
1.620 albertel 6239: $courseprivid=$env{'request.course.id'};
6240: if ($env{'request.course.sec'}) {
6241: $courseprivid.='/'.$env{'request.course.sec'};
1.52 www 6242: }
6243: $courseprivid=~s/\_/\//;
6244: my $checkreferer=1;
1.232 www 6245: my ($match,$cond)=&is_on_map($uri);
6246: if ($match) {
6247: $statecond=$cond;
1.620 albertel 6248: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6249: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6250: my $value = $1;
6251: if ($priv eq 'bre') {
6252: my @blockers = &has_comm_blocking($priv,$symb,$uri);
6253: if (@blockers > 0) {
6254: $thisallowed = 'B';
6255: } else {
6256: $thisallowed.=$value;
6257: }
6258: } else {
6259: $thisallowed.=$value;
6260: }
1.52 www 6261: $checkreferer=0;
6262: }
1.29 www 6263: }
1.83 www 6264:
1.148 www 6265: if ($checkreferer) {
1.620 albertel 6266: my $refuri=$env{'httpref.'.$orguri};
1.148 www 6267: unless ($refuri) {
1.800 albertel 6268: foreach my $key (keys(%env)) {
6269: if ($key=~/^httpref\..*\*/) {
6270: my $pattern=$key;
1.156 www 6271: $pattern=~s/^httpref\.\/res\///;
1.148 www 6272: $pattern=~s/\*/\[\^\/\]\+/g;
6273: $pattern=~s/\//\\\//g;
1.152 www 6274: if ($orguri=~/$pattern/) {
1.800 albertel 6275: $refuri=$env{$key};
1.148 www 6276: }
6277: }
1.191 harris41 6278: }
1.148 www 6279: }
1.232 www 6280:
1.148 www 6281: if ($refuri) {
1.152 www 6282: $refuri=&declutter($refuri);
1.232 www 6283: my ($match,$cond)=&is_on_map($refuri);
6284: if ($match) {
6285: my $refstatecond=$cond;
1.620 albertel 6286: if ($env{'user.priv.'.$env{'request.role'}.'./'.$courseprivid}
1.479 albertel 6287: =~/\Q$priv\E\&([^\:]*)/) {
1.1162 raeburn 6288: my $value = $1;
6289: if ($priv eq 'bre') {
6290: my @blockers = &has_comm_blocking($priv,$symb,$refuri);
6291: if (@blockers > 0) {
6292: $thisallowed = 'B';
6293: } else {
6294: $thisallowed.=$value;
6295: }
6296: } else {
6297: $thisallowed.=$value;
6298: }
1.53 www 6299: $uri=$refuri;
6300: $statecond=$refstatecond;
1.52 www 6301: }
6302: }
1.148 www 6303: }
1.29 www 6304: }
1.52 www 6305: }
1.29 www 6306:
1.52 www 6307: #
1.103 harris41 6308: # Gathered now: all privileges that could apply, and condition number
1.52 www 6309: #
6310: #
6311: # Full or no access?
6312: #
1.29 www 6313:
1.52 www 6314: if ($thisallowed=~/F/) {
6315: return 'F';
6316: }
1.29 www 6317:
1.52 www 6318: unless ($thisallowed) {
6319: return '';
6320: }
1.29 www 6321:
1.52 www 6322: # Restrictions exist, deal with them
6323: #
6324: # C:according to course preferences
6325: # R:according to resource settings
6326: # L:unless locked
6327: # X:according to user session state
6328: #
6329:
6330: # Possibly locked functionality, check all courses
1.54 www 6331: # Locks might take effect only after 10 minutes cache expiration for other
6332: # courses, and 2 minutes for current course
1.52 www 6333:
6334: my $envkey;
6335: if ($thisallowed=~/L/) {
1.1000 raeburn 6336: foreach $envkey (keys(%env)) {
1.54 www 6337: if ($envkey=~/^user\.role\.(st|ta)\.([^\.]*)/) {
6338: my $courseid=$2;
6339: my $roleid=$1.'.'.$2;
1.92 www 6340: $courseid=~s/^\///;
1.54 www 6341: my $expiretime=600;
1.620 albertel 6342: if ($env{'request.role'} eq $roleid) {
1.54 www 6343: $expiretime=120;
6344: }
6345: my ($cdom,$cnum,$csec)=split(/\//,$courseid);
6346: my $prefix='course.'.$cdom.'_'.$cnum.'.';
1.620 albertel 6347: if ((time-$env{$prefix.'last_cache'})>$expiretime) {
1.731 albertel 6348: &coursedescription($courseid,{'freshen_cache' => 1});
1.54 www 6349: }
1.620 albertel 6350: if (($env{$prefix.'res.'.$uri.'.lock.sections'}=~/\,\Q$csec\E\,/)
6351: || ($env{$prefix.'res.'.$uri.'.lock.sections'} eq 'all')) {
6352: if ($env{$prefix.'res.'.$uri.'.lock.expire'}>time) {
6353: &log($env{'user.domain'},$env{'user.name'},
6354: $env{'user.home'},
1.57 www 6355: 'Locked by res: '.$priv.' for '.$uri.' due to '.
1.52 www 6356: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6357: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6358: return '';
6359: }
6360: }
1.620 albertel 6361: if (($env{$prefix.'priv.'.$priv.'.lock.sections'}=~/\,\Q$csec\E\,/)
6362: || ($env{$prefix.'priv.'.$priv.'.lock.sections'} eq 'all')) {
6363: if ($env{'priv.'.$priv.'.lock.expire'}>time) {
6364: &log($env{'user.domain'},$env{'user.name'},
6365: $env{'user.home'},
1.57 www 6366: 'Locked by priv: '.$priv.' for '.$uri.' due to '.
1.52 www 6367: $cdom.'/'.$cnum.'/'.$csec.' expire '.
1.620 albertel 6368: $env{$prefix.'priv.'.$priv.'.lock.expire'});
1.52 www 6369: return '';
6370: }
6371: }
6372: }
1.29 www 6373: }
1.52 www 6374: }
6375:
6376: #
6377: # Rest of the restrictions depend on selected course
6378: #
6379:
1.620 albertel 6380: unless ($env{'request.course.id'}) {
1.766 albertel 6381: if ($thisallowed eq 'A') {
6382: return 'A';
1.814 raeburn 6383: } elsif ($thisallowed eq 'B') {
6384: return 'B';
1.766 albertel 6385: } else {
6386: return '1';
6387: }
1.52 www 6388: }
1.29 www 6389:
1.52 www 6390: #
6391: # Now user is definitely in a course
6392: #
1.53 www 6393:
6394:
6395: # Course preferences
6396:
6397: if ($thisallowed=~/C/) {
1.620 albertel 6398: my $rolecode=(split(/\./,$env{'request.role'}))[0];
6399: my $unamedom=$env{'user.name'}.':'.$env{'user.domain'};
6400: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.roles.denied'}
1.479 albertel 6401: =~/\Q$rolecode\E/) {
1.1103 raeburn 6402: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6403: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6404: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode.' in '.
6405: $env{'request.course.id'});
6406: }
1.237 www 6407: return '';
6408: }
6409:
1.620 albertel 6410: if ($env{'course.'.$env{'request.course.id'}.'.'.$priv.'.users.denied'}
1.479 albertel 6411: =~/\Q$unamedom\E/) {
1.1103 raeburn 6412: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6413: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.
6414: 'Denied by user: '.$priv.' for '.$uri.' as '.$unamedom.' in '.
6415: $env{'request.course.id'});
6416: }
1.54 www 6417: return '';
6418: }
1.53 www 6419: }
6420:
6421: # Resource preferences
6422:
6423: if ($thisallowed=~/R/) {
1.620 albertel 6424: my $rolecode=(split(/\./,$env{'request.role'}))[0];
1.479 albertel 6425: if (&metadata($uri,'roledeny')=~/\Q$rolecode\E/) {
1.1103 raeburn 6426: if (($priv ne 'pch') && ($priv ne 'plc')) {
1.689 albertel 6427: &logthis($env{'user.domain'}.':'.$env{'user.name'}.':'.$env{'user.home'}.':'.
6428: 'Denied by role: '.$priv.' for '.$uri.' as '.$rolecode);
6429: }
6430: return '';
1.54 www 6431: }
1.53 www 6432: }
1.30 www 6433:
1.246 www 6434: # Restricted by state or randomout?
1.30 www 6435:
1.52 www 6436: if ($thisallowed=~/X/) {
1.620 albertel 6437: if ($env{'acc.randomout'}) {
1.579 albertel 6438: if (!$symb) { $symb=&symbread($uri,1); }
1.620 albertel 6439: if (($symb) && ($env{'acc.randomout'}=~/\&\Q$symb\E\&/)) {
1.248 www 6440: return '';
6441: }
1.247 www 6442: }
6443: if (&condval($statecond)) {
1.52 www 6444: return '2';
6445: } else {
6446: return '';
6447: }
6448: }
1.30 www 6449:
1.766 albertel 6450: if ($thisallowed eq 'A') {
6451: return 'A';
1.814 raeburn 6452: } elsif ($thisallowed eq 'B') {
6453: return 'B';
1.766 albertel 6454: }
1.52 www 6455: return 'F';
1.232 www 6456: }
1.1162 raeburn 6457:
6458: sub get_comm_blocks {
6459: my ($cdom,$cnum) = @_;
6460: if ($cdom eq '' || $cnum eq '') {
6461: return unless ($env{'request.course.id'});
6462: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
6463: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
6464: }
6465: my %commblocks;
6466: my $hashid=$cdom.'_'.$cnum;
6467: my ($blocksref,$cached)=&is_cached_new('comm_block',$hashid);
6468: if ((defined($cached)) && (ref($blocksref) eq 'HASH')) {
6469: %commblocks = %{$blocksref};
6470: } else {
6471: %commblocks = &Apache::lonnet::dump('comm_block',$cdom,$cnum);
6472: my $cachetime = 600;
6473: &do_cache_new('comm_block',$hashid,\%commblocks,$cachetime);
6474: }
6475: return %commblocks;
6476: }
6477:
6478: sub has_comm_blocking {
6479: my ($priv,$symb,$uri,$blocks) = @_;
6480: return unless ($env{'request.course.id'});
6481: return unless ($priv eq 'bre');
6482: return if ($env{'user.priv.'.$env{'request.role'}} =~/evb\&([^\:]*)/);
6483: my %commblocks;
6484: if (ref($blocks) eq 'HASH') {
6485: %commblocks = %{$blocks};
6486: } else {
6487: %commblocks = &get_comm_blocks();
6488: }
6489: return unless (keys(%commblocks) > 0);
6490: if (!$symb) { $symb=&symbread($uri,1); }
6491: my ($map,$resid,undef)=&decode_symb($symb);
6492: my %tocheck = (
6493: maps => $map,
6494: resources => $symb,
6495: );
6496: my @blockers;
6497: my $now = time;
1.1163 raeburn 6498: my $navmap = Apache::lonnavmaps::navmap->new();
1.1162 raeburn 6499: foreach my $block (keys(%commblocks)) {
6500: if ($block =~ /^(\d+)____(\d+)$/) {
6501: my ($start,$end) = ($1,$2);
6502: if ($start <= $now && $end >= $now) {
6503: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6504: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6505: if (ref($commblocks{$block}{'blocks'}{'docs'}{'maps'}) eq 'HASH') {
6506: if ($commblocks{$block}{'blocks'}{'docs'}{'maps'}{$map}) {
6507: unless (grep(/^\Q$block\E$/,@blockers)) {
6508: push(@blockers,$block);
6509: }
6510: }
6511: }
6512: if (ref($commblocks{$block}{'blocks'}{'docs'}{'resources'}) eq 'HASH') {
6513: if ($commblocks{$block}{'blocks'}{'docs'}{'resources'}{$symb}) {
6514: unless (grep(/^\Q$block\E$/,@blockers)) {
6515: push(@blockers,$block);
6516: }
6517: }
6518: }
6519: }
6520: }
6521: }
6522: } elsif ($block =~ /^firstaccess____(.+)$/) {
6523: my $item = $1;
1.1163 raeburn 6524: my @to_test;
1.1162 raeburn 6525: if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
6526: if (ref($commblocks{$block}{'blocks'}{'docs'}) eq 'HASH') {
6527: my $check_interval;
6528: if (&check_docs_block($commblocks{$block}{'blocks'}{'docs'},\%tocheck)) {
6529: my @interval;
6530: my $type = 'map';
6531: if ($item eq 'course') {
6532: $type = 'course';
6533: @interval=&EXT("resource.0.interval");
6534: } else {
6535: if ($item =~ /___\d+___/) {
6536: $type = 'resource';
6537: @interval=&EXT("resource.0.interval",$item);
1.1163 raeburn 6538: if (ref($navmap)) {
6539: my $res = $navmap->getBySymb($item);
6540: push(@to_test,$res);
6541: }
1.1162 raeburn 6542: } else {
6543: my $mapsymb = &symbread($item,1);
6544: if ($mapsymb) {
6545: if (ref($navmap)) {
6546: my $mapres = $navmap->getBySymb($mapsymb);
1.1163 raeburn 6547: @to_test = $mapres->retrieveResources($mapres,undef,0,1);
6548: foreach my $res (@to_test) {
1.1162 raeburn 6549: my $symb = $res->symb();
6550: next if ($symb eq $mapsymb);
6551: if ($symb ne '') {
6552: @interval=&EXT("resource.0.interval",$symb);
6553: last;
6554: }
6555: }
6556: }
6557: }
6558: }
6559: }
6560: if ($interval[0] =~ /\d+/) {
6561: my $first_access;
6562: if ($type eq 'resource') {
6563: $first_access=&get_first_access($interval[1],$item);
6564: } elsif ($type eq 'map') {
6565: $first_access=&get_first_access($interval[1],undef,$item);
6566: } else {
6567: $first_access=&get_first_access($interval[1]);
6568: }
6569: if ($first_access) {
6570: my $timesup = $first_access+$interval[0];
6571: if ($timesup > $now) {
1.1163 raeburn 6572: foreach my $res (@to_test) {
6573: if ($res->is_problem()) {
6574: if ($res->completable()) {
6575: unless (grep(/^\Q$block\E$/,@blockers)) {
6576: push(@blockers,$block);
6577: }
6578: last;
6579: }
6580: }
1.1162 raeburn 6581: }
6582: }
6583: }
6584: }
6585: }
6586: }
6587: }
6588: }
6589: }
6590: return @blockers;
6591: }
6592:
6593: sub check_docs_block {
6594: my ($docsblock,$tocheck) =@_;
6595: if ((ref($docsblock) ne 'HASH') || (ref($tocheck) ne 'HASH')) {
6596: return;
6597: }
6598: if (ref($docsblock->{'maps'}) eq 'HASH') {
6599: if ($tocheck->{'maps'}) {
6600: if ($docsblock->{'maps'}{$tocheck->{'maps'}}) {
6601: return 1;
6602: }
6603: }
6604: }
6605: if (ref($docsblock->{'resources'}) eq 'HASH') {
6606: if ($tocheck->{'resources'}) {
6607: if ($docsblock->{'resources'}{$tocheck->{'resources'}}) {
6608: return 1;
6609: }
6610: }
6611: }
6612: return;
6613: }
6614:
1.1133 foxr 6615: #
6616: # Removes the versino from a URI and
6617: # splits it in to its filename and path to the filename.
6618: # Seems like File::Basename could have done this more clearly.
6619: # Parameters:
6620: # $uri - input URI
6621: # Returns:
6622: # Two element list consisting of
6623: # $pathname - the URI up to and excluding the trailing /
6624: # $filename - The part of the URI following the last /
6625: # NOTE:
6626: # Another realization of this is simply:
6627: # use File::Basename;
6628: # ...
6629: # $uri = shift;
6630: # $filename = basename($uri);
6631: # $path = dirname($uri);
6632: # return ($filename, $path);
6633: #
6634: # The implementation below is probably faster however.
6635: #
1.710 albertel 6636: sub split_uri_for_cond {
6637: my $uri=&deversion(&declutter(shift));
6638: my @uriparts=split(/\//,$uri);
6639: my $filename=pop(@uriparts);
6640: my $pathname=join('/',@uriparts);
6641: return ($pathname,$filename);
6642: }
1.232 www 6643: # --------------------------------------------------- Is a resource on the map?
6644:
6645: sub is_on_map {
1.710 albertel 6646: my ($pathname,$filename) = &split_uri_for_cond(shift);
1.289 bowersj2 6647: #Trying to find the conditional for the file
1.620 albertel 6648: my $match=($env{'acc.res.'.$env{'request.course.id'}.'.'.$pathname}=~
1.289 bowersj2 6649: /\&\Q$filename\E\:([\d\|]+)\&/);
1.232 www 6650: if ($match) {
1.289 bowersj2 6651: return (1,$1);
6652: } else {
1.434 www 6653: return (0,0);
1.289 bowersj2 6654: }
1.12 www 6655: }
6656:
1.427 www 6657: # --------------------------------------------------------- Get symb from alias
6658:
6659: sub get_symb_from_alias {
6660: my $symb=shift;
6661: my ($map,$resid,$url)=&decode_symb($symb);
6662: # Already is a symb
6663: if ($url) { return $symb; }
6664: # Must be an alias
6665: my $aliassymb='';
6666: my %bighash;
1.620 albertel 6667: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.427 www 6668: &GDBM_READER(),0640)) {
6669: my $rid=$bighash{'mapalias_'.$symb};
6670: if ($rid) {
6671: my ($mapid,$resid)=split(/\./,$rid);
1.429 albertel 6672: $aliassymb=&encode_symb($bighash{'map_id_'.$mapid},
6673: $resid,$bighash{'src_'.$rid});
1.427 www 6674: }
6675: untie %bighash;
6676: }
6677: return $aliassymb;
6678: }
6679:
1.12 www 6680: # ----------------------------------------------------------------- Define Role
6681:
6682: sub definerole {
6683: if (allowed('mcr','/')) {
6684: my ($rolename,$sysrole,$domrole,$courole)=@_;
1.800 albertel 6685: foreach my $role (split(':',$sysrole)) {
6686: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6687: if ($pr{'cr:s'}!~/\Q$crole\E/) { return "refused:s:$crole"; }
6688: if ($pr{'cr:s'}=~/\Q$crole\E\&/) {
6689: if ($pr{'cr:s'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6690: return "refused:s:$crole&$cqual";
6691: }
6692: }
1.191 harris41 6693: }
1.800 albertel 6694: foreach my $role (split(':',$domrole)) {
6695: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6696: if ($pr{'cr:d'}!~/\Q$crole\E/) { return "refused:d:$crole"; }
6697: if ($pr{'cr:d'}=~/\Q$crole\E\&/) {
6698: if ($pr{'cr:d'}!~/\Q$crole\W\&\w*\Q$cqual\E/) {
1.21 www 6699: return "refused:d:$crole&$cqual";
6700: }
6701: }
1.191 harris41 6702: }
1.800 albertel 6703: foreach my $role (split(':',$courole)) {
6704: my ($crole,$cqual)=split(/\&/,$role);
1.479 albertel 6705: if ($pr{'cr:c'}!~/\Q$crole\E/) { return "refused:c:$crole"; }
6706: if ($pr{'cr:c'}=~/\Q$crole\E\&/) {
6707: if ($pr{'cr:c'}!~/\Q$crole\E\&\w*\Q$cqual\E/) {
1.21 www 6708: return "refused:c:$crole&$cqual";
6709: }
6710: }
1.191 harris41 6711: }
1.620 albertel 6712: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
6713: "$env{'user.domain'}:$env{'user.name'}:".
1.21 www 6714: "rolesdef_$rolename=".
6715: escape($sysrole.'_'.$domrole.'_'.$courole);
1.620 albertel 6716: return reply($command,$env{'user.home'});
1.12 www 6717: } else {
6718: return 'refused';
6719: }
1.105 harris41 6720: }
6721:
6722: # ---------------- Make a metadata query against the network of library servers
6723:
6724: sub metadata_query {
1.244 matthew 6725: my ($query,$custom,$customshow,$server_array)=@_;
1.120 harris41 6726: my %rhash;
1.845 albertel 6727: my %libserv = &all_library();
1.244 matthew 6728: my @server_list = (defined($server_array) ? @$server_array
6729: : keys(%libserv) );
6730: for my $server (@server_list) {
1.118 harris41 6731: unless ($custom or $customshow) {
6732: my $reply=&reply("querysend:".&escape($query),$server);
6733: $rhash{$server}=$reply;
6734: }
6735: else {
6736: my $reply=&reply("querysend:".&escape($query).':'.
6737: &escape($custom).':'.&escape($customshow),
6738: $server);
6739: $rhash{$server}=$reply;
6740: }
1.112 harris41 6741: }
1.118 harris41 6742: return \%rhash;
1.240 www 6743: }
6744:
6745: # ----------------------------------------- Send log queries and wait for reply
6746:
6747: sub log_query {
6748: my ($uname,$udom,$query,%filters)=@_;
6749: my $uhome=&homeserver($uname,$udom);
6750: if ($uhome eq 'no_host') { return 'error: no_host'; }
1.838 albertel 6751: my $uhost=&hostname($uhome);
1.800 albertel 6752: my $command=&escape(join(':',map{$_.'='.$filters{$_}} keys(%filters)));
1.240 www 6753: my $queryid=&reply("querysend:".$query.':'.$udom.':'.$uname.':'.$command,
6754: $uhome);
1.479 albertel 6755: unless ($queryid=~/^\Q$uhost\E\_/) { return 'error: '.$queryid; }
1.242 www 6756: return get_query_reply($queryid);
6757: }
6758:
1.818 raeburn 6759: # -------------------------- Update MySQL table for portfolio file
6760:
6761: sub update_portfolio_table {
1.821 raeburn 6762: my ($uname,$udom,$file_name,$query,$group,$action) = @_;
1.970 raeburn 6763: if ($group ne '') {
6764: $file_name =~s /^\Q$group\E//;
6765: }
1.818 raeburn 6766: my $homeserver = &homeserver($uname,$udom);
6767: my $queryid=
1.821 raeburn 6768: &reply("querysend:".$query.':'.&escape($uname.':'.$udom.':'.$group).
6769: ':'.&escape($file_name).':'.$action,$homeserver);
1.818 raeburn 6770: my $reply = &get_query_reply($queryid);
6771: return $reply;
6772: }
6773:
1.899 raeburn 6774: # -------------------------- Update MySQL allusers table
6775:
6776: sub update_allusers_table {
6777: my ($uname,$udom,$names) = @_;
6778: my $homeserver = &homeserver($uname,$udom);
6779: my $queryid=
6780: &reply('querysend:allusers:'.&escape($uname).':'.&escape($udom).':'.
6781: 'lastname='.&escape($names->{'lastname'}).'%%'.
6782: 'firstname='.&escape($names->{'firstname'}).'%%'.
6783: 'middlename='.&escape($names->{'middlename'}).'%%'.
6784: 'generation='.&escape($names->{'generation'}).'%%'.
6785: 'permanentemail='.&escape($names->{'permanentemail'}).'%%'.
6786: 'id='.&escape($names->{'id'}),$homeserver);
1.1075 raeburn 6787: return;
1.899 raeburn 6788: }
6789:
1.508 raeburn 6790: # ------- Request retrieval of institutional classlists for course(s)
1.506 raeburn 6791:
6792: sub fetch_enrollment_query {
1.511 raeburn 6793: my ($context,$affiliatesref,$replyref,$dom,$cnum) = @_;
1.508 raeburn 6794: my $homeserver;
1.547 raeburn 6795: my $maxtries = 1;
1.508 raeburn 6796: if ($context eq 'automated') {
6797: $homeserver = $perlvar{'lonHostID'};
1.547 raeburn 6798: $maxtries = 10; # will wait for up to 2000s for retrieval of classlist data before timeout
1.508 raeburn 6799: } else {
6800: $homeserver = &homeserver($cnum,$dom);
6801: }
1.838 albertel 6802: my $host=&hostname($homeserver);
1.506 raeburn 6803: my $cmd = '';
1.1000 raeburn 6804: foreach my $affiliate (keys(%{$affiliatesref})) {
1.800 albertel 6805: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.506 raeburn 6806: }
6807: $cmd =~ s/%%$//;
6808: $cmd = &escape($cmd);
6809: my $query = 'fetchenrollment';
1.620 albertel 6810: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$env{'user.name'}.':'.$cmd,$homeserver);
1.526 raeburn 6811: unless ($queryid=~/^\Q$host\E\_/) {
6812: &logthis('fetch_enrollment_query: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' context: '.$context.' '.$cnum);
6813: return 'error: '.$queryid;
6814: }
1.506 raeburn 6815: my $reply = &get_query_reply($queryid);
1.547 raeburn 6816: my $tries = 1;
6817: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
6818: $reply = &get_query_reply($queryid);
6819: $tries ++;
6820: }
1.526 raeburn 6821: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
1.620 albertel 6822: &logthis('fetch_enrollment_query error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' context: '.$context.' '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
1.526 raeburn 6823: } else {
1.901 albertel 6824: my @responses = split(/:/,$reply);
1.515 raeburn 6825: if ($homeserver eq $perlvar{'lonHostID'}) {
1.800 albertel 6826: foreach my $line (@responses) {
6827: my ($key,$value) = split(/=/,$line,2);
1.515 raeburn 6828: $$replyref{$key} = $value;
6829: }
6830: } else {
1.1117 foxr 6831: my $pathname = LONCAPA::tempdir();
1.800 albertel 6832: foreach my $line (@responses) {
6833: my ($key,$value) = split(/=/,$line);
1.506 raeburn 6834: $$replyref{$key} = $value;
6835: if ($value > 0) {
1.800 albertel 6836: foreach my $item (@{$$affiliatesref{$key}}) {
6837: my $filename = $dom.'_'.$key.'_'.$item.'_classlist.xml';
1.506 raeburn 6838: my $destname = $pathname.'/'.$filename;
6839: my $xml_classlist = &reply("autoretrieve:".$filename,$homeserver);
1.526 raeburn 6840: if ($xml_classlist =~ /^error/) {
6841: &logthis('fetch_enrollment_query - autoretrieve error: '.$xml_classlist.' for '.$filename.' from server: '.$homeserver.' '.$context.' '.$cnum);
6842: } else {
1.506 raeburn 6843: if ( open(FILE,">$destname") ) {
6844: print FILE &unescape($xml_classlist);
6845: close(FILE);
1.526 raeburn 6846: } else {
6847: &logthis('fetch_enrollment_query - error opening classlist file '.$destname.' '.$context.' '.$cnum);
1.506 raeburn 6848: }
6849: }
6850: }
6851: }
6852: }
6853: }
6854: return 'ok';
6855: }
6856: return 'error';
6857: }
6858:
1.242 www 6859: sub get_query_reply {
6860: my $queryid=shift;
1.1117 foxr 6861: my $replyfile=LONCAPA::tempdir().$queryid;
1.240 www 6862: my $reply='';
6863: for (1..100) {
6864: sleep 2;
6865: if (-e $replyfile.'.end') {
1.448 albertel 6866: if (open(my $fh,$replyfile)) {
1.904 albertel 6867: $reply = join('',<$fh>);
6868: close($fh);
1.240 www 6869: } else { return 'error: reply_file_error'; }
1.242 www 6870: return &unescape($reply);
6871: }
1.240 www 6872: }
1.242 www 6873: return 'timeout:'.$queryid;
1.240 www 6874: }
6875:
6876: sub courselog_query {
1.241 www 6877: #
6878: # possible filters:
6879: # url: url or symb
6880: # username
6881: # domain
6882: # action: view, submit, grade
6883: # start: timestamp
6884: # end: timestamp
6885: #
1.240 www 6886: my (%filters)=@_;
1.620 albertel 6887: unless ($env{'request.course.id'}) { return 'no_course'; }
1.241 www 6888: if ($filters{'url'}) {
6889: $filters{'url'}=&symbclean(&declutter($filters{'url'}));
6890: $filters{'url'}=~s/\.(\w+)$/(\\.\\d+)*\\.$1/;
6891: $filters{'url'}=~s/\.(\w+)\_\_\_/(\\.\\d+)*\\.$1/;
6892: }
1.620 albertel 6893: my $cname=$env{'course.'.$env{'request.course.id'}.'.num'};
6894: my $cdom=$env{'course.'.$env{'request.course.id'}.'.domain'};
1.240 www 6895: return &log_query($cname,$cdom,'courselog',%filters);
6896: }
6897:
6898: sub userlog_query {
1.858 raeburn 6899: #
6900: # possible filters:
6901: # action: log check role
6902: # start: timestamp
6903: # end: timestamp
6904: #
1.240 www 6905: my ($uname,$udom,%filters)=@_;
6906: return &log_query($uname,$udom,'userlog',%filters);
1.12 www 6907: }
6908:
1.506 raeburn 6909: #--------- Call auto-enrollment subs in localenroll.pm for homeserver for course
6910:
6911: sub auto_run {
1.508 raeburn 6912: my ($cnum,$cdom) = @_;
1.876 raeburn 6913: my $response = 0;
6914: my $settings;
6915: my %domconfig = &get_dom('configuration',['autoenroll'],$cdom);
6916: if (ref($domconfig{'autoenroll'}) eq 'HASH') {
6917: $settings = $domconfig{'autoenroll'};
6918: if ($settings->{'run'} eq '1') {
6919: $response = 1;
6920: }
6921: } else {
1.934 raeburn 6922: my $homeserver;
6923: if (&is_course($cdom,$cnum)) {
6924: $homeserver = &homeserver($cnum,$cdom);
6925: } else {
6926: $homeserver = &domain($cdom,'primary');
6927: }
6928: if ($homeserver ne 'no_host') {
6929: $response = &reply('autorun:'.$cdom,$homeserver);
6930: }
1.876 raeburn 6931: }
1.506 raeburn 6932: return $response;
6933: }
1.776 albertel 6934:
1.506 raeburn 6935: sub auto_get_sections {
1.508 raeburn 6936: my ($cnum,$cdom,$inst_coursecode) = @_;
1.1007 raeburn 6937: my $homeserver;
6938: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6939: $homeserver = &homeserver($cnum,$cdom);
6940: }
6941: if (!defined($homeserver)) {
6942: if ($cdom =~ /^$match_domain$/) {
6943: $homeserver = &domain($cdom,'primary');
6944: }
6945: }
6946: my @secs;
6947: if (defined($homeserver)) {
6948: my $response=&unescape(&reply('autogetsections:'.$inst_coursecode.':'.$cdom,$homeserver));
6949: unless ($response eq 'refused') {
6950: @secs = split(/:/,$response);
6951: }
1.506 raeburn 6952: }
6953: return @secs;
6954: }
1.776 albertel 6955:
1.506 raeburn 6956: sub auto_new_course {
1.1099 raeburn 6957: my ($cnum,$cdom,$inst_course_id,$owner,$coowners) = @_;
1.508 raeburn 6958: my $homeserver = &homeserver($cnum,$cdom);
1.1099 raeburn 6959: my $response=&unescape(&reply('autonewcourse:'.$inst_course_id.':'.&escape($owner).':'.$cdom.':'.&escape($coowners),$homeserver));
1.506 raeburn 6960: return $response;
6961: }
1.776 albertel 6962:
1.506 raeburn 6963: sub auto_validate_courseID {
1.508 raeburn 6964: my ($cnum,$cdom,$inst_course_id) = @_;
6965: my $homeserver = &homeserver($cnum,$cdom);
1.511 raeburn 6966: my $response=&unescape(&reply('autovalidatecourse:'.$inst_course_id.':'.$cdom,$homeserver));
1.506 raeburn 6967: return $response;
6968: }
1.776 albertel 6969:
1.1007 raeburn 6970: sub auto_validate_instcode {
1.1020 raeburn 6971: my ($cnum,$cdom,$instcode,$owner) = @_;
1.1007 raeburn 6972: my ($homeserver,$response);
6973: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6974: $homeserver = &homeserver($cnum,$cdom);
6975: }
6976: if (!defined($homeserver)) {
6977: if ($cdom =~ /^$match_domain$/) {
6978: $homeserver = &domain($cdom,'primary');
6979: }
6980: }
1.1065 raeburn 6981: $response=&unescape(&reply('autovalidateinstcode:'.$cdom.':'.
6982: &escape($instcode).':'.&escape($owner),$homeserver));
1.1027 raeburn 6983: my ($outcome,$description) = map { &unescape($_); } split('&',$response,2);
6984: return ($outcome,$description);
1.1007 raeburn 6985: }
6986:
1.506 raeburn 6987: sub auto_create_password {
1.873 raeburn 6988: my ($cnum,$cdom,$authparam,$udom) = @_;
6989: my ($homeserver,$response);
1.506 raeburn 6990: my $create_passwd = 0;
6991: my $authchk = '';
1.873 raeburn 6992: if ($udom =~ /^$match_domain$/) {
6993: $homeserver = &domain($udom,'primary');
6994: }
6995: if ($homeserver eq '') {
6996: if (($cdom =~ /^$match_domain$/) && ($cnum =~ /^$match_courseid$/)) {
6997: $homeserver = &homeserver($cnum,$cdom);
6998: }
6999: }
7000: if ($homeserver eq '') {
7001: $authchk = 'nodomain';
1.506 raeburn 7002: } else {
1.873 raeburn 7003: $response=&unescape(&reply('autocreatepassword:'.$authparam.':'.$cdom,$homeserver));
7004: if ($response eq 'refused') {
7005: $authchk = 'refused';
7006: } else {
1.901 albertel 7007: ($authparam,$create_passwd,$authchk) = split(/:/,$response);
1.873 raeburn 7008: }
1.506 raeburn 7009: }
7010: return ($authparam,$create_passwd,$authchk);
7011: }
7012:
1.706 raeburn 7013: sub auto_photo_permission {
7014: my ($cnum,$cdom,$students) = @_;
7015: my $homeserver = &homeserver($cnum,$cdom);
1.707 albertel 7016: my ($outcome,$perm_reqd,$conditions) =
7017: split(/:/,&unescape(&reply('autophotopermission:'.$cdom,$homeserver)),3);
1.709 albertel 7018: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7019: return (undef,undef);
7020: }
1.706 raeburn 7021: return ($outcome,$perm_reqd,$conditions);
7022: }
7023:
7024: sub auto_checkphotos {
7025: my ($uname,$udom,$pid) = @_;
7026: my $homeserver = &homeserver($uname,$udom);
7027: my ($result,$resulttype);
7028: my $outcome = &unescape(&reply('autophotocheck:'.&escape($udom).':'.
1.707 albertel 7029: &escape($uname).':'.&escape($pid),
7030: $homeserver));
1.709 albertel 7031: if ($outcome =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7032: return (undef,undef);
7033: }
1.706 raeburn 7034: if ($outcome) {
7035: ($result,$resulttype) = split(/:/,$outcome);
7036: }
7037: return ($result,$resulttype);
7038: }
7039:
7040: sub auto_photochoice {
7041: my ($cnum,$cdom) = @_;
7042: my $homeserver = &homeserver($cnum,$cdom);
7043: my ($update,$comment) = split(/:/,&unescape(&reply('autophotochoice:'.
1.707 albertel 7044: &escape($cdom),
7045: $homeserver)));
1.709 albertel 7046: if ($update =~ /^(con_lost|unknown_cmd|no_such_host)$/) {
7047: return (undef,undef);
7048: }
1.706 raeburn 7049: return ($update,$comment);
7050: }
7051:
7052: sub auto_photoupdate {
7053: my ($affiliatesref,$dom,$cnum,$photo) = @_;
7054: my $homeserver = &homeserver($cnum,$dom);
1.838 albertel 7055: my $host=&hostname($homeserver);
1.706 raeburn 7056: my $cmd = '';
7057: my $maxtries = 1;
1.800 albertel 7058: foreach my $affiliate (keys(%{$affiliatesref})) {
7059: $cmd .= $affiliate.'='.join(",",@{$$affiliatesref{$affiliate}}).'%%';
1.706 raeburn 7060: }
7061: $cmd =~ s/%%$//;
7062: $cmd = &escape($cmd);
7063: my $query = 'institutionalphotos';
7064: my $queryid=&reply("querysend:".$query.':'.$dom.':'.$cnum.':'.$cmd,$homeserver);
7065: unless ($queryid=~/^\Q$host\E\_/) {
7066: &logthis('institutionalphotos: invalid queryid: '.$queryid.' for host: '.$host.' and homeserver: '.$homeserver.' and course: '.$cnum);
7067: return 'error: '.$queryid;
7068: }
7069: my $reply = &get_query_reply($queryid);
7070: my $tries = 1;
7071: while (($reply=~/^timeout/) && ($tries < $maxtries)) {
7072: $reply = &get_query_reply($queryid);
7073: $tries ++;
7074: }
7075: if ( ($reply =~/^timeout/) || ($reply =~/^error/) ) {
7076: &logthis('institutionalphotos error: '.$reply.' for '.$dom.' '.$env{'user.name'}.' for '.$queryid.' course: '.$cnum.' maxtries: '.$maxtries.' tries: '.$tries);
7077: } else {
7078: my @responses = split(/:/,$reply);
7079: my $outcome = shift(@responses);
7080: foreach my $item (@responses) {
7081: my ($key,$value) = split(/=/,$item);
7082: $$photo{$key} = $value;
7083: }
7084: return $outcome;
7085: }
7086: return 'error';
7087: }
7088:
1.521 raeburn 7089: sub auto_instcode_format {
1.793 albertel 7090: my ($caller,$codedom,$instcodes,$codes,$codetitles,$cat_titles,
7091: $cat_order) = @_;
1.521 raeburn 7092: my $courses = '';
1.772 raeburn 7093: my @homeservers;
1.521 raeburn 7094: if ($caller eq 'global') {
1.841 albertel 7095: my %servers = &get_servers($codedom,'library');
7096: foreach my $tryserver (keys(%servers)) {
7097: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7098: push(@homeservers,$tryserver);
7099: }
1.584 raeburn 7100: }
1.1022 raeburn 7101: } elsif ($caller eq 'requests') {
7102: if ($codedom =~ /^$match_domain$/) {
7103: my $chome = &domain($codedom,'primary');
7104: unless ($chome eq 'no_host') {
7105: push(@homeservers,$chome);
7106: }
7107: }
1.521 raeburn 7108: } else {
1.772 raeburn 7109: push(@homeservers,&homeserver($caller,$codedom));
1.521 raeburn 7110: }
1.793 albertel 7111: foreach my $code (keys(%{$instcodes})) {
7112: $courses .= &escape($code).'='.&escape($$instcodes{$code}).'&';
1.521 raeburn 7113: }
7114: chop($courses);
1.772 raeburn 7115: my $ok_response = 0;
7116: my $response;
7117: while (@homeservers > 0 && $ok_response == 0) {
7118: my $server = shift(@homeservers);
7119: $response=&reply('autoinstcodeformat:'.$codedom.':'.$courses,$server);
7120: if ($response !~ /(con_lost|error|no_such_host|refused)/) {
7121: my ($codes_str,$codetitles_str,$cat_titles_str,$cat_order_str) =
1.901 albertel 7122: split(/:/,$response);
1.772 raeburn 7123: %{$codes} = (%{$codes},&str2hash($codes_str));
7124: push(@{$codetitles},&str2array($codetitles_str));
7125: %{$cat_titles} = (%{$cat_titles},&str2hash($cat_titles_str));
7126: %{$cat_order} = (%{$cat_order},&str2hash($cat_order_str));
7127: $ok_response = 1;
7128: }
7129: }
7130: if ($ok_response) {
1.521 raeburn 7131: return 'ok';
1.772 raeburn 7132: } else {
7133: return $response;
1.521 raeburn 7134: }
7135: }
7136:
1.792 raeburn 7137: sub auto_instcode_defaults {
7138: my ($domain,$returnhash,$code_order) = @_;
7139: my @homeservers;
1.841 albertel 7140:
7141: my %servers = &get_servers($domain,'library');
7142: foreach my $tryserver (keys(%servers)) {
7143: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7144: push(@homeservers,$tryserver);
7145: }
1.792 raeburn 7146: }
1.841 albertel 7147:
1.792 raeburn 7148: my $response;
1.841 albertel 7149: foreach my $server (@homeservers) {
1.792 raeburn 7150: $response=&reply('autoinstcodedefaults:'.$domain,$server);
1.841 albertel 7151: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
7152:
7153: foreach my $pair (split(/\&/,$response)) {
7154: my ($name,$value)=split(/\=/,$pair);
7155: if ($name eq 'code_order') {
7156: @{$code_order} = split(/\&/,&unescape($value));
7157: } else {
7158: $returnhash->{&unescape($name)}=&unescape($value);
7159: }
7160: }
7161: return 'ok';
1.792 raeburn 7162: }
1.841 albertel 7163:
7164: return $response;
1.1003 raeburn 7165: }
7166:
7167: sub auto_possible_instcodes {
1.1007 raeburn 7168: my ($domain,$codetitles,$cat_titles,$cat_orders,$code_order) = @_;
7169: unless ((ref($codetitles) eq 'ARRAY') && (ref($cat_titles) eq 'HASH') &&
7170: (ref($cat_orders) eq 'HASH') && (ref($code_order) eq 'ARRAY')) {
7171: return;
7172: }
1.1003 raeburn 7173: my (@homeservers,$uhome);
7174: if (defined(&domain($domain,'primary'))) {
7175: $uhome=&domain($domain,'primary');
7176: push(@homeservers,&domain($domain,'primary'));
7177: } else {
7178: my %servers = &get_servers($domain,'library');
7179: foreach my $tryserver (keys(%servers)) {
7180: if (!grep(/^\Q$tryserver\E$/,@homeservers)) {
7181: push(@homeservers,$tryserver);
7182: }
7183: }
7184: }
7185: my $response;
7186: foreach my $server (@homeservers) {
7187: $response=&reply('autopossibleinstcodes:'.$domain,$server);
7188: next if ($response =~ /(con_lost|error|no_such_host|refused)/);
1.1007 raeburn 7189: my ($codetitlestr,$codeorderstr,$cat_title,$cat_order) =
7190: split(':',$response);
7191: @{$codetitles} = map { &unescape($_); } (split('&',$codetitlestr));
7192: @{$code_order} = map { &unescape($_); } (split('&',$codeorderstr));
1.1003 raeburn 7193: foreach my $item (split('&',$cat_title)) {
1.1005 raeburn 7194: my ($name,$value)=split('=',$item);
7195: $cat_titles->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7196: }
7197: foreach my $item (split('&',$cat_order)) {
1.1005 raeburn 7198: my ($name,$value)=split('=',$item);
7199: $cat_orders->{&unescape($name)}=&thaw_unescape($value);
1.1003 raeburn 7200: }
7201: return 'ok';
7202: }
7203: return $response;
7204: }
1.792 raeburn 7205:
1.1010 raeburn 7206: sub auto_courserequest_checks {
7207: my ($dom) = @_;
1.1020 raeburn 7208: my ($homeserver,%validations);
7209: if ($dom =~ /^$match_domain$/) {
7210: $homeserver = &domain($dom,'primary');
7211: }
7212: unless ($homeserver eq 'no_host') {
7213: my $response=&reply('autocrsreqchecks:'.$dom,$homeserver);
7214: unless ($response =~ /(con_lost|error|no_such_host|refused)/) {
7215: my @items = split(/&/,$response);
7216: foreach my $item (@items) {
7217: my ($key,$value) = split('=',$item);
7218: $validations{&unescape($key)} = &thaw_unescape($value);
7219: }
7220: }
7221: }
1.1010 raeburn 7222: return %validations;
7223: }
7224:
1.1020 raeburn 7225: sub auto_courserequest_validation {
7226: my ($dom,$owner,$crstype,$inststatuslist,$instcode,$instseclist) = @_;
7227: my ($homeserver,$response);
7228: if ($dom =~ /^$match_domain$/) {
7229: $homeserver = &domain($dom,'primary');
7230: }
7231: unless ($homeserver eq 'no_host') {
1.1021 raeburn 7232:
1.1020 raeburn 7233: $response=&unescape(&reply('autocrsreqvalidation:'.$dom.':'.&escape($owner).
1.1021 raeburn 7234: ':'.&escape($crstype).':'.&escape($inststatuslist).
1.1020 raeburn 7235: ':'.&escape($instcode).':'.&escape($instseclist),
7236: $homeserver));
7237: }
7238: return $response;
7239: }
7240:
1.777 albertel 7241: sub auto_validate_class_sec {
1.918 raeburn 7242: my ($cdom,$cnum,$owners,$inst_class) = @_;
1.773 raeburn 7243: my $homeserver = &homeserver($cnum,$cdom);
1.918 raeburn 7244: my $ownerlist;
7245: if (ref($owners) eq 'ARRAY') {
7246: $ownerlist = join(',',@{$owners});
7247: } else {
7248: $ownerlist = $owners;
7249: }
1.773 raeburn 7250: my $response=&reply('autovalidateclass_sec:'.$inst_class.':'.
1.918 raeburn 7251: &escape($ownerlist).':'.$cdom,$homeserver);
1.773 raeburn 7252: return $response;
7253: }
7254:
1.679 raeburn 7255: # ------------------------------------------------------- Course Group routines
7256:
7257: sub get_coursegroups {
1.809 raeburn 7258: my ($cdom,$cnum,$group,$namespace) = @_;
7259: return(&dump($namespace,$cdom,$cnum,$group));
1.805 raeburn 7260: }
7261:
1.679 raeburn 7262: sub modify_coursegroup {
7263: my ($cdom,$cnum,$groupsettings) = @_;
7264: return(&put('coursegroups',$groupsettings,$cdom,$cnum));
7265: }
7266:
1.809 raeburn 7267: sub toggle_coursegroup_status {
7268: my ($cdom,$cnum,$group,$action) = @_;
7269: my ($from_namespace,$to_namespace);
7270: if ($action eq 'delete') {
7271: $from_namespace = 'coursegroups';
7272: $to_namespace = 'deleted_groups';
7273: } else {
7274: $from_namespace = 'deleted_groups';
7275: $to_namespace = 'coursegroups';
7276: }
7277: my %curr_group = &get_coursegroups($cdom,$cnum,$group,$from_namespace);
1.805 raeburn 7278: if (my $tmp = &error(%curr_group)) {
7279: &Apache::lonnet::logthis('Error retrieving group: '.$tmp.' in '.$cnum.':'.$cdom);
7280: return ('read error',$tmp);
7281: } else {
7282: my %savedsettings = %curr_group;
1.809 raeburn 7283: my $result = &put($to_namespace,\%savedsettings,$cdom,$cnum);
1.805 raeburn 7284: my $deloutcome;
7285: if ($result eq 'ok') {
1.809 raeburn 7286: $deloutcome = &del($from_namespace,[$group],$cdom,$cnum);
1.805 raeburn 7287: } else {
7288: return ('write error',$result);
7289: }
7290: if ($deloutcome eq 'ok') {
7291: return 'ok';
7292: } else {
7293: return ('delete error',$deloutcome);
7294: }
7295: }
7296: }
7297:
1.679 raeburn 7298: sub modify_group_roles {
1.957 raeburn 7299: my ($cdom,$cnum,$group_id,$user,$end,$start,$userprivs,$selfenroll,$context) = @_;
1.679 raeburn 7300: my $url = '/'.$cdom.'/'.$cnum.'/'.$group_id;
7301: my $role = 'gr/'.&escape($userprivs);
7302: my ($uname,$udom) = split(/:/,$user);
1.957 raeburn 7303: my $result = &assignrole($udom,$uname,$url,$role,$end,$start,'',$selfenroll,$context);
1.684 raeburn 7304: if ($result eq 'ok') {
7305: &devalidate_getgroups_cache($udom,$uname,$cdom,$cnum);
7306: }
1.679 raeburn 7307: return $result;
7308: }
7309:
7310: sub modify_coursegroup_membership {
7311: my ($cdom,$cnum,$membership) = @_;
7312: my $result = &put('groupmembership',$membership,$cdom,$cnum);
7313: return $result;
7314: }
7315:
1.682 raeburn 7316: sub get_active_groups {
7317: my ($udom,$uname,$cdom,$cnum) = @_;
7318: my $now = time;
7319: my %groups = ();
7320: foreach my $key (keys(%env)) {
1.811 albertel 7321: if ($key =~ m-user\.role\.gr\./($match_domain)/($match_courseid)/(\w+)$-) {
1.682 raeburn 7322: my ($start,$end) = split(/\./,$env{$key});
7323: if (($end!=0) && ($end<$now)) { next; }
7324: if (($start!=0) && ($start>$now)) { next; }
7325: if ($1 eq $cdom && $2 eq $cnum) {
7326: $groups{$3} = $env{$key} ;
7327: }
7328: }
7329: }
7330: return %groups;
7331: }
7332:
1.683 raeburn 7333: sub get_group_membership {
7334: my ($cdom,$cnum,$group) = @_;
7335: return(&dump('groupmembership',$cdom,$cnum,$group));
7336: }
7337:
7338: sub get_users_groups {
7339: my ($udom,$uname,$courseid) = @_;
1.733 raeburn 7340: my @usersgroups;
1.683 raeburn 7341: my $cachetime=1800;
7342:
7343: my $hashid="$udom:$uname:$courseid";
1.733 raeburn 7344: my ($grouplist,$cached)=&is_cached_new('getgroups',$hashid);
7345: if (defined($cached)) {
1.734 albertel 7346: @usersgroups = split(/:/,$grouplist);
1.733 raeburn 7347: } else {
7348: $grouplist = '';
1.816 raeburn 7349: my $courseurl = &courseid_to_courseurl($courseid);
1.1166 raeburn 7350: my %roleshash = &dump('roles',$udom,$uname,$courseurl);
1.817 raeburn 7351: my $access_end = $env{'course.'.$courseid.
7352: '.default_enrollment_end_date'};
7353: my $now = time;
7354: foreach my $key (keys(%roleshash)) {
7355: if ($key =~ /^\Q$courseurl\E\/(\w+)\_gr$/) {
7356: my $group = $1;
7357: if ($roleshash{$key} =~ /_(\d+)_(\d+)$/) {
7358: my $start = $2;
7359: my $end = $1;
7360: if ($start == -1) { next; } # deleted from group
7361: if (($start!=0) && ($start>$now)) { next; }
7362: if (($end!=0) && ($end<$now)) {
7363: if ($access_end && $access_end < $now) {
7364: if ($access_end - $end < 86400) {
7365: push(@usersgroups,$group);
1.733 raeburn 7366: }
7367: }
1.817 raeburn 7368: next;
1.733 raeburn 7369: }
1.817 raeburn 7370: push(@usersgroups,$group);
1.683 raeburn 7371: }
7372: }
7373: }
1.817 raeburn 7374: @usersgroups = &sort_course_groups($courseid,@usersgroups);
7375: $grouplist = join(':',@usersgroups);
7376: &do_cache_new('getgroups',$hashid,$grouplist,$cachetime);
1.683 raeburn 7377: }
1.733 raeburn 7378: return @usersgroups;
1.683 raeburn 7379: }
7380:
7381: sub devalidate_getgroups_cache {
7382: my ($udom,$uname,$cdom,$cnum)=@_;
7383: my $courseid = $cdom.'_'.$cnum;
1.807 albertel 7384:
1.683 raeburn 7385: my $hashid="$udom:$uname:$courseid";
7386: &devalidate_cache_new('getgroups',$hashid);
7387: }
7388:
1.12 www 7389: # ------------------------------------------------------------------ Plain Text
7390:
7391: sub plaintext {
1.988 raeburn 7392: my ($short,$type,$cid,$forcedefault) = @_;
1.1046 raeburn 7393: if ($short =~ m{^cr/}) {
1.758 albertel 7394: return (split('/',$short))[-1];
7395: }
1.742 raeburn 7396: if (!defined($cid)) {
7397: $cid = $env{'request.course.id'};
7398: }
7399: my %rolenames = (
1.1008 raeburn 7400: Course => 'std',
7401: Community => 'alt1',
1.742 raeburn 7402: );
1.1037 raeburn 7403: if ($cid ne '') {
7404: if ($env{'course.'.$cid.'.'.$short.'.plaintext'} ne '') {
7405: unless ($forcedefault) {
7406: my $roletext = $env{'course.'.$cid.'.'.$short.'.plaintext'};
7407: &Apache::lonlocal::mt_escape(\$roletext);
7408: return &Apache::lonlocal::mt($roletext);
7409: }
7410: }
7411: }
7412: if ((defined($type)) && (defined($rolenames{$type})) &&
7413: (defined($rolenames{$type})) &&
7414: (defined($prp{$short}{$rolenames{$type}}))) {
1.742 raeburn 7415: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$type}});
1.1037 raeburn 7416: } elsif ($cid ne '') {
7417: my $crstype = $env{'course.'.$cid.'.type'};
7418: if (($crstype ne '') && (defined($rolenames{$crstype})) &&
7419: (defined($prp{$short}{$rolenames{$crstype}}))) {
7420: return &Apache::lonlocal::mt($prp{$short}{$rolenames{$crstype}});
7421: }
1.742 raeburn 7422: }
1.1037 raeburn 7423: return &Apache::lonlocal::mt($prp{$short}{'std'});
1.12 www 7424: }
7425:
7426: # ----------------------------------------------------------------- Assign Role
7427:
7428: sub assignrole {
1.957 raeburn 7429: my ($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,
7430: $context)=@_;
1.21 www 7431: my $mrole;
7432: if ($role =~ /^cr\//) {
1.393 www 7433: my $cwosec=$url;
1.811 albertel 7434: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.393 www 7435: unless (&allowed('ccr',$cwosec)) {
1.1026 raeburn 7436: my $refused = 1;
7437: if ($context eq 'requestcourses') {
7438: if (($env{'user.name'} ne '') && ($env{'user.domain'} ne '')) {
7439: if ($role =~ m{^cr/($match_domain)/($match_username)/([^/]+)$}) {
7440: if (($1 eq $env{'user.domain'}) && ($2 eq $env{'user.name'})) {
7441: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7442: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7443: if ($crsenv{'internal.courseowner'} eq
7444: $env{'user.name'}.':'.$env{'user.domain'}) {
7445: $refused = '';
7446: }
7447: }
7448: }
7449: }
7450: }
7451: if ($refused) {
7452: &logthis('Refused custom assignrole: '.
7453: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.
7454: ' by '.$env{'user.name'}.' at '.$env{'user.domain'});
7455: return 'refused';
7456: }
1.104 www 7457: }
1.21 www 7458: $mrole='cr';
1.678 raeburn 7459: } elsif ($role =~ /^gr\//) {
7460: my $cwogrp=$url;
1.811 albertel 7461: $cwogrp=~s{^/($match_domain)/($match_courseid)/.*}{$1/$2};
1.678 raeburn 7462: unless (&allowed('mdg',$cwogrp)) {
7463: &logthis('Refused group assignrole: '.
7464: $udom.' '.$uname.' '.$url.' '.$role.' '.$end.' '.$start.' by '.
7465: $env{'user.name'}.' at '.$env{'user.domain'});
7466: return 'refused';
7467: }
7468: $mrole='gr';
1.21 www 7469: } else {
1.82 www 7470: my $cwosec=$url;
1.811 albertel 7471: $cwosec=~s/^\/($match_domain)\/($match_courseid)\/.*/$1\/$2/;
1.932 raeburn 7472: if (!(&allowed('c'.$role,$cwosec)) && !(&allowed('c'.$role,$udom))) {
7473: my $refused;
7474: if (($env{'request.course.sec'} ne '') && ($role eq 'st')) {
7475: if (!(&allowed('c'.$role,$url))) {
7476: $refused = 1;
7477: }
7478: } else {
7479: $refused = 1;
7480: }
1.947 raeburn 7481: if ($refused) {
1.1045 raeburn 7482: my ($cdom,$cnum) = ($cwosec =~ m{^/?($match_domain)/($match_courseid)$});
7483: if (!$selfenroll && $context eq 'course') {
7484: my %crsenv;
7485: if ($role eq 'cc' || $role eq 'co') {
7486: %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7487: if (($role eq 'cc') && ($cnum !~ /^$match_community$/)) {
7488: if ($env{'request.role'} eq 'cc./'.$cdom.'/'.$cnum) {
7489: if ($crsenv{'internal.courseowner'} eq
7490: $env{'user.name'}.':'.$env{'user.domain'}) {
7491: $refused = '';
7492: }
7493: }
7494: } elsif (($role eq 'co') && ($cnum =~ /^$match_community$/)) {
7495: if ($env{'request.role'} eq 'co./'.$cdom.'/'.$cnum) {
7496: if ($crsenv{'internal.courseowner'} eq
7497: $env{'user.name'}.':'.$env{'user.domain'}) {
7498: $refused = '';
7499: }
7500: }
7501: }
7502: }
7503: } elsif (($selfenroll == 1) && ($role eq 'st') && ($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'})) {
1.947 raeburn 7504: $refused = '';
1.1017 raeburn 7505: } elsif ($context eq 'requestcourses') {
1.1041 raeburn 7506: my @possroles = ('st','ta','ep','in','cc','co');
1.1026 raeburn 7507: if ((grep(/^\Q$role\E$/,@possroles)) && ($env{'user.name'} ne '' && $env{'user.domain'} ne '')) {
1.1041 raeburn 7508: my $wrongcc;
7509: if ($cnum =~ /^$match_community$/) {
7510: $wrongcc = 1 if ($role eq 'cc');
7511: } else {
7512: $wrongcc = 1 if ($role eq 'co');
7513: }
7514: unless ($wrongcc) {
7515: my %crsenv = &userenvironment($cdom,$cnum,('internal.courseowner'));
7516: if ($crsenv{'internal.courseowner'} eq
7517: $env{'user.name'}.':'.$env{'user.domain'}) {
7518: $refused = '';
7519: }
1.1017 raeburn 7520: }
7521: }
1.1183 ! raeburn 7522: } elsif ($context eq 'requestauthor') {
! 7523: if (($udom eq $env{'user.domain'}) && ($uname eq $env{'user.name'}) &&
! 7524: ($url eq '/'.$udom.'/') && ($role eq 'au')) {
! 7525: if ($env{'environment.requestauthor'} eq 'automatic') {
! 7526: $refused = '';
! 7527: } else {
! 7528: my %domdefaults = &get_domain_defaults($udom);
! 7529: if (ref($domdefaults{'requestauthor'}) eq 'HASH') {
! 7530: my $checkbystatus;
! 7531: if ($env{'user.adv'}) {
! 7532: my $disposition = $domdefaults{'requestauthor'}{'_LC_adv'};
! 7533: if ($disposition eq 'automatic') {
! 7534: $refused = '';
! 7535: } elsif ($disposition eq '') {
! 7536: $checkbystatus = 1;
! 7537: }
! 7538: } else {
! 7539: $checkbystatus = 1;
! 7540: }
! 7541: if ($checkbystatus) {
! 7542: if ($env{'environment.inststatus'}) {
! 7543: my @inststatuses = split(/,/,$env{'environment.inststatus'});
! 7544: foreach my $type (@inststatuses) {
! 7545: if (($type ne '') &&
! 7546: ($domdefaults{'requestauthor'}{$type} eq 'automatic')) {
! 7547: $refused = '';
! 7548: }
! 7549: }
! 7550: } elsif ($domdefaults{'requestauthor'}{'default'} eq 'automatic') {
! 7551: $refused = '';
! 7552: }
! 7553: }
! 7554: }
! 7555: }
! 7556: }
1.1017 raeburn 7557: }
7558: if ($refused) {
1.947 raeburn 7559: &logthis('Refused assignrole: '.$udom.' '.$uname.' '.$url.
7560: ' '.$role.' '.$end.' '.$start.' by '.
7561: $env{'user.name'}.' at '.$env{'user.domain'});
7562: return 'refused';
7563: }
1.932 raeburn 7564: }
1.1131 raeburn 7565: } elsif ($role eq 'au') {
7566: if ($url ne '/'.$udom.'/') {
7567: &logthis('Attempt by '.$env{'user.name'}.':'.$env{'user.domain'}.
7568: ' to assign author role for '.$uname.':'.$udom.
7569: ' in domain: '.$url.' refused (wrong domain).');
7570: return 'refused';
7571: }
1.104 www 7572: }
1.21 www 7573: $mrole=$role;
7574: }
1.620 albertel 7575: my $command="encrypt:rolesput:$env{'user.domain'}:$env{'user.name'}:".
1.21 www 7576: "$udom:$uname:$url".'_'."$mrole=$role";
1.81 www 7577: if ($end) { $command.='_'.$end; }
1.21 www 7578: if ($start) {
7579: if ($end) {
1.81 www 7580: $command.='_'.$start;
1.21 www 7581: } else {
1.81 www 7582: $command.='_0_'.$start;
1.21 www 7583: }
7584: }
1.739 raeburn 7585: my $origstart = $start;
7586: my $origend = $end;
1.957 raeburn 7587: my $delflag;
1.357 www 7588: # actually delete
7589: if ($deleteflag) {
1.373 www 7590: if ((&allowed('dro',$udom)) || (&allowed('dro',$url))) {
1.357 www 7591: # modify command to delete the role
1.620 albertel 7592: $command="encrypt:rolesdel:$env{'user.domain'}:$env{'user.name'}:".
1.357 www 7593: "$udom:$uname:$url".'_'."$mrole";
1.620 albertel 7594: &logthis("$env{'user.name'} at $env{'user.domain'} deletes $mrole in $url for $uname at $udom");
1.357 www 7595: # set start and finish to negative values for userrolelog
7596: $start=-1;
7597: $end=-1;
1.957 raeburn 7598: $delflag = 1;
1.357 www 7599: }
7600: }
7601: # send command
1.349 www 7602: my $answer=&reply($command,&homeserver($uname,$udom));
1.357 www 7603: # log new user role if status is ok
1.349 www 7604: if ($answer eq 'ok') {
1.663 raeburn 7605: &userrolelog($role,$uname,$udom,$url,$start,$end);
1.739 raeburn 7606: # for course roles, perform group memberships changes triggered by role change.
1.957 raeburn 7607: &courserolelog($role,$uname,$udom,$url,$origstart,$origend,$delflag,$selfenroll,$context);
1.739 raeburn 7608: unless ($role =~ /^gr/) {
7609: &Apache::longroup::group_changes($udom,$uname,$url,$role,$origend,
1.957 raeburn 7610: $origstart,$selfenroll,$context);
1.739 raeburn 7611: }
1.1053 raeburn 7612: if ($role eq 'cc') {
7613: &autoupdate_coowners($url,$end,$start,$uname,$udom);
7614: }
1.349 www 7615: }
7616: return $answer;
1.169 harris41 7617: }
7618:
1.1053 raeburn 7619: sub autoupdate_coowners {
7620: my ($url,$end,$start,$uname,$udom) = @_;
7621: my ($cdom,$cnum) = ($url =~ m{^/($match_domain)/($match_courseid)});
7622: if (($cdom ne '') && ($cnum ne '')) {
7623: my $now = time;
7624: my %domdesign = &Apache::loncommon::get_domainconf($cdom);
7625: if ($domdesign{$cdom.'.autoassign.co-owners'}) {
7626: my %coursehash = &coursedescription($cdom.'_'.$cnum);
7627: my $instcode = $coursehash{'internal.coursecode'};
7628: if ($instcode ne '') {
1.1056 raeburn 7629: if (($start && $start <= $now) && ($end == 0) || ($end > $now)) {
7630: unless ($coursehash{'internal.courseowner'} eq $uname.':'.$udom) {
1.1053 raeburn 7631: my ($delcoowners,@newcoowners,$putresult,$delresult,$coowners);
1.1056 raeburn 7632: my ($result,$desc) = &auto_validate_instcode($cnum,$cdom,$instcode,$uname.':'.$udom);
7633: if ($result eq 'valid') {
7634: if ($coursehash{'internal.co-owners'}) {
1.1053 raeburn 7635: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7636: push(@newcoowners,$coowner);
7637: }
7638: unless (grep(/^\Q$uname\E:\Q$udom\E$/,@newcoowners)) {
7639: push(@newcoowners,$uname.':'.$udom);
7640: }
7641: @newcoowners = sort(@newcoowners);
7642: } else {
7643: push(@newcoowners,$uname.':'.$udom);
7644: }
7645: } else {
7646: if ($coursehash{'internal.co-owners'}) {
7647: foreach my $coowner (split(',',$coursehash{'internal.co-owners'})) {
7648: unless ($coowner eq $uname.':'.$udom) {
7649: push(@newcoowners,$coowner);
7650: }
7651: }
7652: unless (@newcoowners > 0) {
7653: $delcoowners = 1;
7654: $coowners = '';
7655: }
7656: }
7657: }
7658: if (@newcoowners || $delcoowners) {
7659: &store_coowners($cdom,$cnum,$coursehash{'home'},
7660: $delcoowners,@newcoowners);
7661: }
7662: }
7663: }
7664: }
7665: }
7666: }
7667: }
7668:
7669: sub store_coowners {
7670: my ($cdom,$cnum,$chome,$delcoowners,@newcoowners) = @_;
7671: my $cid = $cdom.'_'.$cnum;
7672: my ($coowners,$delresult,$putresult);
7673: if (@newcoowners) {
7674: $coowners = join(',',@newcoowners);
7675: my %coownershash = (
7676: 'internal.co-owners' => $coowners,
7677: );
7678: $putresult = &put('environment',\%coownershash,$cdom,$cnum);
7679: if ($putresult eq 'ok') {
7680: if ($env{'course.'.$cid.'.num'} eq $cnum) {
7681: &appenv({'course.'.$cid.'.internal.co-owners' => $coowners});
7682: }
7683: }
7684: }
7685: if ($delcoowners) {
7686: $delresult = &Apache::lonnet::del('environment',['internal.co-owners'],$cdom,$cnum);
7687: if ($delresult eq 'ok') {
7688: if ($env{'course.'.$cid.'.internal.co-owners'}) {
7689: &Apache::lonnet::delenv('course.'.$cid.'.internal.co-owners');
7690: }
7691: }
7692: }
7693: if (($putresult eq 'ok') || ($delresult eq 'ok')) {
7694: my %crsinfo =
7695: &Apache::lonnet::courseiddump($cdom,'.',1,'.','.',$cnum,undef,undef,'.');
7696: if (ref($crsinfo{$cid}) eq 'HASH') {
7697: $crsinfo{$cid}{'co-owners'} = \@newcoowners;
7698: my $cidput = &Apache::lonnet::courseidput($cdom,\%crsinfo,$chome,'notime');
7699: }
7700: }
7701: }
7702:
1.169 harris41 7703: # -------------------------------------------------- Modify user authentication
1.197 www 7704: # Overrides without validation
7705:
1.169 harris41 7706: sub modifyuserauth {
7707: my ($udom,$uname,$umode,$upass)=@_;
7708: my $uhome=&homeserver($uname,$udom);
1.197 www 7709: unless (&allowed('mau',$udom)) { return 'refused'; }
7710: &logthis('Call to modify user authentication '.$udom.', '.$uname.', '.
1.620 albertel 7711: $umode.' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7712: ' in domain '.$env{'request.role.domain'});
1.169 harris41 7713: my $reply=&reply('encrypt:changeuserauth:'.$udom.':'.$uname.':'.$umode.':'.
7714: &escape($upass),$uhome);
1.620 albertel 7715: &log($env{'user.domain'},$env{'user.name'},$env{'user.home'},
1.197 www 7716: 'Authentication changed for '.$udom.', '.$uname.', '.$umode.
7717: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
7718: &log($udom,,$uname,$uhome,
1.620 albertel 7719: 'Authentication changed by '.$env{'user.domain'}.', '.
7720: $env{'user.name'}.', '.$umode.
1.197 www 7721: '(Remote '.$ENV{'REMOTE_ADDR'}.'): '.$reply);
1.169 harris41 7722: unless ($reply eq 'ok') {
1.197 www 7723: &logthis('Authentication mode error: '.$reply);
1.169 harris41 7724: return 'error: '.$reply;
7725: }
1.170 harris41 7726: return 'ok';
1.80 www 7727: }
7728:
1.81 www 7729: # --------------------------------------------------------------- Modify a user
1.80 www 7730:
1.81 www 7731: sub modifyuser {
1.206 matthew 7732: my ($udom, $uname, $uid,
7733: $umode, $upass, $first,
7734: $middle, $last, $gene,
1.1058 raeburn 7735: $forceid, $desiredhome, $email, $inststatus, $candelete)=@_;
1.807 albertel 7736: $udom= &LONCAPA::clean_domain($udom);
7737: $uname=&LONCAPA::clean_username($uname);
1.1059 raeburn 7738: my $showcandelete = 'none';
7739: if (ref($candelete) eq 'ARRAY') {
7740: if (@{$candelete} > 0) {
7741: $showcandelete = join(', ',@{$candelete});
7742: }
7743: }
1.81 www 7744: &logthis('Call to modify user '.$udom.', '.$uname.', '.$uid.', '.
1.80 www 7745: $umode.', '.$first.', '.$middle.', '.
1.1059 raeburn 7746: $last.', '.$gene.'(forceid: '.$forceid.'; candelete: '.$showcandelete.')'.
1.206 matthew 7747: (defined($desiredhome) ? ' desiredhome = '.$desiredhome :
7748: ' desiredhome not specified').
1.620 albertel 7749: ' by '.$env{'user.name'}.' at '.$env{'user.domain'}.
7750: ' in domain '.$env{'request.role.domain'});
1.230 stredwic 7751: my $uhome=&homeserver($uname,$udom,'true');
1.1075 raeburn 7752: my $newuser;
7753: if ($uhome eq 'no_host') {
7754: $newuser = 1;
7755: }
1.80 www 7756: # ----------------------------------------------------------------- Create User
1.406 albertel 7757: if (($uhome eq 'no_host') &&
7758: (($umode && $upass) || ($umode eq 'localauth'))) {
1.80 www 7759: my $unhome='';
1.844 albertel 7760: if (defined($desiredhome) && &host_domain($desiredhome) eq $udom) {
1.209 matthew 7761: $unhome = $desiredhome;
1.620 albertel 7762: } elsif($env{'course.'.$env{'request.course.id'}.'.domain'} eq $udom) {
7763: $unhome=$env{'course.'.$env{'request.course.id'}.'.home'};
1.209 matthew 7764: } else { # load balancing routine for determining $unhome
1.81 www 7765: my $loadm=10000000;
1.841 albertel 7766: my %servers = &get_servers($udom,'library');
7767: foreach my $tryserver (keys(%servers)) {
7768: my $answer=reply('load',$tryserver);
7769: if (($answer=~/\d+/) && ($answer<$loadm)) {
7770: $loadm=$answer;
7771: $unhome=$tryserver;
7772: }
1.80 www 7773: }
7774: }
7775: if (($unhome eq '') || ($unhome eq 'no_host')) {
1.206 matthew 7776: return 'error: unable to find a home server for '.$uname.
7777: ' in domain '.$udom;
1.80 www 7778: }
7779: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':'.$umode.':'.
7780: &escape($upass),$unhome);
7781: unless ($reply eq 'ok') {
7782: return 'error: '.$reply;
7783: }
1.230 stredwic 7784: $uhome=&homeserver($uname,$udom,'true');
1.80 www 7785: if (($uhome eq '') || ($uhome eq 'no_host') || ($uhome ne $unhome)) {
1.386 matthew 7786: return 'error: unable verify users home machine.';
1.80 www 7787: }
1.209 matthew 7788: } # End of creation of new user
1.80 www 7789: # ---------------------------------------------------------------------- Add ID
7790: if ($uid) {
7791: $uid=~tr/A-Z/a-z/;
7792: my %uidhash=&idrget($udom,$uname);
1.196 www 7793: if (($uidhash{$uname}) && ($uidhash{$uname}!~/error\:/)
7794: && (!$forceid)) {
1.80 www 7795: unless ($uid eq $uidhash{$uname}) {
1.386 matthew 7796: return 'error: user id "'.$uid.'" does not match '.
7797: 'current user id "'.$uidhash{$uname}.'".';
1.80 www 7798: }
7799: } else {
7800: &idput($udom,($uname => $uid));
7801: }
7802: }
7803: # -------------------------------------------------------------- Add names, etc
1.313 matthew 7804: my @tmp=&get('environment',
1.899 raeburn 7805: ['firstname','middlename','lastname','generation','id',
1.963 raeburn 7806: 'permanentemail','inststatus'],
1.134 albertel 7807: $udom,$uname);
1.1075 raeburn 7808: my (%names,%oldnames);
1.313 matthew 7809: if ($tmp[0] =~ m/^error:.*/) {
7810: %names=();
7811: } else {
7812: %names = @tmp;
1.1075 raeburn 7813: %oldnames = %names;
1.313 matthew 7814: }
1.388 www 7815: #
1.1058 raeburn 7816: # If name, email and/or uid are blank (e.g., because an uploaded file
7817: # of users did not contain them), do not overwrite existing values
7818: # unless field is in $candelete array ref.
7819: #
7820:
7821: my @fields = ('firstname','middlename','lastname','generation',
7822: 'permanentemail','id');
7823: my %newvalues;
7824: if (ref($candelete) eq 'ARRAY') {
7825: foreach my $field (@fields) {
7826: if (grep(/^\Q$field\E$/,@{$candelete})) {
7827: if ($field eq 'firstname') {
7828: $names{$field} = $first;
7829: } elsif ($field eq 'middlename') {
7830: $names{$field} = $middle;
7831: } elsif ($field eq 'lastname') {
7832: $names{$field} = $last;
7833: } elsif ($field eq 'generation') {
7834: $names{$field} = $gene;
7835: } elsif ($field eq 'permanentemail') {
7836: $names{$field} = $email;
7837: } elsif ($field eq 'id') {
7838: $names{$field} = $uid;
7839: }
7840: }
7841: }
7842: }
1.388 www 7843: if ($first) { $names{'firstname'} = $first; }
1.385 matthew 7844: if (defined($middle)) { $names{'middlename'} = $middle; }
1.388 www 7845: if ($last) { $names{'lastname'} = $last; }
1.385 matthew 7846: if (defined($gene)) { $names{'generation'} = $gene; }
1.592 www 7847: if ($email) {
7848: $email=~s/[^\w\@\.\-\,]//gs;
1.963 raeburn 7849: if ($email=~/\@/) { $names{'permanentemail'} = $email; }
1.592 www 7850: }
1.899 raeburn 7851: if ($uid) { $names{'id'} = $uid; }
1.989 raeburn 7852: if (defined($inststatus)) {
7853: $names{'inststatus'} = '';
7854: my ($usertypes,$typesorder) = &retrieve_inst_usertypes($udom);
7855: if (ref($usertypes) eq 'HASH') {
7856: my @okstatuses;
7857: foreach my $item (split(/:/,$inststatus)) {
7858: if (defined($usertypes->{$item})) {
7859: push(@okstatuses,$item);
7860: }
7861: }
7862: if (@okstatuses) {
7863: $names{'inststatus'} = join(':', map { &escape($_); } @okstatuses);
7864: }
7865: }
7866: }
1.1075 raeburn 7867: my $logmsg = $udom.', '.$uname.', '.$uid.', '.
1.963 raeburn 7868: $umode.', '.$first.', '.$middle.', '.
1.1075 raeburn 7869: $last.', '.$gene.', '.$email.', '.$inststatus;
1.963 raeburn 7870: if ($env{'user.name'} ne '' && $env{'user.domain'}) {
7871: $logmsg .= ' by '.$env{'user.name'}.' at '.$env{'user.domain'};
7872: } else {
7873: $logmsg .= ' during self creation';
7874: }
1.1075 raeburn 7875: my $changed;
7876: if ($newuser) {
7877: $changed = 1;
7878: } else {
7879: foreach my $field (@fields) {
7880: if ($names{$field} ne $oldnames{$field}) {
7881: $changed = 1;
7882: last;
7883: }
7884: }
7885: }
7886: unless ($changed) {
7887: $logmsg = 'No changes in user information needed for: '.$logmsg;
7888: &logthis($logmsg);
7889: return 'ok';
7890: }
7891: my $reply = &put('environment', \%names, $udom,$uname);
7892: if ($reply ne 'ok') {
7893: return 'error: '.$reply;
7894: }
1.1087 raeburn 7895: if ($names{'permanentemail'} ne $oldnames{'permanentemail'}) {
7896: &Apache::lonnet::devalidate_cache_new('emailscache',$uname.':'.$udom);
7897: }
1.1075 raeburn 7898: my $sqlresult = &update_allusers_table($uname,$udom,\%names);
7899: &devalidate_cache_new('namescache',$uname.':'.$udom);
7900: $logmsg = 'Success modifying user '.$logmsg;
1.963 raeburn 7901: &logthis($logmsg);
1.134 albertel 7902: return 'ok';
1.80 www 7903: }
7904:
1.81 www 7905: # -------------------------------------------------------------- Modify student
1.80 www 7906:
1.81 www 7907: sub modifystudent {
7908: my ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$usec,
1.957 raeburn 7909: $end,$start,$forceid,$desiredhome,$email,$type,$locktype,$cid,
1.990 raeburn 7910: $selfenroll,$context,$inststatus)=@_;
1.455 albertel 7911: if (!$cid) {
1.620 albertel 7912: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7913: return 'not_in_class';
7914: }
1.80 www 7915: }
7916: # --------------------------------------------------------------- Make the user
1.81 www 7917: my $reply=&modifyuser
1.209 matthew 7918: ($udom,$uname,$uid,$umode,$upass,$first,$middle,$last,$gene,$forceid,
1.990 raeburn 7919: $desiredhome,$email,$inststatus);
1.80 www 7920: unless ($reply eq 'ok') { return $reply; }
1.297 matthew 7921: # This will cause &modify_student_enrollment to get the uid from the
7922: # students environment
7923: $uid = undef if (!$forceid);
1.455 albertel 7924: $reply = &modify_student_enrollment($udom,$uname,$uid,$first,$middle,$last,
1.957 raeburn 7925: $gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context);
1.297 matthew 7926: return $reply;
7927: }
7928:
7929: sub modify_student_enrollment {
1.957 raeburn 7930: my ($udom,$uname,$uid,$first,$middle,$last,$gene,$usec,$end,$start,$type,$locktype,$cid,$selfenroll,$context) = @_;
1.455 albertel 7931: my ($cdom,$cnum,$chome);
7932: if (!$cid) {
1.620 albertel 7933: unless ($cid=$env{'request.course.id'}) {
1.455 albertel 7934: return 'not_in_class';
7935: }
1.620 albertel 7936: $cdom=$env{'course.'.$cid.'.domain'};
7937: $cnum=$env{'course.'.$cid.'.num'};
1.455 albertel 7938: } else {
7939: ($cdom,$cnum)=split(/_/,$cid);
7940: }
1.620 albertel 7941: $chome=$env{'course.'.$cid.'.home'};
1.455 albertel 7942: if (!$chome) {
1.457 raeburn 7943: $chome=&homeserver($cnum,$cdom);
1.297 matthew 7944: }
1.455 albertel 7945: if (!$chome) { return 'unknown_course'; }
1.297 matthew 7946: # Make sure the user exists
1.81 www 7947: my $uhome=&homeserver($uname,$udom);
7948: if (($uhome eq '') || ($uhome eq 'no_host')) {
7949: return 'error: no such user';
7950: }
1.297 matthew 7951: # Get student data if we were not given enough information
7952: if (!defined($first) || $first eq '' ||
7953: !defined($last) || $last eq '' ||
7954: !defined($uid) || $uid eq '' ||
7955: !defined($middle) || $middle eq '' ||
7956: !defined($gene) || $gene eq '') {
1.294 matthew 7957: # They did not supply us with enough data to enroll the student, so
7958: # we need to pick up more information.
1.297 matthew 7959: my %tmp = &get('environment',
1.294 matthew 7960: ['firstname','middlename','lastname', 'generation','id']
1.297 matthew 7961: ,$udom,$uname);
7962:
1.800 albertel 7963: #foreach my $key (keys(%tmp)) {
7964: # &logthis("key $key = ".$tmp{$key});
1.455 albertel 7965: #}
1.294 matthew 7966: $first = $tmp{'firstname'} if (!defined($first) || $first eq '');
7967: $middle = $tmp{'middlename'} if (!defined($middle) || $middle eq '');
7968: $last = $tmp{'lastname'} if (!defined($last) || $last eq '');
1.297 matthew 7969: $gene = $tmp{'generation'} if (!defined($gene) || $gene eq '');
1.294 matthew 7970: $uid = $tmp{'id'} if (!defined($uid) || $uid eq '');
7971: }
1.556 albertel 7972: my $fullname = &format_name($first,$middle,$last,$gene,'lastname');
1.1148 raeburn 7973: my $user = "$uname:$udom";
7974: my %old_entry = &Apache::lonnet::get('classlist',[$user],$cdom,$cnum);
1.487 albertel 7975: my $reply=cput('classlist',
1.1148 raeburn 7976: {$user =>
1.515 raeburn 7977: join(':',$end,$start,$uid,$usec,$fullname,$type,$locktype) },
1.487 albertel 7978: $cdom,$cnum);
1.1148 raeburn 7979: if (($reply eq 'ok') || ($reply eq 'delayed')) {
7980: &devalidate_getsection_cache($udom,$uname,$cid);
7981: } else {
1.81 www 7982: return 'error: '.$reply;
7983: }
1.297 matthew 7984: # Add student role to user
1.83 www 7985: my $uurl='/'.$cid;
1.81 www 7986: $uurl=~s/\_/\//g;
7987: if ($usec) {
7988: $uurl.='/'.$usec;
7989: }
1.1148 raeburn 7990: my $result = &assignrole($udom,$uname,$uurl,'st',$end,$start,undef,
7991: $selfenroll,$context);
7992: if ($result ne 'ok') {
7993: if ($old_entry{$user} ne '') {
7994: $reply = &cput('classlist',\%old_entry,$cdom,$cnum);
7995: } else {
7996: $reply = &del('classlist',[$user],$cdom,$cnum);
7997: }
7998: }
7999: return $result;
1.21 www 8000: }
8001:
1.556 albertel 8002: sub format_name {
8003: my ($firstname,$middlename,$lastname,$generation,$first)=@_;
8004: my $name;
8005: if ($first ne 'lastname') {
8006: $name=$firstname.' '.$middlename.' '.$lastname.' '.$generation;
8007: } else {
8008: if ($lastname=~/\S/) {
8009: $name.= $lastname.' '.$generation.', '.$firstname.' '.$middlename;
8010: $name=~s/\s+,/,/;
8011: } else {
8012: $name.= $firstname.' '.$middlename.' '.$generation;
8013: }
8014: }
8015: $name=~s/^\s+//;
8016: $name=~s/\s+$//;
8017: $name=~s/\s+/ /g;
8018: return $name;
8019: }
8020:
1.84 www 8021: # ------------------------------------------------- Write to course preferences
8022:
8023: sub writecoursepref {
8024: my ($courseid,%prefs)=@_;
8025: $courseid=~s/^\///;
8026: $courseid=~s/\_/\//g;
8027: my ($cdomain,$cnum)=split(/\//,$courseid);
8028: my $chome=homeserver($cnum,$cdomain);
8029: if (($chome eq '') || ($chome eq 'no_host')) {
8030: return 'error: no such course';
8031: }
8032: my $cstring='';
1.800 albertel 8033: foreach my $pref (keys(%prefs)) {
8034: $cstring.=&escape($pref).'='.&escape($prefs{$pref}).'&';
1.191 harris41 8035: }
1.84 www 8036: $cstring=~s/\&$//;
8037: return reply('put:'.$cdomain.':'.$cnum.':environment:'.$cstring,$chome);
8038: }
8039:
8040: # ---------------------------------------------------------- Make/modify course
8041:
8042: sub createcourse {
1.741 raeburn 8043: my ($udom,$description,$url,$course_server,$nonstandard,$inst_code,
1.1017 raeburn 8044: $course_owner,$crstype,$cnum,$context,$category)=@_;
1.84 www 8045: $url=&declutter($url);
8046: my $cid='';
1.1028 raeburn 8047: if ($context eq 'requestcourses') {
8048: my $can_create = 0;
8049: my ($ownername,$ownerdom) = split(':',$course_owner);
8050: if ($udom eq $ownerdom) {
8051: if (&usertools_access($ownername,$ownerdom,$category,undef,
8052: $context)) {
8053: $can_create = 1;
8054: }
8055: } else {
8056: my %userenv = &userenvironment($ownerdom,$ownername,'reqcrsotherdom.'.
8057: $category);
8058: if ($userenv{'reqcrsotherdom.'.$category} ne '') {
8059: my @curr = split(',',$userenv{'reqcrsotherdom.'.$category});
8060: if (@curr > 0) {
8061: my @options = qw(approval validate autolimit);
8062: my $optregex = join('|',@options);
8063: if (grep(/^\Q$udom\E:($optregex)(=?\d*)$/,@curr)) {
8064: $can_create = 1;
8065: }
8066: }
8067: }
8068: }
8069: if ($can_create) {
8070: unless ($ownername eq $env{'user.name'} && $ownerdom eq $env{'user.domain'}) {
8071: unless (&allowed('ccc',$udom)) {
8072: return 'refused';
8073: }
1.1017 raeburn 8074: }
8075: } else {
8076: return 'refused';
8077: }
1.1028 raeburn 8078: } elsif (!&allowed('ccc',$udom)) {
8079: return 'refused';
1.84 www 8080: }
1.1011 raeburn 8081: # --------------------------------------------------------------- Get Unique ID
8082: my $uname;
8083: if ($cnum =~ /^$match_courseid$/) {
8084: my $chome=&homeserver($cnum,$udom,'true');
8085: if (($chome eq '') || ($chome eq 'no_host')) {
8086: $uname = $cnum;
8087: } else {
1.1038 raeburn 8088: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8089: }
8090: } else {
1.1038 raeburn 8091: $uname = &generate_coursenum($udom,$crstype);
1.1011 raeburn 8092: }
8093: return $uname if ($uname =~ /^error/);
8094: # -------------------------------------------------- Check supplied server name
1.1052 raeburn 8095: if (!defined($course_server)) {
8096: if (defined(&domain($udom,'primary'))) {
8097: $course_server = &domain($udom,'primary');
8098: } else {
8099: $course_server = $env{'user.home'};
8100: }
8101: }
8102: my %host_servers =
8103: &Apache::lonnet::get_servers($udom,'library');
8104: unless ($host_servers{$course_server}) {
8105: return 'error: invalid home server for course: '.$course_server;
1.264 matthew 8106: }
1.84 www 8107: # ------------------------------------------------------------- Make the course
8108: my $reply=&reply('encrypt:makeuser:'.$udom.':'.$uname.':none::',
1.264 matthew 8109: $course_server);
1.84 www 8110: unless ($reply eq 'ok') { return 'error: '.$reply; }
1.1011 raeburn 8111: my $uhome=&homeserver($uname,$udom,'true');
1.84 www 8112: if (($uhome eq '') || ($uhome eq 'no_host')) {
8113: return 'error: no such course';
8114: }
1.271 www 8115: # ----------------------------------------------------------------- Course made
1.516 raeburn 8116: # log existence
1.1029 raeburn 8117: my $now = time;
1.918 raeburn 8118: my $newcourse = {
8119: $udom.'_'.$uname => {
1.921 raeburn 8120: description => $description,
8121: inst_code => $inst_code,
8122: owner => $course_owner,
8123: type => $crstype,
1.1029 raeburn 8124: creator => $env{'user.name'}.':'.
8125: $env{'user.domain'},
8126: created => $now,
8127: context => $context,
1.918 raeburn 8128: },
8129: };
1.921 raeburn 8130: &courseidput($udom,$newcourse,$uhome,'notime');
1.358 www 8131: # set toplevel url
1.271 www 8132: my $topurl=$url;
8133: unless ($nonstandard) {
8134: # ------------------------------------------ For standard courses, make top url
8135: my $mapurl=&clutter($url);
1.278 www 8136: if ($mapurl eq '/res/') { $mapurl=''; }
1.620 albertel 8137: $env{'form.initmap'}=(<<ENDINITMAP);
1.271 www 8138: <map>
8139: <resource id="1" type="start"></resource>
8140: <resource id="2" src="$mapurl"></resource>
8141: <resource id="3" type="finish"></resource>
8142: <link index="1" from="1" to="2"></link>
8143: <link index="2" from="2" to="3"></link>
8144: </map>
8145: ENDINITMAP
8146: $topurl=&declutter(
1.638 albertel 8147: &finishuserfileupload($uname,$udom,'initmap','default.sequence')
1.271 www 8148: );
8149: }
8150: # ----------------------------------------------------------- Write preferences
1.84 www 8151: &writecoursepref($udom.'_'.$uname,
1.1056 raeburn 8152: ('description' => $description,
8153: 'url' => $topurl,
8154: 'internal.creator' => $env{'user.name'}.':'.
8155: $env{'user.domain'},
8156: 'internal.created' => $now,
8157: 'internal.creationcontext' => $context)
8158: );
1.84 www 8159: return '/'.$udom.'/'.$uname;
8160: }
8161:
1.1011 raeburn 8162: # ------------------------------------------------------------------- Create ID
8163: sub generate_coursenum {
1.1038 raeburn 8164: my ($udom,$crstype) = @_;
1.1011 raeburn 8165: my $domdesc = &domain($udom);
8166: return 'error: invalid domain' if ($domdesc eq '');
1.1038 raeburn 8167: my $first;
8168: if ($crstype eq 'Community') {
8169: $first = '0';
8170: } else {
8171: $first = int(1+rand(9));
8172: }
8173: my $uname=$first.
1.1011 raeburn 8174: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8175: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8176: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8177: # ----------------------------------------------- Make sure that does not exist
8178: my $uhome=&homeserver($uname,$udom,'true');
8179: unless (($uhome eq '') || ($uhome eq 'no_host')) {
1.1038 raeburn 8180: if ($crstype eq 'Community') {
8181: $first = '0';
8182: } else {
8183: $first = int(1+rand(9));
8184: }
8185: $uname=$first.
1.1011 raeburn 8186: ('a'..'z','A'..'Z','0'..'9')[int(rand(62))].
8187: substr($$.time,0,5).unpack("H8",pack("I32",time)).
8188: unpack("H2",pack("I32",int(rand(255)))).$perlvar{'lonHostID'};
8189: $uhome=&homeserver($uname,$udom,'true');
8190: unless (($uhome eq '') || ($uhome eq 'no_host')) {
8191: return 'error: unable to generate unique course-ID';
8192: }
8193: }
8194: return $uname;
8195: }
8196:
1.813 albertel 8197: sub is_course {
1.1167 droeschl 8198: my ($cdom, $cnum) = scalar(@_) == 1 ?
8199: ($_[0] =~ /^($match_domain)_($match_courseid)$/) : @_;
8200:
8201: return unless $cdom and $cnum;
8202:
8203: my %courses = &courseiddump($cdom, '.', 1, '.', '.', $cnum, undef, undef,
8204: '.');
8205:
8206: return unless exists($courses{$cdom.'_'.$cnum});
8207: return wantarray ? ($cdom, $cnum) : $cdom.'_'.$cnum;
1.813 albertel 8208: }
8209:
1.1015 raeburn 8210: sub store_userdata {
8211: my ($storehash,$datakey,$namespace,$udom,$uname) = @_;
1.1013 raeburn 8212: my $result;
1.1016 raeburn 8213: if ($datakey ne '') {
1.1013 raeburn 8214: if (ref($storehash) eq 'HASH') {
1.1017 raeburn 8215: if ($udom eq '' || $uname eq '') {
8216: $udom = $env{'user.domain'};
8217: $uname = $env{'user.name'};
8218: }
8219: my $uhome=&homeserver($uname,$udom);
1.1013 raeburn 8220: if (($uhome eq '') || ($uhome eq 'no_host')) {
8221: $result = 'error: no_host';
8222: } else {
8223: $storehash->{'ip'} = $ENV{'REMOTE_ADDR'};
8224: $storehash->{'host'} = $perlvar{'lonHostID'};
8225:
8226: my $namevalue='';
8227: foreach my $key (keys(%{$storehash})) {
8228: $namevalue.=&escape($key).'='.&freeze_escape($$storehash{$key}).'&';
8229: }
8230: $namevalue=~s/\&$//;
1.1105 raeburn 8231: $result = &reply("store:$udom:$uname:$namespace:$datakey:".
8232: $namevalue,$uhome);
1.1013 raeburn 8233: }
8234: } else {
8235: $result = 'error: data to store was not a hash reference';
8236: }
8237: } else {
8238: $result= 'error: invalid requestkey';
8239: }
8240: return $result;
8241: }
8242:
1.21 www 8243: # ---------------------------------------------------------- Assign Custom Role
8244:
8245: sub assigncustomrole {
1.957 raeburn 8246: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8247: return &assignrole($udom,$uname,$url,'cr/'.$rdom.'/'.$rnam.'/'.$rolename,
1.957 raeburn 8248: $end,$start,$deleteflag,$selfenroll,$context);
1.21 www 8249: }
8250:
8251: # ----------------------------------------------------------------- Revoke Role
8252:
8253: sub revokerole {
1.957 raeburn 8254: my ($udom,$uname,$url,$role,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8255: my $now=time;
1.965 raeburn 8256: return &assignrole($udom,$uname,$url,$role,$now,undef,$deleteflag,$selfenroll,$context);
1.21 www 8257: }
8258:
8259: # ---------------------------------------------------------- Revoke Custom Role
8260:
8261: sub revokecustomrole {
1.957 raeburn 8262: my ($udom,$uname,$url,$rdom,$rnam,$rolename,$deleteflag,$selfenroll,$context)=@_;
1.21 www 8263: my $now=time;
1.357 www 8264: return &assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$now,
1.957 raeburn 8265: $deleteflag,$selfenroll,$context);
1.17 www 8266: }
8267:
1.533 banghart 8268: # ------------------------------------------------------------ Disk usage
1.535 albertel 8269: sub diskusage {
1.955 raeburn 8270: my ($udom,$uname,$directorypath,$getpropath)=@_;
8271: $directorypath =~ s/\/$//;
8272: my $listing=&reply('du2:'.&escape($directorypath).':'
8273: .&escape($getpropath).':'.&escape($uname).':'
8274: .&escape($udom),homeserver($uname,$udom));
8275: if ($listing eq 'unknown_cmd') {
8276: if ($getpropath) {
8277: $directorypath = &propath($udom,$uname).'/'.$directorypath;
8278: }
8279: $listing = &reply('du:'.$directorypath,homeserver($uname,$udom));
8280: }
1.514 albertel 8281: return $listing;
1.512 banghart 8282: }
8283:
1.566 banghart 8284: sub is_locked {
1.1096 raeburn 8285: my ($file_name, $domain, $user, $which) = @_;
1.566 banghart 8286: my @check;
8287: my $is_locked;
1.1093 raeburn 8288: push (@check,$file_name);
1.613 albertel 8289: my %locked = &get('file_permissions',\@check,
1.620 albertel 8290: $env{'user.domain'},$env{'user.name'});
1.615 albertel 8291: my ($tmp)=keys(%locked);
8292: if ($tmp=~/^error:/) { undef(%locked); }
1.745 raeburn 8293:
1.566 banghart 8294: if (ref($locked{$file_name}) eq 'ARRAY') {
1.745 raeburn 8295: $is_locked = 'false';
8296: foreach my $entry (@{$locked{$file_name}}) {
1.1096 raeburn 8297: if (ref($entry) eq 'ARRAY') {
1.746 raeburn 8298: $is_locked = 'true';
1.1096 raeburn 8299: if (ref($which) eq 'ARRAY') {
8300: push(@{$which},$entry);
8301: } else {
8302: last;
8303: }
1.745 raeburn 8304: }
8305: }
1.566 banghart 8306: } else {
8307: $is_locked = 'false';
8308: }
1.1093 raeburn 8309: return $is_locked;
1.566 banghart 8310: }
8311:
1.759 albertel 8312: sub declutter_portfile {
8313: my ($file) = @_;
1.833 albertel 8314: $file =~ s{^(/portfolio/|portfolio/)}{/};
1.759 albertel 8315: return $file;
8316: }
8317:
1.559 banghart 8318: # ------------------------------------------------------------- Mark as Read Only
8319:
8320: sub mark_as_readonly {
8321: my ($domain,$user,$files,$what) = @_;
1.613 albertel 8322: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8323: my ($tmp)=keys(%current_permissions);
8324: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.560 banghart 8325: foreach my $file (@{$files}) {
1.759 albertel 8326: $file = &declutter_portfile($file);
1.561 banghart 8327: push(@{$current_permissions{$file}},$what);
1.559 banghart 8328: }
1.613 albertel 8329: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8330: return;
8331: }
8332:
1.572 banghart 8333: # ------------------------------------------------------------Save Selected Files
8334:
8335: sub save_selected_files {
8336: my ($user, $path, @files) = @_;
8337: my $filename = $user."savedfiles";
1.573 banghart 8338: my @other_files = &files_not_in_path($user, $path);
1.871 albertel 8339: open (OUT, '>'.$tmpdir.$filename);
1.573 banghart 8340: foreach my $file (@files) {
1.620 albertel 8341: print (OUT $env{'form.currentpath'}.$file."\n");
1.573 banghart 8342: }
8343: foreach my $file (@other_files) {
1.574 banghart 8344: print (OUT $file."\n");
1.572 banghart 8345: }
1.574 banghart 8346: close (OUT);
1.572 banghart 8347: return 'ok';
8348: }
8349:
1.574 banghart 8350: sub clear_selected_files {
8351: my ($user) = @_;
8352: my $filename = $user."savedfiles";
1.1117 foxr 8353: open (OUT, '>'.LONCAPA::tempdir().$filename);
1.574 banghart 8354: print (OUT undef);
8355: close (OUT);
8356: return ("ok");
8357: }
8358:
1.572 banghart 8359: sub files_in_path {
8360: my ($user, $path) = @_;
8361: my $filename = $user."savedfiles";
8362: my %return_files;
1.1117 foxr 8363: open (IN, '<'.LONCAPA::tempdir().$filename);
1.573 banghart 8364: while (my $line_in = <IN>) {
1.574 banghart 8365: chomp ($line_in);
8366: my @paths_and_file = split (m!/!, $line_in);
8367: my $file_part = pop (@paths_and_file);
8368: my $path_part = join ('/', @paths_and_file);
1.573 banghart 8369: $path_part.='/';
8370: my $path_and_file = $path_part.$file_part;
8371: if ($path_part eq $path) {
8372: $return_files{$file_part}= 'selected';
8373: }
8374: }
1.574 banghart 8375: close (IN);
8376: return (\%return_files);
1.572 banghart 8377: }
8378:
8379: # called in portfolio select mode, to show files selected NOT in current directory
8380: sub files_not_in_path {
8381: my ($user, $path) = @_;
8382: my $filename = $user."savedfiles";
8383: my @return_files;
8384: my $path_part;
1.1117 foxr 8385: open(IN, '<'.LONCAPA::.$filename);
1.800 albertel 8386: while (my $line = <IN>) {
1.572 banghart 8387: #ok, I know it's clunky, but I want it to work
1.800 albertel 8388: my @paths_and_file = split(m|/|, $line);
8389: my $file_part = pop(@paths_and_file);
8390: chomp($file_part);
8391: my $path_part = join('/', @paths_and_file);
1.572 banghart 8392: $path_part .= '/';
8393: my $path_and_file = $path_part.$file_part;
8394: if ($path_part ne $path) {
1.800 albertel 8395: push(@return_files, ($path_and_file));
1.572 banghart 8396: }
8397: }
1.800 albertel 8398: close(OUT);
1.574 banghart 8399: return (@return_files);
1.572 banghart 8400: }
8401:
1.745 raeburn 8402: #----------------------------------------------Get portfolio file permissions
1.629 banghart 8403:
1.745 raeburn 8404: sub get_portfile_permissions {
8405: my ($domain,$user) = @_;
1.613 albertel 8406: my %current_permissions = &dump('file_permissions',$domain,$user);
1.615 albertel 8407: my ($tmp)=keys(%current_permissions);
8408: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8409: return \%current_permissions;
8410: }
8411:
8412: #---------------------------------------------Get portfolio file access controls
8413:
1.749 raeburn 8414: sub get_access_controls {
1.745 raeburn 8415: my ($current_permissions,$group,$file) = @_;
1.769 albertel 8416: my %access;
8417: my $real_file = $file;
8418: $file =~ s/\.meta$//;
1.745 raeburn 8419: if (defined($file)) {
1.749 raeburn 8420: if (ref($$current_permissions{$file."\0".'accesscontrol'}) eq 'HASH') {
8421: foreach my $control (keys(%{$$current_permissions{$file."\0".'accesscontrol'}})) {
1.769 albertel 8422: $access{$real_file}{$control} = $$current_permissions{$file."\0".$control};
1.749 raeburn 8423: }
8424: }
1.745 raeburn 8425: } else {
1.749 raeburn 8426: foreach my $key (keys(%{$current_permissions})) {
8427: if ($key =~ /\0accesscontrol$/) {
8428: if (defined($group)) {
8429: if ($key !~ m-^\Q$group\E/-) {
8430: next;
8431: }
8432: }
8433: my ($fullpath) = split(/\0/,$key);
8434: if (ref($$current_permissions{$key}) eq 'HASH') {
8435: foreach my $control (keys(%{$$current_permissions{$key}})) {
8436: $access{$fullpath}{$control}=$$current_permissions{$fullpath."\0".$control};
8437: }
8438: }
8439: }
8440: }
8441: }
8442: return %access;
8443: }
8444:
8445: sub modify_access_controls {
8446: my ($file_name,$changes,$domain,$user)=@_;
8447: my ($outcome,$deloutcome);
8448: my %store_permissions;
8449: my %new_values;
8450: my %new_control;
8451: my %translation;
8452: my @deletions = ();
8453: my $now = time;
8454: if (exists($$changes{'activate'})) {
8455: if (ref($$changes{'activate'}) eq 'HASH') {
8456: my @newitems = sort(keys(%{$$changes{'activate'}}));
8457: my $numnew = scalar(@newitems);
8458: for (my $i=0; $i<$numnew; $i++) {
8459: my $newkey = $newitems[$i];
8460: my $newid = &Apache::loncommon::get_cgi_id();
1.797 raeburn 8461: if ($newkey =~ /^\d+:/) {
8462: $newkey =~ s/^(\d+)/$newid/;
8463: $translation{$1} = $newid;
8464: } elsif ($newkey =~ /^\d+_\d+_\d+:/) {
8465: $newkey =~ s/^(\d+_\d+_\d+)/$newid/;
8466: $translation{$1} = $newid;
8467: }
1.749 raeburn 8468: $new_values{$file_name."\0".$newkey} =
8469: $$changes{'activate'}{$newitems[$i]};
8470: $new_control{$newkey} = $now;
8471: }
8472: }
8473: }
8474: my %todelete;
8475: my %changed_items;
8476: foreach my $action ('delete','update') {
8477: if (exists($$changes{$action})) {
8478: if (ref($$changes{$action}) eq 'HASH') {
8479: foreach my $key (keys(%{$$changes{$action}})) {
8480: my ($itemnum) = ($key =~ /^([^:]+):/);
8481: if ($action eq 'delete') {
8482: $todelete{$itemnum} = 1;
8483: } else {
8484: $changed_items{$itemnum} = $key;
8485: }
8486: }
1.745 raeburn 8487: }
8488: }
1.749 raeburn 8489: }
8490: # get lock on access controls for file.
8491: my $lockhash = {
8492: $file_name."\0".'locked_access_records' => $env{'user.name'}.
8493: ':'.$env{'user.domain'},
8494: };
8495: my $tries = 0;
8496: my $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8497:
8498: while (($gotlock ne 'ok') && $tries <3) {
8499: $tries ++;
8500: sleep 1;
8501: $gotlock = &newput('file_permissions',$lockhash,$domain,$user);
8502: }
8503: if ($gotlock eq 'ok') {
8504: my %curr_permissions = &dump('file_permissions',$domain,$user,$file_name);
8505: my ($tmp)=keys(%curr_permissions);
8506: if ($tmp=~/^error:/) { undef(%curr_permissions); }
8507: if (exists($curr_permissions{$file_name."\0".'accesscontrol'})) {
8508: my $curr_controls = $curr_permissions{$file_name."\0".'accesscontrol'};
8509: if (ref($curr_controls) eq 'HASH') {
8510: foreach my $control_item (keys(%{$curr_controls})) {
8511: my ($itemnum) = ($control_item =~ /^([^:]+):/);
8512: if (defined($todelete{$itemnum})) {
8513: push(@deletions,$file_name."\0".$control_item);
8514: } else {
8515: if (defined($changed_items{$itemnum})) {
8516: $new_control{$changed_items{$itemnum}} = $now;
8517: push(@deletions,$file_name."\0".$control_item);
8518: $new_values{$file_name."\0".$changed_items{$itemnum}} = $$changes{'update'}{$changed_items{$itemnum}};
8519: } else {
8520: $new_control{$control_item} = $$curr_controls{$control_item};
8521: }
8522: }
1.745 raeburn 8523: }
8524: }
8525: }
1.970 raeburn 8526: my ($group);
8527: if (&is_course($domain,$user)) {
8528: ($group,my $file) = split(/\//,$file_name,2);
8529: }
1.749 raeburn 8530: $deloutcome = &del('file_permissions',\@deletions,$domain,$user);
8531: $new_values{$file_name."\0".'accesscontrol'} = \%new_control;
8532: $outcome = &put('file_permissions',\%new_values,$domain,$user);
8533: # remove lock
8534: my @del_lock = ($file_name."\0".'locked_access_records');
8535: my $dellockoutcome = &del('file_permissions',\@del_lock,$domain,$user);
1.818 raeburn 8536: my $sqlresult =
1.970 raeburn 8537: &update_portfolio_table($user,$domain,$file_name,'portfolio_access',
1.818 raeburn 8538: $group);
1.749 raeburn 8539: } else {
8540: $outcome = "error: could not obtain lockfile\n";
1.745 raeburn 8541: }
1.749 raeburn 8542: return ($outcome,$deloutcome,\%new_values,\%translation);
1.745 raeburn 8543: }
8544:
1.827 raeburn 8545: sub make_public_indefinitely {
8546: my ($requrl) = @_;
8547: my $now = time;
8548: my $action = 'activate';
8549: my $aclnum = 0;
8550: if (&is_portfolio_url($requrl)) {
8551: my (undef,$udom,$unum,$file_name,$group) =
8552: &parse_portfolio_url($requrl);
8553: my $current_perms = &get_portfile_permissions($udom,$unum);
8554: my %access_controls = &get_access_controls($current_perms,
8555: $group,$file_name);
8556: foreach my $key (keys(%{$access_controls{$file_name}})) {
8557: my ($num,$scope,$end,$start) =
8558: ($key =~ /^([^:]+):([a-z]+)_(\d*)_?(\d*)$/);
8559: if ($scope eq 'public') {
8560: if ($start <= $now && $end == 0) {
8561: $action = 'none';
8562: } else {
8563: $action = 'update';
8564: $aclnum = $num;
8565: }
8566: last;
8567: }
8568: }
8569: if ($action eq 'none') {
8570: return 'ok';
8571: } else {
8572: my %changes;
8573: my $newend = 0;
8574: my $newstart = $now;
8575: my $newkey = $aclnum.':public_'.$newend.'_'.$newstart;
8576: $changes{$action}{$newkey} = {
8577: type => 'public',
8578: time => {
8579: start => $newstart,
8580: end => $newend,
8581: },
8582: };
8583: my ($outcome,$deloutcome,$new_values,$translation) =
8584: &modify_access_controls($file_name,\%changes,$udom,$unum);
8585: return $outcome;
8586: }
8587: } else {
8588: return 'invalid';
8589: }
8590: }
8591:
1.745 raeburn 8592: #------------------------------------------------------Get Marked as Read Only
8593:
8594: sub get_marked_as_readonly {
8595: my ($domain,$user,$what,$group) = @_;
8596: my $current_permissions = &get_portfile_permissions($domain,$user);
1.563 banghart 8597: my @readonly_files;
1.629 banghart 8598: my $cmp1=$what;
8599: if (ref($what)) { $cmp1=join('',@{$what}) };
1.745 raeburn 8600: while (my ($file_name,$value) = each(%{$current_permissions})) {
8601: if (defined($group)) {
8602: if ($file_name !~ m-^\Q$group\E/-) {
8603: next;
8604: }
8605: }
1.561 banghart 8606: if (ref($value) eq "ARRAY"){
8607: foreach my $stored_what (@{$value}) {
1.629 banghart 8608: my $cmp2=$stored_what;
1.759 albertel 8609: if (ref($stored_what) eq 'ARRAY') {
1.746 raeburn 8610: $cmp2=join('',@{$stored_what});
1.745 raeburn 8611: }
1.629 banghart 8612: if ($cmp1 eq $cmp2) {
1.561 banghart 8613: push(@readonly_files, $file_name);
1.745 raeburn 8614: last;
1.563 banghart 8615: } elsif (!defined($what)) {
8616: push(@readonly_files, $file_name);
1.745 raeburn 8617: last;
1.561 banghart 8618: }
8619: }
1.745 raeburn 8620: }
1.561 banghart 8621: }
8622: return @readonly_files;
8623: }
1.577 banghart 8624: #-----------------------------------------------------------Get Marked as Read Only Hash
1.561 banghart 8625:
1.577 banghart 8626: sub get_marked_as_readonly_hash {
1.745 raeburn 8627: my ($current_permissions,$group,$what) = @_;
1.577 banghart 8628: my %readonly_files;
1.745 raeburn 8629: while (my ($file_name,$value) = each(%{$current_permissions})) {
8630: if (defined($group)) {
8631: if ($file_name !~ m-^\Q$group\E/-) {
8632: next;
8633: }
8634: }
1.577 banghart 8635: if (ref($value) eq "ARRAY"){
8636: foreach my $stored_what (@{$value}) {
1.745 raeburn 8637: if (ref($stored_what) eq 'ARRAY') {
1.750 banghart 8638: foreach my $lock_descriptor(@{$stored_what}) {
8639: if ($lock_descriptor eq 'graded') {
8640: $readonly_files{$file_name} = 'graded';
8641: } elsif ($lock_descriptor eq 'handback') {
8642: $readonly_files{$file_name} = 'handback';
8643: } else {
8644: if (!exists($readonly_files{$file_name})) {
8645: $readonly_files{$file_name} = 'locked';
8646: }
8647: }
1.745 raeburn 8648: }
1.750 banghart 8649: }
1.577 banghart 8650: }
8651: }
8652: }
8653: return %readonly_files;
8654: }
1.559 banghart 8655: # ------------------------------------------------------------ Unmark as Read Only
8656:
8657: sub unmark_as_readonly {
1.629 banghart 8658: # unmarks $file_name (if $file_name is defined), or all files locked by $what
8659: # for portfolio submissions, $what contains [$symb,$crsid]
1.745 raeburn 8660: my ($domain,$user,$what,$file_name,$group) = @_;
1.759 albertel 8661: $file_name = &declutter_portfile($file_name);
1.634 albertel 8662: my $symb_crs = $what;
8663: if (ref($what)) { $symb_crs=join('',@$what); }
1.745 raeburn 8664: my %current_permissions = &dump('file_permissions',$domain,$user,$group);
1.615 albertel 8665: my ($tmp)=keys(%current_permissions);
8666: if ($tmp=~/^error:/) { undef(%current_permissions); }
1.745 raeburn 8667: my @readonly_files = &get_marked_as_readonly($domain,$user,$what,$group);
1.650 albertel 8668: foreach my $file (@readonly_files) {
1.759 albertel 8669: my $clean_file = &declutter_portfile($file);
8670: if (defined($file_name) && ($file_name ne $clean_file)) { next; }
1.650 albertel 8671: my $current_locks = $current_permissions{$file};
1.563 banghart 8672: my @new_locks;
8673: my @del_keys;
8674: if (ref($current_locks) eq "ARRAY"){
8675: foreach my $locker (@{$current_locks}) {
1.632 albertel 8676: my $compare=$locker;
1.749 raeburn 8677: if (ref($locker) eq 'ARRAY') {
1.745 raeburn 8678: $compare=join('',@{$locker});
1.746 raeburn 8679: if ($compare ne $symb_crs) {
8680: push(@new_locks, $locker);
8681: }
1.563 banghart 8682: }
8683: }
1.650 albertel 8684: if (scalar(@new_locks) > 0) {
1.563 banghart 8685: $current_permissions{$file} = \@new_locks;
8686: } else {
8687: push(@del_keys, $file);
1.613 albertel 8688: &del('file_permissions',\@del_keys, $domain, $user);
1.650 albertel 8689: delete($current_permissions{$file});
1.563 banghart 8690: }
8691: }
1.561 banghart 8692: }
1.613 albertel 8693: &put('file_permissions',\%current_permissions,$domain,$user);
1.559 banghart 8694: return;
8695: }
1.512 banghart 8696:
1.17 www 8697: # ------------------------------------------------------------ Directory lister
8698:
8699: sub dirlist {
1.955 raeburn 8700: my ($uri,$userdomain,$username,$getpropath,$getuserdir,$alternateRoot)=@_;
1.18 www 8701: $uri=~s/^\///;
8702: $uri=~s/\/$//;
1.253 stredwic 8703: my ($udom, $uname);
1.955 raeburn 8704: if ($getuserdir) {
1.253 stredwic 8705: $udom = $userdomain;
8706: $uname = $username;
1.955 raeburn 8707: } else {
8708: (undef,$udom,$uname)=split(/\//,$uri);
8709: if(defined($userdomain)) {
8710: $udom = $userdomain;
8711: }
8712: if(defined($username)) {
8713: $uname = $username;
8714: }
1.253 stredwic 8715: }
1.955 raeburn 8716: my ($dirRoot,$listing,@listing_results);
1.253 stredwic 8717:
1.955 raeburn 8718: $dirRoot = $perlvar{'lonDocRoot'};
8719: if (defined($getpropath)) {
8720: $dirRoot = &propath($udom,$uname);
1.253 stredwic 8721: $dirRoot =~ s/\/$//;
1.955 raeburn 8722: } elsif (defined($getuserdir)) {
8723: my $subdir=$uname.'__';
8724: $subdir =~ s/(.)(.)(.).*/$1\/$2\/$3/;
8725: $dirRoot = $Apache::lonnet::perlvar{'lonUsersDir'}
8726: ."/$udom/$subdir/$uname";
8727: } elsif (defined($alternateRoot)) {
8728: $dirRoot = $alternateRoot;
1.751 banghart 8729: }
1.253 stredwic 8730:
8731: if($udom) {
8732: if($uname) {
1.1135 raeburn 8733: my $uhome = &homeserver($uname,$udom);
1.1136 raeburn 8734: if ($uhome eq 'no_host') {
8735: return ([],'no_host');
8736: }
1.955 raeburn 8737: $listing = &reply('ls3:'.&escape('/'.$uri).':'.$getpropath.':'
1.956 raeburn 8738: .$getuserdir.':'.&escape($dirRoot)
1.1135 raeburn 8739: .':'.&escape($uname).':'.&escape($udom),$uhome);
1.955 raeburn 8740: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8741: $listing = &reply('ls2:'.$dirRoot.'/'.$uri,$uhome);
1.955 raeburn 8742: } else {
8743: @listing_results = map { &unescape($_); } split(/:/,$listing);
8744: }
1.605 matthew 8745: if ($listing eq 'unknown_cmd') {
1.1135 raeburn 8746: $listing = &reply('ls:'.$dirRoot.'/'.$uri,$uhome);
1.605 matthew 8747: @listing_results = split(/:/,$listing);
8748: } else {
8749: @listing_results = map { &unescape($_); } split(/:/,$listing);
8750: }
1.1135 raeburn 8751: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
1.1136 raeburn 8752: ($listing eq 'rejected') || ($listing eq 'refused') ||
8753: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8754: return ([],$listing);
8755: } else {
8756: return (\@listing_results);
1.1135 raeburn 8757: }
1.955 raeburn 8758: } elsif(!$alternateRoot) {
1.1136 raeburn 8759: my (%allusers,%listerror);
1.841 albertel 8760: my %servers = &get_servers($udom,'library');
1.955 raeburn 8761: foreach my $tryserver (keys(%servers)) {
8762: $listing = &reply('ls3:'.&escape("/res/$udom").':::::'.
8763: &escape($udom),$tryserver);
8764: if ($listing eq 'unknown_cmd') {
8765: $listing = &reply('ls2:'.$perlvar{'lonDocRoot'}.'/res/'.
8766: $udom, $tryserver);
8767: } else {
8768: @listing_results = map { &unescape($_); } split(/:/,$listing);
8769: }
1.841 albertel 8770: if ($listing eq 'unknown_cmd') {
8771: $listing = &reply('ls:'.$perlvar{'lonDocRoot'}.'/res/'.
8772: $udom, $tryserver);
8773: @listing_results = split(/:/,$listing);
8774: } else {
8775: @listing_results =
8776: map { &unescape($_); } split(/:/,$listing);
8777: }
1.1136 raeburn 8778: if (($listing eq 'no_such_host') || ($listing eq 'con_lost') ||
8779: ($listing eq 'rejected') || ($listing eq 'refused') ||
8780: ($listing eq 'no_such_dir') || ($listing eq 'empty')) {
8781: $listerror{$tryserver} = $listing;
8782: } else {
1.841 albertel 8783: foreach my $line (@listing_results) {
8784: my ($entry) = split(/&/,$line,2);
8785: $allusers{$entry} = 1;
8786: }
8787: }
1.253 stredwic 8788: }
1.1136 raeburn 8789: my @alluserslist=();
1.800 albertel 8790: foreach my $user (sort(keys(%allusers))) {
1.1136 raeburn 8791: push(@alluserslist,$user.'&user');
1.253 stredwic 8792: }
1.1136 raeburn 8793: return (\@alluserslist);
1.253 stredwic 8794: } else {
1.1136 raeburn 8795: return ([],'missing username');
1.253 stredwic 8796: }
1.955 raeburn 8797: } elsif(!defined($getpropath)) {
1.1136 raeburn 8798: my $path = $perlvar{'lonDocRoot'}.'/res/';
8799: my @all_domains = map { $path.$_.'/&domain'; } (sort(&all_domains()));
8800: return (\@all_domains);
1.955 raeburn 8801: } else {
1.1136 raeburn 8802: return ([],'missing domain');
1.275 stredwic 8803: }
8804: }
8805:
8806: # --------------------------------------------- GetFileTimestamp
8807: # This function utilizes dirlist and returns the date stamp for
8808: # when it was last modified. It will also return an error of -1
8809: # if an error occurs
8810:
8811: sub GetFileTimestamp {
1.955 raeburn 8812: my ($studentDomain,$studentName,$filename,$getuserdir)=@_;
1.807 albertel 8813: $studentDomain = &LONCAPA::clean_domain($studentDomain);
8814: $studentName = &LONCAPA::clean_username($studentName);
1.1136 raeburn 8815: my ($fileref,$error) = &dirlist($filename,$studentDomain,$studentName,
8816: undef,$getuserdir);
8817: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8818: return -1;
8819: }
8820: if (ref($fileref) eq 'ARRAY') {
8821: my @stats = split('&',$fileref->[0]);
1.375 matthew 8822: # @stats contains first the filename, then the stat output
8823: return $stats[10]; # so this is 10 instead of 9.
1.275 stredwic 8824: } else {
8825: return -1;
1.253 stredwic 8826: }
1.26 www 8827: }
8828:
1.712 albertel 8829: sub stat_file {
8830: my ($uri) = @_;
1.787 albertel 8831: $uri = &clutter_with_no_wrapper($uri);
1.722 albertel 8832:
1.955 raeburn 8833: my ($udom,$uname,$file);
1.712 albertel 8834: if ($uri =~ m-^/(uploaded|editupload)/-) {
8835: ($udom,$uname,$file) =
1.811 albertel 8836: ($uri =~ m-/(?:uploaded|editupload)/?($match_domain)/?($match_name)/?(.*)-);
1.712 albertel 8837: $file = 'userfiles/'.$file;
8838: }
8839: if ($uri =~ m-^/res/-) {
8840: ($udom,$uname) =
1.807 albertel 8841: ($uri =~ m-/(?:res)/?($match_domain)/?($match_username)/-);
1.712 albertel 8842: $file = $uri;
8843: }
8844:
8845: if (!$udom || !$uname || !$file) {
8846: # unable to handle the uri
8847: return ();
8848: }
1.956 raeburn 8849: my $getpropath;
8850: if ($file =~ /^userfiles\//) {
8851: $getpropath = 1;
8852: }
1.1136 raeburn 8853: my ($listref,$error) = &dirlist($file,$udom,$uname,$getpropath);
8854: if (($error eq 'empty') || ($error eq 'no_such_dir')) {
8855: return ();
8856: } else {
8857: if (ref($listref) eq 'ARRAY') {
8858: my @stats = split('&',$listref->[0]);
8859: shift(@stats); #filename is first
8860: return @stats;
8861: }
1.712 albertel 8862: }
8863: return ();
8864: }
8865:
1.26 www 8866: # -------------------------------------------------------- Value of a Condition
8867:
1.713 albertel 8868: # gets the value of a specific preevaluated condition
8869: # stored in the string $env{user.state.<cid>}
8870: # or looks up a condition reference in the bighash and if if hasn't
8871: # already been evaluated recurses into docondval to get the value of
8872: # the condition, then memoizing it to
8873: # $env{user.state.<cid>.<condition>}
1.40 www 8874: sub directcondval {
8875: my $number=shift;
1.620 albertel 8876: if (!defined($env{'user.state.'.$env{'request.course.id'}})) {
1.555 albertel 8877: &Apache::lonuserstate::evalstate();
8878: }
1.713 albertel 8879: if (exists($env{'user.state.'.$env{'request.course.id'}.".$number"})) {
8880: return $env{'user.state.'.$env{'request.course.id'}.".$number"};
8881: } elsif ($number =~ /^_/) {
8882: my $sub_condition;
8883: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
8884: &GDBM_READER(),0640)) {
8885: $sub_condition=$bighash{'conditions'.$number};
8886: untie(%bighash);
8887: }
8888: my $value = &docondval($sub_condition);
1.949 raeburn 8889: &appenv({'user.state.'.$env{'request.course.id'}.".$number" => $value});
1.713 albertel 8890: return $value;
8891: }
1.620 albertel 8892: if ($env{'user.state.'.$env{'request.course.id'}}) {
8893: return substr($env{'user.state.'.$env{'request.course.id'}},$number,1);
1.40 www 8894: } else {
8895: return 2;
8896: }
8897: }
8898:
1.713 albertel 8899: # get the collection of conditions for this resource
1.26 www 8900: sub condval {
8901: my $condidx=shift;
1.54 www 8902: my $allpathcond='';
1.713 albertel 8903: foreach my $cond (split(/\|/,$condidx)) {
8904: if (defined($env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond})) {
8905: $allpathcond.=
8906: '('.$env{'acc.cond.'.$env{'request.course.id'}.'.'.$cond}.')|';
8907: }
1.191 harris41 8908: }
1.54 www 8909: $allpathcond=~s/\|$//;
1.713 albertel 8910: return &docondval($allpathcond);
8911: }
8912:
8913: #evaluates an expression of conditions
8914: sub docondval {
8915: my ($allpathcond) = @_;
8916: my $result=0;
8917: if ($env{'request.course.id'}
8918: && defined($allpathcond)) {
8919: my $operand='|';
8920: my @stack;
8921: foreach my $chunk ($allpathcond=~/(\d+|_\d+\.\d+|\(|\)|\&|\|)/g) {
8922: if ($chunk eq '(') {
8923: push @stack,($operand,$result);
8924: } elsif ($chunk eq ')') {
8925: my $before=pop @stack;
8926: if (pop @stack eq '&') {
8927: $result=$result>$before?$before:$result;
8928: } else {
8929: $result=$result>$before?$result:$before;
8930: }
8931: } elsif (($chunk eq '&') || ($chunk eq '|')) {
8932: $operand=$chunk;
8933: } else {
8934: my $new=directcondval($chunk);
8935: if ($operand eq '&') {
8936: $result=$result>$new?$new:$result;
8937: } else {
8938: $result=$result>$new?$result:$new;
8939: }
8940: }
8941: }
1.26 www 8942: }
8943: return $result;
1.421 albertel 8944: }
8945:
8946: # ---------------------------------------------------- Devalidate courseresdata
8947:
8948: sub devalidatecourseresdata {
8949: my ($coursenum,$coursedomain)=@_;
8950: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8951: &devalidate_cache_new('courseres',$hashid);
1.28 www 8952: }
8953:
1.763 www 8954:
1.200 www 8955: # --------------------------------------------------- Course Resourcedata Query
1.878 foxr 8956: #
8957: # Parameters:
8958: # $coursenum - Number of the course.
8959: # $coursedomain - Domain at which the course was created.
8960: # Returns:
8961: # A hash of the course parameters along (I think) with timestamps
8962: # and version info.
1.877 foxr 8963:
1.624 albertel 8964: sub get_courseresdata {
8965: my ($coursenum,$coursedomain)=@_;
1.200 www 8966: my $coursehom=&homeserver($coursenum,$coursedomain);
8967: my $hashid=$coursenum.':'.$coursedomain;
1.599 albertel 8968: my ($result,$cached)=&is_cached_new('courseres',$hashid);
1.624 albertel 8969: my %dumpreply;
1.417 albertel 8970: unless (defined($cached)) {
1.624 albertel 8971: %dumpreply=&dump('resourcedata',$coursedomain,$coursenum);
1.417 albertel 8972: $result=\%dumpreply;
1.251 albertel 8973: my ($tmp) = keys(%dumpreply);
8974: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
1.599 albertel 8975: &do_cache_new('courseres',$hashid,$result,600);
1.306 albertel 8976: } elsif ($tmp =~ /^(con_lost|no_such_host)/) {
8977: return $tmp;
1.416 albertel 8978: } elsif ($tmp =~ /^(error)/) {
1.417 albertel 8979: $result=undef;
1.599 albertel 8980: &do_cache_new('courseres',$hashid,$result,600);
1.250 albertel 8981: }
8982: }
1.624 albertel 8983: return $result;
8984: }
8985:
1.633 albertel 8986: sub devalidateuserresdata {
8987: my ($uname,$udom)=@_;
8988: my $hashid="$udom:$uname";
8989: &devalidate_cache_new('userres',$hashid);
8990: }
8991:
1.624 albertel 8992: sub get_userresdata {
8993: my ($uname,$udom)=@_;
8994: #most student don\'t have any data set, check if there is some data
8995: if (&EXT_cache_status($udom,$uname)) { return undef; }
8996:
8997: my $hashid="$udom:$uname";
8998: my ($result,$cached)=&is_cached_new('userres',$hashid);
8999: if (!defined($cached)) {
9000: my %resourcedata=&dump('resourcedata',$udom,$uname);
9001: $result=\%resourcedata;
9002: &do_cache_new('userres',$hashid,$result,600);
9003: }
9004: my ($tmp)=keys(%$result);
9005: if (($tmp!~/^error\:/) && ($tmp!~/^con_lost/)) {
9006: return $result;
9007: }
9008: #error 2 occurs when the .db doesn't exist
9009: if ($tmp!~/error: 2 /) {
1.672 albertel 9010: &logthis("<font color=\"blue\">WARNING:".
1.624 albertel 9011: " Trying to get resource data for ".
9012: $uname." at ".$udom.": ".
9013: $tmp."</font>");
9014: } elsif ($tmp=~/error: 2 /) {
1.633 albertel 9015: #&EXT_cache_set($udom,$uname);
9016: &do_cache_new('userres',$hashid,undef,600);
1.636 albertel 9017: undef($tmp); # not really an error so don't send it back
1.624 albertel 9018: }
9019: return $tmp;
9020: }
1.879 foxr 9021: #----------------------------------------------- resdata - return resource data
9022: # Purpose:
9023: # Return resource data for either users or for a course.
9024: # Parameters:
9025: # $name - Course/user name.
9026: # $domain - Name of the domain the user/course is registered on.
9027: # $type - Type of thing $name is (must be 'course' or 'user'
9028: # @which - Array of names of resources desired.
9029: # Returns:
9030: # The value of the first reasource in @which that is found in the
9031: # resource hash.
9032: # Exceptional Conditions:
9033: # If the $type passed in is not valid (not the string 'course' or
9034: # 'user', an undefined reference is returned.
9035: # If none of the resources are found, an undef is returned
1.624 albertel 9036: sub resdata {
9037: my ($name,$domain,$type,@which)=@_;
9038: my $result;
9039: if ($type eq 'course') {
9040: $result=&get_courseresdata($name,$domain);
9041: } elsif ($type eq 'user') {
9042: $result=&get_userresdata($name,$domain);
9043: }
9044: if (!ref($result)) { return $result; }
1.251 albertel 9045: foreach my $item (@which) {
1.927 albertel 9046: if (defined($result->{$item->[0]})) {
9047: return [$result->{$item->[0]},$item->[1]];
1.251 albertel 9048: }
1.250 albertel 9049: }
1.291 albertel 9050: return undef;
1.200 www 9051: }
9052:
1.379 matthew 9053: #
9054: # EXT resource caching routines
9055: #
9056:
9057: sub clear_EXT_cache_status {
1.383 albertel 9058: &delenv('cache.EXT.');
1.379 matthew 9059: }
9060:
9061: sub EXT_cache_status {
9062: my ($target_domain,$target_user) = @_;
1.383 albertel 9063: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.620 albertel 9064: if (exists($env{$cachename}) && ($env{$cachename}+600) > time) {
1.379 matthew 9065: # We know already the user has no data
9066: return 1;
9067: } else {
9068: return 0;
9069: }
9070: }
9071:
9072: sub EXT_cache_set {
9073: my ($target_domain,$target_user) = @_;
1.383 albertel 9074: my $cachename = 'cache.EXT.'.$target_user.'.'.$target_domain;
1.949 raeburn 9075: #&appenv({$cachename => time});
1.379 matthew 9076: }
9077:
1.28 www 9078: # --------------------------------------------------------- Value of a Variable
1.58 www 9079: sub EXT {
1.715 albertel 9080:
1.395 albertel 9081: my ($varname,$symbparm,$udom,$uname,$usection,$recurse)=@_;
1.68 www 9082: unless ($varname) { return ''; }
1.218 albertel 9083: #get real user name/domain, courseid and symb
9084: my $courseid;
1.359 albertel 9085: my $publicuser;
1.427 www 9086: if ($symbparm) {
9087: $symbparm=&get_symb_from_alias($symbparm);
9088: }
1.218 albertel 9089: if (!($uname && $udom)) {
1.790 albertel 9090: (my $cursymb,$courseid,$udom,$uname,$publicuser)= &whichuser($symbparm);
1.218 albertel 9091: if (!$symbparm) { $symbparm=$cursymb; }
9092: } else {
1.620 albertel 9093: $courseid=$env{'request.course.id'};
1.218 albertel 9094: }
1.48 www 9095: my ($realm,$space,$qualifier,@therest)=split(/\./,$varname);
9096: my $rest;
1.320 albertel 9097: if (defined($therest[0])) {
1.48 www 9098: $rest=join('.',@therest);
9099: } else {
9100: $rest='';
9101: }
1.320 albertel 9102:
1.57 www 9103: my $qualifierrest=$qualifier;
9104: if ($rest) { $qualifierrest.='.'.$rest; }
9105: my $spacequalifierrest=$space;
9106: if ($qualifierrest) { $spacequalifierrest.='.'.$qualifierrest; }
1.28 www 9107: if ($realm eq 'user') {
1.48 www 9108: # --------------------------------------------------------------- user.resource
9109: if ($space eq 'resource') {
1.651 albertel 9110: if ( (defined($Apache::lonhomework::parsing_a_problem)
9111: || defined($Apache::lonhomework::parsing_a_task))
9112: &&
1.744 albertel 9113: ($symbparm eq &symbread()) ) {
9114: # if we are in the middle of processing the resource the
9115: # get the value we are planning on committing
9116: if (defined($Apache::lonhomework::results{$qualifierrest})) {
9117: return $Apache::lonhomework::results{$qualifierrest};
9118: } else {
9119: return $Apache::lonhomework::history{$qualifierrest};
9120: }
1.335 albertel 9121: } else {
1.359 albertel 9122: my %restored;
1.620 albertel 9123: if ($publicuser || $env{'request.state'} eq 'construct') {
1.359 albertel 9124: %restored=&tmprestore($symbparm,$courseid,$udom,$uname);
9125: } else {
9126: %restored=&restore($symbparm,$courseid,$udom,$uname);
9127: }
1.335 albertel 9128: return $restored{$qualifierrest};
9129: }
1.48 www 9130: # ----------------------------------------------------------------- user.access
9131: } elsif ($space eq 'access') {
1.218 albertel 9132: # FIXME - not supporting calls for a specific user
1.48 www 9133: return &allowed($qualifier,$rest);
9134: # ------------------------------------------ user.preferences, user.environment
9135: } elsif (($space eq 'preferences') || ($space eq 'environment')) {
1.620 albertel 9136: if (($uname eq $env{'user.name'}) &&
9137: ($udom eq $env{'user.domain'})) {
9138: return $env{join('.',('environment',$qualifierrest))};
1.218 albertel 9139: } else {
1.359 albertel 9140: my %returnhash;
9141: if (!$publicuser) {
9142: %returnhash=&userenvironment($udom,$uname,
9143: $qualifierrest);
9144: }
1.218 albertel 9145: return $returnhash{$qualifierrest};
9146: }
1.48 www 9147: # ----------------------------------------------------------------- user.course
9148: } elsif ($space eq 'course') {
1.218 albertel 9149: # FIXME - not supporting calls for a specific user
1.620 albertel 9150: return $env{join('.',('request.course',$qualifier))};
1.48 www 9151: # ------------------------------------------------------------------- user.role
9152: } elsif ($space eq 'role') {
1.218 albertel 9153: # FIXME - not supporting calls for a specific user
1.620 albertel 9154: my ($role,$where)=split(/\./,$env{'request.role'});
1.48 www 9155: if ($qualifier eq 'value') {
9156: return $role;
9157: } elsif ($qualifier eq 'extent') {
9158: return $where;
9159: }
9160: # ----------------------------------------------------------------- user.domain
9161: } elsif ($space eq 'domain') {
1.218 albertel 9162: return $udom;
1.48 www 9163: # ------------------------------------------------------------------- user.name
9164: } elsif ($space eq 'name') {
1.218 albertel 9165: return $uname;
1.48 www 9166: # ---------------------------------------------------- Any other user namespace
1.29 www 9167: } else {
1.359 albertel 9168: my %reply;
9169: if (!$publicuser) {
9170: %reply=&get($space,[$qualifierrest],$udom,$uname);
9171: }
9172: return $reply{$qualifierrest};
1.48 www 9173: }
1.236 www 9174: } elsif ($realm eq 'query') {
9175: # ---------------------------------------------- pull stuff out of query string
1.384 albertel 9176: &Apache::loncommon::get_unprocessed_cgi($ENV{'QUERY_STRING'},
9177: [$spacequalifierrest]);
1.620 albertel 9178: return $env{'form.'.$spacequalifierrest};
1.236 www 9179: } elsif ($realm eq 'request') {
1.48 www 9180: # ------------------------------------------------------------- request.browser
9181: if ($space eq 'browser') {
1.1145 bisitz 9182: return $env{'browser.'.$qualifier};
1.57 www 9183: # ------------------------------------------------------------ request.filename
9184: } else {
1.620 albertel 9185: return $env{'request.'.$spacequalifierrest};
1.29 www 9186: }
1.28 www 9187: } elsif ($realm eq 'course') {
1.48 www 9188: # ---------------------------------------------------------- course.description
1.620 albertel 9189: return $env{'course.'.$courseid.'.'.$spacequalifierrest};
1.57 www 9190: } elsif ($realm eq 'resource') {
1.165 www 9191:
1.620 albertel 9192: if (defined($courseid) && $courseid eq $env{'request.course.id'}) {
1.539 albertel 9193: if (!$symbparm) { $symbparm=&symbread(); }
9194: }
1.693 albertel 9195:
9196: if ($space eq 'title') {
9197: if (!$symbparm) { $symbparm = $env{'request.filename'}; }
9198: return &gettitle($symbparm);
9199: }
9200:
9201: if ($space eq 'map') {
9202: my ($map) = &decode_symb($symbparm);
9203: return &symbread($map);
9204: }
1.905 albertel 9205: if ($space eq 'filename') {
9206: if ($symbparm) {
9207: return &clutter((&decode_symb($symbparm))[2]);
9208: }
9209: return &hreflocation('',$env{'request.filename'});
9210: }
1.693 albertel 9211:
9212: my ($section, $group, @groups);
1.593 albertel 9213: my ($courselevelm,$courselevel);
1.539 albertel 9214: if ($symbparm && defined($courseid) &&
1.620 albertel 9215: $courseid eq $env{'request.course.id'}) {
1.165 www 9216:
1.218 albertel 9217: #print '<br>'.$space.' - '.$qualifier.' - '.$spacequalifierrest;
1.165 www 9218:
1.60 www 9219: # ----------------------------------------------------- Cascading lookup scheme
1.218 albertel 9220: my $symbp=$symbparm;
1.735 albertel 9221: my $mapp=&deversion((&decode_symb($symbp))[0]);
1.218 albertel 9222:
9223: my $symbparm=$symbp.'.'.$spacequalifierrest;
9224: my $mapparm=$mapp.'___(all).'.$spacequalifierrest;
9225:
1.620 albertel 9226: if (($env{'user.name'} eq $uname) &&
9227: ($env{'user.domain'} eq $udom)) {
9228: $section=$env{'request.course.sec'};
1.733 raeburn 9229: @groups = split(/:/,$env{'request.course.groups'});
9230: @groups=&sort_course_groups($courseid,@groups);
1.218 albertel 9231: } else {
1.539 albertel 9232: if (! defined($usection)) {
1.551 albertel 9233: $section=&getsection($udom,$uname,$courseid);
1.539 albertel 9234: } else {
9235: $section = $usection;
9236: }
1.733 raeburn 9237: @groups = &get_users_groups($udom,$uname,$courseid);
1.218 albertel 9238: }
9239:
9240: my $seclevel=$courseid.'.['.$section.'].'.$spacequalifierrest;
9241: my $seclevelr=$courseid.'.['.$section.'].'.$symbparm;
9242: my $seclevelm=$courseid.'.['.$section.'].'.$mapparm;
9243:
1.593 albertel 9244: $courselevel=$courseid.'.'.$spacequalifierrest;
1.218 albertel 9245: my $courselevelr=$courseid.'.'.$symbparm;
1.593 albertel 9246: $courselevelm=$courseid.'.'.$mapparm;
1.69 www 9247:
1.60 www 9248: # ----------------------------------------------------------- first, check user
1.624 albertel 9249:
9250: my $userreply=&resdata($uname,$udom,'user',
1.927 albertel 9251: ([$courselevelr,'resource'],
9252: [$courselevelm,'map' ],
9253: [$courselevel, 'course' ]));
1.931 albertel 9254: if (defined($userreply)) { return &get_reply($userreply); }
1.95 www 9255:
1.594 albertel 9256: # ------------------------------------------------ second, check some of course
1.684 raeburn 9257: my $coursereply;
1.691 raeburn 9258: if (@groups > 0) {
9259: $coursereply = &check_group_parms($courseid,\@groups,$symbparm,
9260: $mapparm,$spacequalifierrest);
1.927 albertel 9261: if (defined($coursereply)) { return &get_reply($coursereply); }
1.684 raeburn 9262: }
1.96 www 9263:
1.684 raeburn 9264: $coursereply=&resdata($env{'course.'.$courseid.'.num'},
1.927 albertel 9265: $env{'course.'.$courseid.'.domain'},
9266: 'course',
9267: ([$seclevelr, 'resource'],
9268: [$seclevelm, 'map' ],
9269: [$seclevel, 'course' ],
9270: [$courselevelr,'resource']));
9271: if (defined($coursereply)) { return &get_reply($coursereply); }
1.200 www 9272:
1.60 www 9273: # ------------------------------------------------------ third, check map parms
1.218 albertel 9274: my %parmhash=();
9275: my $thisparm='';
9276: if (tie(%parmhash,'GDBM_File',
1.620 albertel 9277: $env{'request.course.fn'}.'_parms.db',
1.256 albertel 9278: &GDBM_READER(),0640)) {
1.218 albertel 9279: $thisparm=$parmhash{$symbparm};
9280: untie(%parmhash);
9281: }
1.927 albertel 9282: if ($thisparm) { return &get_reply([$thisparm,'resource']); }
1.218 albertel 9283: }
1.594 albertel 9284: # ------------------------------------------ fourth, look in resource metadata
1.71 www 9285:
1.218 albertel 9286: $spacequalifierrest=~s/\./\_/;
1.282 albertel 9287: my $filename;
9288: if (!$symbparm) { $symbparm=&symbread(); }
9289: if ($symbparm) {
1.409 www 9290: $filename=(&decode_symb($symbparm))[2];
1.282 albertel 9291: } else {
1.620 albertel 9292: $filename=$env{'request.filename'};
1.282 albertel 9293: }
9294: my $metadata=&metadata($filename,$spacequalifierrest);
1.927 albertel 9295: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.282 albertel 9296: $metadata=&metadata($filename,'parameter_'.$spacequalifierrest);
1.927 albertel 9297: if (defined($metadata)) { return &get_reply([$metadata,'resource']); }
1.142 www 9298:
1.927 albertel 9299: # ---------------------------------------------- fourth, look in rest of course
1.593 albertel 9300: if ($symbparm && defined($courseid) &&
1.620 albertel 9301: $courseid eq $env{'request.course.id'}) {
1.624 albertel 9302: my $coursereply=&resdata($env{'course.'.$courseid.'.num'},
9303: $env{'course.'.$courseid.'.domain'},
9304: 'course',
1.927 albertel 9305: ([$courselevelm,'map' ],
9306: [$courselevel, 'course']));
9307: if (defined($coursereply)) { return &get_reply($coursereply); }
1.593 albertel 9308: }
1.145 www 9309: # ------------------------------------------------------------------ Cascade up
1.218 albertel 9310: unless ($space eq '0') {
1.336 albertel 9311: my @parts=split(/_/,$space);
9312: my $id=pop(@parts);
9313: my $part=join('_',@parts);
9314: if ($part eq '') { $part='0'; }
1.927 albertel 9315: my @partgeneral=&EXT('resource.'.$part.'.'.$qualifierrest,
1.395 albertel 9316: $symbparm,$udom,$uname,$section,1);
1.938 raeburn 9317: if (defined($partgeneral[0])) { return &get_reply(\@partgeneral); }
1.218 albertel 9318: }
1.395 albertel 9319: if ($recurse) { return undef; }
9320: my $pack_def=&packages_tab_default($filename,$varname);
1.927 albertel 9321: if (defined($pack_def)) { return &get_reply([$pack_def,'resource']); }
1.48 www 9322: # ---------------------------------------------------- Any other user namespace
9323: } elsif ($realm eq 'environment') {
9324: # ----------------------------------------------------------------- environment
1.620 albertel 9325: if (($uname eq $env{'user.name'})&&($udom eq $env{'user.domain'})) {
9326: return $env{'environment.'.$spacequalifierrest};
1.219 albertel 9327: } else {
1.770 albertel 9328: if ($uname eq 'anonymous' && $udom eq '') {
9329: return '';
9330: }
1.219 albertel 9331: my %returnhash=&userenvironment($udom,$uname,
9332: $spacequalifierrest);
9333: return $returnhash{$spacequalifierrest};
9334: }
1.28 www 9335: } elsif ($realm eq 'system') {
1.48 www 9336: # ----------------------------------------------------------------- system.time
9337: if ($space eq 'time') {
9338: return time;
9339: }
1.696 albertel 9340: } elsif ($realm eq 'server') {
9341: # ----------------------------------------------------------------- system.time
9342: if ($space eq 'name') {
9343: return $ENV{'SERVER_NAME'};
9344: }
1.28 www 9345: }
1.48 www 9346: return '';
1.61 www 9347: }
9348:
1.927 albertel 9349: sub get_reply {
9350: my ($reply_value) = @_;
1.940 raeburn 9351: if (ref($reply_value) eq 'ARRAY') {
9352: if (wantarray) {
9353: return @$reply_value;
9354: }
9355: return $reply_value->[0];
9356: } else {
9357: return $reply_value;
1.927 albertel 9358: }
9359: }
9360:
1.691 raeburn 9361: sub check_group_parms {
9362: my ($courseid,$groups,$symbparm,$mapparm,$what) = @_;
9363: my @groupitems = ();
9364: my $resultitem;
1.927 albertel 9365: my @levels = ([$symbparm,'resource'],[$mapparm,'map'],[$what,'course']);
1.691 raeburn 9366: foreach my $group (@{$groups}) {
9367: foreach my $level (@levels) {
1.927 albertel 9368: my $item = $courseid.'.['.$group.'].'.$level->[0];
9369: push(@groupitems,[$item,$level->[1]]);
1.691 raeburn 9370: }
9371: }
9372: my $coursereply = &resdata($env{'course.'.$courseid.'.num'},
9373: $env{'course.'.$courseid.'.domain'},
9374: 'course',@groupitems);
9375: return $coursereply;
9376: }
9377:
9378: sub sort_course_groups { # Sort groups based on defined rankings. Default is sort().
1.733 raeburn 9379: my ($courseid,@groups) = @_;
9380: @groups = sort(@groups);
1.691 raeburn 9381: return @groups;
9382: }
9383:
1.395 albertel 9384: sub packages_tab_default {
9385: my ($uri,$varname)=@_;
9386: my (undef,$part,$name)=split(/\./,$varname);
1.738 albertel 9387:
9388: my (@extension,@specifics,$do_default);
9389: foreach my $package (split(/,/,&metadata($uri,'packages'))) {
1.395 albertel 9390: my ($pack_type,$pack_part)=split(/_/,$package,2);
1.738 albertel 9391: if ($pack_type eq 'default') {
9392: $do_default=1;
9393: } elsif ($pack_type eq 'extension') {
9394: push(@extension,[$package,$pack_type,$pack_part]);
1.885 albertel 9395: } elsif ($pack_part eq $part || $pack_type eq 'part') {
1.848 albertel 9396: # only look at packages defaults for packages that this id is
1.738 albertel 9397: push(@specifics,[$package,$pack_type,$pack_part]);
9398: }
9399: }
9400: # first look for a package that matches the requested part id
9401: foreach my $package (@specifics) {
9402: my (undef,$pack_type,$pack_part)=@{$package};
9403: next if ($pack_part ne $part);
9404: if (defined($packagetab{"$pack_type&$name&default"})) {
9405: return $packagetab{"$pack_type&$name&default"};
9406: }
9407: }
9408: # look for any possible matching non extension_ package
9409: foreach my $package (@specifics) {
9410: my (undef,$pack_type,$pack_part)=@{$package};
1.468 albertel 9411: if (defined($packagetab{"$pack_type&$name&default"})) {
9412: return $packagetab{"$pack_type&$name&default"};
9413: }
1.585 albertel 9414: if ($pack_type eq 'part') { $pack_part='0'; }
1.468 albertel 9415: if (defined($packagetab{$pack_type."_".$pack_part."&$name&default"})) {
9416: return $packagetab{$pack_type."_".$pack_part."&$name&default"};
1.395 albertel 9417: }
9418: }
1.738 albertel 9419: # look for any posible extension_ match
9420: foreach my $package (@extension) {
9421: my ($package,$pack_type)=@{$package};
9422: if (defined($packagetab{"$pack_type&$name&default"})) {
9423: return $packagetab{"$pack_type&$name&default"};
9424: }
9425: if (defined($packagetab{$package."&$name&default"})) {
9426: return $packagetab{$package."&$name&default"};
9427: }
9428: }
9429: # look for a global default setting
9430: if ($do_default && defined($packagetab{"default&$name&default"})) {
9431: return $packagetab{"default&$name&default"};
9432: }
1.395 albertel 9433: return undef;
9434: }
9435:
1.334 albertel 9436: sub add_prefix_and_part {
9437: my ($prefix,$part)=@_;
9438: my $keyroot;
9439: if (defined($prefix) && $prefix !~ /^__/) {
9440: # prefix that has a part already
9441: $keyroot=$prefix;
9442: } elsif (defined($prefix)) {
9443: # prefix that is missing a part
9444: if (defined($part)) { $keyroot='_'.$part.substr($prefix,1); }
9445: } else {
9446: # no prefix at all
9447: if (defined($part)) { $keyroot='_'.$part; }
9448: }
9449: return $keyroot;
9450: }
9451:
1.71 www 9452: # ---------------------------------------------------------------- Get metadata
9453:
1.599 albertel 9454: my %metaentry;
1.1070 www 9455: my %importedpartids;
1.71 www 9456: sub metadata {
1.176 www 9457: my ($uri,$what,$liburi,$prefix,$depthcount)=@_;
1.71 www 9458: $uri=&declutter($uri);
1.288 albertel 9459: # if it is a non metadata possible uri return quickly
1.529 albertel 9460: if (($uri eq '') ||
9461: (($uri =~ m|^/*adm/|) &&
1.698 albertel 9462: ($uri !~ m|^adm/includes|) && ($uri !~ m|/bulletinboard$|)) ||
1.1108 raeburn 9463: ($uri =~ m|/$|) || ($uri =~ m|/.meta$|) || ($uri =~ m{^/*uploaded/.+\.sequence$})) {
1.924 albertel 9464: return undef;
9465: }
1.1140 www 9466: if (($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/)
1.924 albertel 9467: && &Apache::lonxml::get_state('target') =~ /^(|meta)$/) {
1.468 albertel 9468: return undef;
1.288 albertel 9469: }
1.73 www 9470: my $filename=$uri;
9471: $uri=~s/\.meta$//;
1.172 www 9472: #
9473: # Is the metadata already cached?
1.177 www 9474: # Look at timestamp of caching
1.172 www 9475: # Everything is cached by the main uri, libraries are never directly cached
9476: #
1.428 albertel 9477: if (!defined($liburi)) {
1.599 albertel 9478: my ($result,$cached)=&is_cached_new('meta',$uri);
1.428 albertel 9479: if (defined($cached)) { return $result->{':'.$what}; }
9480: }
9481: {
1.1069 www 9482: # Imported parts would go here
1.1070 www 9483: my %importedids=();
9484: my @origfileimportpartids=();
1.1069 www 9485: my $importedparts=0;
1.172 www 9486: #
9487: # Is this a recursive call for a library?
9488: #
1.599 albertel 9489: # if (! exists($metacache{$uri})) {
9490: # $metacache{$uri}={};
9491: # }
1.924 albertel 9492: my $cachetime = 60*60;
1.171 www 9493: if ($liburi) {
9494: $liburi=&declutter($liburi);
9495: $filename=$liburi;
1.401 bowersj2 9496: } else {
1.599 albertel 9497: &devalidate_cache_new('meta',$uri);
9498: undef(%metaentry);
1.401 bowersj2 9499: }
1.140 www 9500: my %metathesekeys=();
1.73 www 9501: unless ($filename=~/\.meta$/) { $filename.='.meta'; }
1.489 albertel 9502: my $metastring;
1.1140 www 9503: if ($uri =~ /^priv/ || $uri=~/home\/httpd\/html\/priv/) {
1.929 albertel 9504: my $which = &hreflocation('','/'.($liburi || $uri));
1.924 albertel 9505: $metastring =
1.929 albertel 9506: &Apache::lonnet::ssi_body($which,
1.924 albertel 9507: ('grade_target' => 'meta'));
9508: $cachetime = 1; # only want this cached in the child not long term
1.1108 raeburn 9509: } elsif (($uri !~ m -^(editupload)/-) &&
9510: ($uri !~ m{^/*uploaded/$match_domain/$match_courseid/docs/})) {
1.543 albertel 9511: my $file=&filelocation('',&clutter($filename));
1.599 albertel 9512: #push(@{$metaentry{$uri.'.file'}},$file);
1.543 albertel 9513: $metastring=&getfile($file);
1.489 albertel 9514: }
1.208 albertel 9515: my $parser=HTML::LCParser->new(\$metastring);
1.71 www 9516: my $token;
1.140 www 9517: undef %metathesekeys;
1.71 www 9518: while ($token=$parser->get_token) {
1.339 albertel 9519: if ($token->[0] eq 'S') {
9520: if (defined($token->[2]->{'package'})) {
1.172 www 9521: #
9522: # This is a package - get package info
9523: #
1.339 albertel 9524: my $package=$token->[2]->{'package'};
9525: my $keyroot=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9526: if (defined($token->[2]->{'id'})) {
9527: $keyroot.='_'.$token->[2]->{'id'};
9528: }
1.599 albertel 9529: if ($metaentry{':packages'}) {
9530: $metaentry{':packages'}.=','.$package.$keyroot;
1.339 albertel 9531: } else {
1.599 albertel 9532: $metaentry{':packages'}=$package.$keyroot;
1.339 albertel 9533: }
1.736 albertel 9534: foreach my $pack_entry (keys(%packagetab)) {
1.432 albertel 9535: my $part=$keyroot;
9536: $part=~s/^\_//;
1.736 albertel 9537: if ($pack_entry=~/^\Q$package\E\&/ ||
9538: $pack_entry=~/^\Q$package\E_0\&/) {
9539: my ($pack,$name,$subp)=split(/\&/,$pack_entry);
1.395 albertel 9540: # ignore package.tab specified default values
9541: # here &package_tab_default() will fetch those
9542: if ($subp eq 'default') { next; }
1.736 albertel 9543: my $value=$packagetab{$pack_entry};
1.432 albertel 9544: my $unikey;
9545: if ($pack =~ /_0$/) {
9546: $unikey='parameter_0_'.$name;
9547: $part=0;
9548: } else {
9549: $unikey='parameter'.$keyroot.'_'.$name;
9550: }
1.339 albertel 9551: if ($subp eq 'display') {
9552: $value.=' [Part: '.$part.']';
9553: }
1.599 albertel 9554: $metaentry{':'.$unikey.'.part'}=$part;
1.395 albertel 9555: $metathesekeys{$unikey}=1;
1.599 albertel 9556: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9557: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.339 albertel 9558: }
1.599 albertel 9559: if (defined($metaentry{':'.$unikey.'.default'})) {
9560: $metaentry{':'.$unikey}=
9561: $metaentry{':'.$unikey.'.default'};
1.356 albertel 9562: }
1.339 albertel 9563: }
9564: }
9565: } else {
1.172 www 9566: #
9567: # This is not a package - some other kind of start tag
1.339 albertel 9568: #
9569: my $entry=$token->[1];
1.1068 www 9570: my $unikey='';
1.175 www 9571:
1.339 albertel 9572: if ($entry eq 'import') {
1.175 www 9573: #
9574: # Importing a library here
1.339 albertel 9575: #
1.1067 www 9576: my $location=$parser->get_text('/import');
9577: my $dir=$filename;
9578: $dir=~s|[^/]*$||;
9579: $location=&filelocation($dir,$location);
1.1069 www 9580:
1.1068 www 9581: my $importmode=$token->[2]->{'importmode'};
9582: if ($importmode eq 'problem') {
1.1069 www 9583: # Import as problem/response
1.1068 www 9584: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9585: } elsif ($importmode eq 'part') {
9586: # Import as part(s)
1.1069 www 9587: $importedparts=1;
9588: # We need to get the original file and the imported file to get the part order correct
9589: # Good news: we do not need to worry about nested libraries, since parts cannot be nested
9590: # Load and inspect original file
1.1070 www 9591: if ($#origfileimportpartids<0) {
9592: undef(%importedpartids);
9593: my $origfilelocation=$perlvar{'lonDocRoot'}.&clutter($uri);
9594: my $origfile=&getfile($origfilelocation);
9595: @origfileimportpartids=($origfile=~/<(part|import)[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9596: }
9597:
1.1069 www 9598: # Load and inspect imported file
9599: my $impfile=&getfile($location);
9600: my @impfilepartids=($impfile=~/<part[^>]*id\s*=\s*[\"\']([^\"\']+)[\"\'][^>]*>/gs);
9601: if ($#impfilepartids>=0) {
9602: # This problem had parts
1.1070 www 9603: $importedpartids{$token->[2]->{'id'}}=join(',',@impfilepartids);
1.1069 www 9604: } else {
9605: # Importing by turning a single problem into a problem part
9606: # It gets the import-tags ID as part-ID
9607: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'id'});
1.1070 www 9608: $importedpartids{$token->[2]->{'id'}}=$token->[2]->{'id'};
1.1069 www 9609: }
1.1068 www 9610: } else {
9611: # Normal import
9612: $unikey=&add_prefix_and_part($prefix,$token->[2]->{'part'});
9613: if (defined($token->[2]->{'id'})) {
9614: $unikey.='_'.$token->[2]->{'id'};
9615: }
1.1067 www 9616: }
9617:
1.339 albertel 9618: if ($depthcount<20) {
1.736 albertel 9619: my $metadata =
9620: &metadata($uri,'keys', $location,$unikey,
9621: $depthcount+1);
9622: foreach my $meta (split(',',$metadata)) {
9623: $metaentry{':'.$meta}=$metaentry{':'.$meta};
9624: $metathesekeys{$meta}=1;
1.339 albertel 9625: }
1.1068 www 9626:
9627: }
1.1067 www 9628: } else {
9629: #
9630: # Not importing, some other kind of non-package, non-library start tag
9631: #
9632: $unikey=$entry.&add_prefix_and_part($prefix,$token->[2]->{'part'});
9633: if (defined($token->[2]->{'id'})) {
9634: $unikey.='_'.$token->[2]->{'id'};
9635: }
1.339 albertel 9636: if (defined($token->[2]->{'name'})) {
9637: $unikey.='_'.$token->[2]->{'name'};
9638: }
9639: $metathesekeys{$unikey}=1;
1.736 albertel 9640: foreach my $param (@{$token->[3]}) {
9641: $metaentry{':'.$unikey.'.'.$param} =
9642: $token->[2]->{$param};
1.339 albertel 9643: }
9644: my $internaltext=&HTML::Entities::decode($parser->get_text('/'.$entry));
1.599 albertel 9645: my $default=$metaentry{':'.$unikey.'.default'};
1.339 albertel 9646: if ( $internaltext =~ /^\s*$/ && $default !~ /^\s*$/) {
9647: # only ws inside the tag, and not in default, so use default
9648: # as value
1.599 albertel 9649: $metaentry{':'.$unikey}=$default;
1.908 albertel 9650: } elsif ( $internaltext =~ /\S/ ) {
9651: # something interesting inside the tag
9652: $metaentry{':'.$unikey}=$internaltext;
1.339 albertel 9653: } else {
1.908 albertel 9654: # no interesting values, don't set a default
1.339 albertel 9655: }
1.172 www 9656: # end of not-a-package not-a-library import
1.339 albertel 9657: }
1.172 www 9658: # end of not-a-package start tag
1.339 albertel 9659: }
1.172 www 9660: # the next is the end of "start tag"
1.339 albertel 9661: }
9662: }
1.483 albertel 9663: my ($extension) = ($uri =~ /\.(\w+)$/);
1.883 albertel 9664: $extension = lc($extension);
9665: if ($extension eq 'htm') { $extension='html'; }
9666:
1.737 albertel 9667: foreach my $key (keys(%packagetab)) {
1.483 albertel 9668: #no specific packages #how's our extension
9669: if ($key!~/^extension_\Q$extension\E&/) { next; }
1.488 albertel 9670: &metadata_create_package_def($uri,$key,'extension_'.$extension,
1.483 albertel 9671: \%metathesekeys);
9672: }
1.883 albertel 9673:
9674: if (!exists($metaentry{':packages'})
9675: || $packagetab{"import_defaults&extension_$extension"}) {
1.737 albertel 9676: foreach my $key (keys(%packagetab)) {
1.483 albertel 9677: #no specific packages well let's get default then
9678: if ($key!~/^default&/) { next; }
1.488 albertel 9679: &metadata_create_package_def($uri,$key,'default',
1.483 albertel 9680: \%metathesekeys);
9681: }
9682: }
1.338 www 9683: # are there custom rights to evaluate
1.599 albertel 9684: if ($metaentry{':copyright'} eq 'custom') {
1.339 albertel 9685:
1.338 www 9686: #
9687: # Importing a rights file here
1.339 albertel 9688: #
9689: unless ($depthcount) {
1.599 albertel 9690: my $location=$metaentry{':customdistributionfile'};
1.339 albertel 9691: my $dir=$filename;
9692: $dir=~s|[^/]*$||;
9693: $location=&filelocation($dir,$location);
1.736 albertel 9694: my $rights_metadata =
9695: &metadata($uri,'keys',$location,'_rights',
9696: $depthcount+1);
9697: foreach my $rights (split(',',$rights_metadata)) {
9698: #$metaentry{':'.$rights}=$metacache{$uri}->{':'.$rights};
9699: $metathesekeys{$rights}=1;
1.339 albertel 9700: }
9701: }
9702: }
1.737 albertel 9703: # uniqifiy package listing
9704: my %seen;
9705: my @uniq_packages =
9706: grep { ! $seen{$_} ++ } (split(',',$metaentry{':packages'}));
9707: $metaentry{':packages'} = join(',',@uniq_packages);
9708:
1.1070 www 9709: if ($importedparts) {
9710: # We had imported parts and need to rebuild partorder
9711: $metaentry{':partorder'}='';
9712: $metathesekeys{'partorder'}=1;
9713: for (my $index=0;$index<$#origfileimportpartids;$index+=2) {
9714: if ($origfileimportpartids[$index] eq 'part') {
9715: # original part, part of the problem
9716: $metaentry{':partorder'}.=','.$origfileimportpartids[$index+1];
9717: } else {
9718: # we have imported parts at this position
9719: $metaentry{':partorder'}.=','.$importedpartids{$origfileimportpartids[$index+1]};
9720: }
9721: }
9722: $metaentry{':partorder'}=~s/^\,//;
9723: }
9724:
1.737 albertel 9725: $metaentry{':keys'} = join(',',keys(%metathesekeys));
1.599 albertel 9726: &metadata_generate_part0(\%metathesekeys,\%metaentry,$uri);
9727: $metaentry{':allpossiblekeys'}=join(',',keys %metathesekeys);
1.924 albertel 9728: &do_cache_new('meta',$uri,\%metaentry,$cachetime);
1.177 www 9729: # this is the end of "was not already recently cached
1.71 www 9730: }
1.599 albertel 9731: return $metaentry{':'.$what};
1.261 albertel 9732: }
9733:
1.488 albertel 9734: sub metadata_create_package_def {
1.483 albertel 9735: my ($uri,$key,$package,$metathesekeys)=@_;
9736: my ($pack,$name,$subp)=split(/\&/,$key);
9737: if ($subp eq 'default') { next; }
9738:
1.599 albertel 9739: if (defined($metaentry{':packages'})) {
9740: $metaentry{':packages'}.=','.$package;
1.483 albertel 9741: } else {
1.599 albertel 9742: $metaentry{':packages'}=$package;
1.483 albertel 9743: }
9744: my $value=$packagetab{$key};
9745: my $unikey;
9746: $unikey='parameter_0_'.$name;
1.599 albertel 9747: $metaentry{':'.$unikey.'.part'}=0;
1.483 albertel 9748: $$metathesekeys{$unikey}=1;
1.599 albertel 9749: unless (defined($metaentry{':'.$unikey.'.'.$subp})) {
9750: $metaentry{':'.$unikey.'.'.$subp}=$value;
1.483 albertel 9751: }
1.599 albertel 9752: if (defined($metaentry{':'.$unikey.'.default'})) {
9753: $metaentry{':'.$unikey}=
9754: $metaentry{':'.$unikey.'.default'};
1.483 albertel 9755: }
9756: }
9757:
1.261 albertel 9758: sub metadata_generate_part0 {
9759: my ($metadata,$metacache,$uri) = @_;
9760: my %allnames;
1.737 albertel 9761: foreach my $metakey (keys(%$metadata)) {
1.261 albertel 9762: if ($metakey=~/^parameter\_(.*)/) {
1.428 albertel 9763: my $part=$$metacache{':'.$metakey.'.part'};
9764: my $name=$$metacache{':'.$metakey.'.name'};
1.356 albertel 9765: if (! exists($$metadata{'parameter_0_'.$name.'.name'})) {
1.261 albertel 9766: $allnames{$name}=$part;
9767: }
9768: }
9769: }
9770: foreach my $name (keys(%allnames)) {
9771: $$metadata{"parameter_0_$name"}=1;
1.428 albertel 9772: my $key=":parameter_0_$name";
1.261 albertel 9773: $$metacache{"$key.part"}='0';
9774: $$metacache{"$key.name"}=$name;
1.428 albertel 9775: $$metacache{"$key.type"}=$$metacache{':parameter_'.
1.261 albertel 9776: $allnames{$name}.'_'.$name.
9777: '.type'};
1.428 albertel 9778: my $olddis=$$metacache{':parameter_'.$allnames{$name}.'_'.$name.
1.261 albertel 9779: '.display'};
1.644 www 9780: my $expr='[Part: '.$allnames{$name}.']';
1.479 albertel 9781: $olddis=~s/\Q$expr\E/\[Part: 0\]/;
1.261 albertel 9782: $$metacache{"$key.display"}=$olddis;
9783: }
1.71 www 9784: }
9785:
1.764 albertel 9786: # ------------------------------------------------------ Devalidate title cache
9787:
9788: sub devalidate_title_cache {
9789: my ($url)=@_;
9790: if (!$env{'request.course.id'}) { return; }
9791: my $symb=&symbread($url);
9792: if (!$symb) { return; }
9793: my $key=$env{'request.course.id'}."\0".$symb;
9794: &devalidate_cache_new('title',$key);
9795: }
9796:
1.1014 droeschl 9797: # ------------------------------------------------- Get the title of a course
9798:
9799: sub current_course_title {
9800: return $env{ 'course.' . $env{'request.course.id'} . '.description' };
9801: }
1.301 www 9802: # ------------------------------------------------- Get the title of a resource
9803:
9804: sub gettitle {
9805: my $urlsymb=shift;
9806: my $symb=&symbread($urlsymb);
1.534 albertel 9807: if ($symb) {
1.620 albertel 9808: my $key=$env{'request.course.id'}."\0".$symb;
1.599 albertel 9809: my ($result,$cached)=&is_cached_new('title',$key);
1.575 albertel 9810: if (defined($cached)) {
9811: return $result;
9812: }
1.534 albertel 9813: my ($map,$resid,$url)=&decode_symb($symb);
9814: my $title='';
1.907 albertel 9815: if (!$map && $resid == 0 && $url =~/default\.sequence$/) {
9816: $title = $env{'course.'.$env{'request.course.id'}.'.description'};
9817: } else {
9818: if (tie(my %bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
9819: &GDBM_READER(),0640)) {
9820: my $mapid=$bighash{'map_pc_'.&clutter($map)};
9821: $title=$bighash{'title_'.$mapid.'.'.$resid};
9822: untie(%bighash);
9823: }
1.534 albertel 9824: }
9825: $title=~s/\&colon\;/\:/gs;
9826: if ($title) {
1.1159 www 9827: # Remember both $symb and $title for dynamic metadata
9828: $accesshash{$symb.'___crstitle'}=$title;
1.1161 www 9829: $accesshash{&declutter($map).'___'.&declutter($url).'___usage'}=time;
1.1159 www 9830: # Cache this title and then return it
1.599 albertel 9831: return &do_cache_new('title',$key,$title,600);
1.534 albertel 9832: }
9833: $urlsymb=$url;
9834: }
9835: my $title=&metadata($urlsymb,'title');
9836: if (!$title) { $title=(split('/',$urlsymb))[-1]; }
9837: return $title;
1.301 www 9838: }
1.613 albertel 9839:
1.614 albertel 9840: sub get_slot {
9841: my ($which,$cnum,$cdom)=@_;
9842: if (!$cnum || !$cdom) {
1.790 albertel 9843: (undef,my $courseid)=&whichuser();
1.620 albertel 9844: $cdom=$env{'course.'.$courseid.'.domain'};
9845: $cnum=$env{'course.'.$courseid.'.num'};
1.614 albertel 9846: }
1.703 albertel 9847: my $key=join("\0",'slots',$cdom,$cnum,$which);
9848: my %slotinfo;
9849: if (exists($remembered{$key})) {
9850: $slotinfo{$which} = $remembered{$key};
9851: } else {
9852: %slotinfo=&get('slots',[$which],$cdom,$cnum);
9853: &Apache::lonhomework::showhash(%slotinfo);
9854: my ($tmp)=keys(%slotinfo);
9855: if ($tmp=~/^error:/) { return (); }
9856: $remembered{$key} = $slotinfo{$which};
9857: }
1.616 albertel 9858: if (ref($slotinfo{$which}) eq 'HASH') {
9859: return %{$slotinfo{$which}};
9860: }
9861: return $slotinfo{$which};
1.614 albertel 9862: }
1.1150 raeburn 9863:
9864: sub get_reservable_slots {
9865: my ($cnum,$cdom,$uname,$udom) = @_;
9866: my $now = time;
9867: my $reservable_info;
9868: my $key=join("\0",'reservableslots',$cdom,$cnum,$uname,$udom);
9869: if (exists($remembered{$key})) {
9870: $reservable_info = $remembered{$key};
9871: } else {
9872: my %resv;
9873: ($resv{'now_order'},$resv{'now'},$resv{'future_order'},$resv{'future'}) =
9874: &Apache::loncommon::get_future_slots($cnum,$cdom,$now);
9875: $reservable_info = \%resv;
9876: $remembered{$key} = $reservable_info;
9877: }
9878: return $reservable_info;
9879: }
9880:
9881: sub get_course_slots {
9882: my ($cnum,$cdom) = @_;
9883: my $hashid=$cnum.':'.$cdom;
9884: my ($result,$cached) = &Apache::lonnet::is_cached_new('allslots',$hashid);
9885: if (defined($cached)) {
9886: if (ref($result) eq 'HASH') {
9887: return %{$result};
9888: }
9889: } else {
9890: my %slots=&Apache::lonnet::dump('slots',$cdom,$cnum);
9891: my ($tmp) = keys(%slots);
9892: if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
9893: &Apache::lonnet::do_cache_new('allslots',$hashid,\%slots,600);
9894: return %slots;
9895: }
9896: }
9897: return;
9898: }
9899:
9900: sub devalidate_slots_cache {
9901: my ($cnum,$cdom)=@_;
9902: my $hashid=$cnum.':'.$cdom;
9903: &devalidate_cache_new('allslots',$hashid);
9904: }
9905:
1.1181 raeburn 9906: sub get_coursechange {
9907: my ($cdom,$cnum) = @_;
9908: if ($cdom eq '' || $cnum eq '') {
9909: return unless ($env{'request.course.id'});
9910: $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
9911: $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
9912: }
9913: my $hashid=$cdom.'_'.$cnum;
9914: my ($change,$cached)=&is_cached_new('crschange',$hashid);
9915: if ((defined($cached)) && ($change ne '')) {
9916: return $change;
9917: } else {
9918: my %crshash;
9919: %crshash = &get('environment',['internal.contentchange'],$cdom,$cnum);
9920: if ($crshash{'internal.contentchange'} eq '') {
9921: $change = $env{'course.'.$cdom.'_'.$cnum.'.internal.created'};
9922: if ($change eq '') {
9923: %crshash = &get('environment',['internal.created'],$cdom,$cnum);
9924: $change = $crshash{'internal.created'};
9925: }
9926: } else {
9927: $change = $crshash{'internal.contentchange'};
9928: }
9929: my $cachetime = 600;
9930: &do_cache_new('crschange',$hashid,$change,$cachetime);
9931: }
9932: return $change;
9933: }
9934:
9935: sub devalidate_coursechange_cache {
9936: my ($cnum,$cdom)=@_;
9937: my $hashid=$cnum.':'.$cdom;
9938: &devalidate_cache_new('crschange',$hashid);
9939: }
9940:
1.31 www 9941: # ------------------------------------------------- Update symbolic store links
9942:
9943: sub symblist {
9944: my ($mapname,%newhash)=@_;
1.438 www 9945: $mapname=&deversion(&declutter($mapname));
1.31 www 9946: my %hash;
1.620 albertel 9947: if (($env{'request.course.fn'}) && (%newhash)) {
9948: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 9949: &GDBM_WRCREAT(),0640)) {
1.1000 raeburn 9950: foreach my $url (keys(%newhash)) {
1.711 albertel 9951: next if ($url eq 'last_known'
9952: && $env{'form.no_update_last_known'});
9953: $hash{declutter($url)}=&encode_symb($mapname,
9954: $newhash{$url}->[1],
9955: $newhash{$url}->[0]);
1.191 harris41 9956: }
1.31 www 9957: if (untie(%hash)) {
9958: return 'ok';
9959: }
9960: }
9961: }
9962: return 'error';
1.212 www 9963: }
9964:
9965: # --------------------------------------------------------------- Verify a symb
9966:
9967: sub symbverify {
1.510 www 9968: my ($symb,$thisurl)=@_;
9969: my $thisfn=$thisurl;
1.439 www 9970: $thisfn=&declutter($thisfn);
1.215 www 9971: # direct jump to resource in page or to a sequence - will construct own symbs
9972: if ($thisfn=~/\.(page|sequence)$/) { return 1; }
9973: # check URL part
1.409 www 9974: my ($map,$resid,$url)=&decode_symb($symb);
1.439 www 9975:
1.431 www 9976: unless ($url eq $thisfn) { return 0; }
1.213 www 9977:
1.216 www 9978: $symb=&symbclean($symb);
1.510 www 9979: $thisurl=&deversion($thisurl);
1.439 www 9980: $thisfn=&deversion($thisfn);
1.213 www 9981:
9982: my %bighash;
9983: my $okay=0;
1.431 www 9984:
1.620 albertel 9985: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 9986: &GDBM_READER(),0640)) {
1.1032 raeburn 9987: if (($thisurl =~ m{^/adm/wrapper/ext/}) || ($thisurl =~ m{^ext/})) {
9988: $thisurl =~ s/\?.+$//;
9989: }
1.510 www 9990: my $ids=$bighash{'ids_'.&clutter($thisurl)};
1.1102 raeburn 9991: unless ($ids) {
9992: my $idkey = 'ids_'.($thisurl =~ m{^/}? '' : '/').$thisurl;
9993: $ids=$bighash{$idkey};
1.216 www 9994: }
9995: if ($ids) {
9996: # ------------------------------------------------------------------- Has ID(s)
1.800 albertel 9997: foreach my $id (split(/\,/,$ids)) {
9998: my ($mapid,$resid)=split(/\./,$id);
1.1032 raeburn 9999: if ($thisfn =~ m{^/adm/wrapper/ext/}) {
10000: $symb =~ s/\?.+$//;
10001: }
1.216 www 10002: if (
10003: &symbclean(&declutter($bighash{'map_id_'.$mapid}).'___'.$resid.'___'.$thisfn)
10004: eq $symb) {
1.620 albertel 10005: if (($env{'request.role.adv'}) ||
1.1101 raeburn 10006: ($bighash{'encrypted_'.$id} eq $env{'request.enc'}) ||
10007: ($thisurl eq '/adm/navmaps')) {
1.582 albertel 10008: $okay=1;
10009: }
10010: }
1.216 www 10011: }
10012: }
1.213 www 10013: untie(%bighash);
10014: }
10015: return $okay;
1.31 www 10016: }
10017:
1.210 www 10018: # --------------------------------------------------------------- Clean-up symb
10019:
10020: sub symbclean {
10021: my $symb=shift;
1.568 albertel 10022: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
1.210 www 10023: # remove version from map
10024: $symb=~s/\.(\d+)\.(\w+)\_\_\_/\.$2\_\_\_/;
1.215 www 10025:
1.210 www 10026: # remove version from URL
10027: $symb=~s/\.(\d+)\.(\w+)$/\.$2/;
1.213 www 10028:
1.507 www 10029: # remove wrapper
10030:
1.510 www 10031: $symb=~s/(\_\_\_\d+\_\_\_)adm\/wrapper\/(res\/)*/$1/;
1.694 albertel 10032: $symb=~s/(\_\_\_\d+\_\_\_)adm\/coursedocs\/showdoc\/(res\/)*/$1/;
1.210 www 10033: return $symb;
1.409 www 10034: }
10035:
10036: # ---------------------------------------------- Split symb to find map and url
1.429 albertel 10037:
10038: sub encode_symb {
10039: my ($map,$resid,$url)=@_;
10040: return &symbclean(&declutter($map).'___'.$resid.'___'.&declutter($url));
10041: }
1.409 www 10042:
10043: sub decode_symb {
1.568 albertel 10044: my $symb=shift;
10045: if ($symb=~m|^/enc/|) { $symb=&Apache::lonenc::unencrypted($symb); }
10046: my ($map,$resid,$url)=split(/___/,$symb);
1.413 www 10047: return (&fixversion($map),$resid,&fixversion($url));
10048: }
10049:
10050: sub fixversion {
10051: my $fn=shift;
1.609 banghart 10052: if ($fn=~/^(adm|uploaded|editupload|public)/) { return $fn; }
1.435 www 10053: my %bighash;
10054: my $uri=&clutter($fn);
1.620 albertel 10055: my $key=$env{'request.course.id'}.'_'.$uri;
1.440 www 10056: # is this cached?
1.599 albertel 10057: my ($result,$cached)=&is_cached_new('courseresversion',$key);
1.440 www 10058: if (defined($cached)) { return $result; }
10059: # unfortunately not cached, or expired
1.620 albertel 10060: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.440 www 10061: &GDBM_READER(),0640)) {
10062: if ($bighash{'version_'.$uri}) {
10063: my $version=$bighash{'version_'.$uri};
1.444 www 10064: unless (($version eq 'mostrecent') ||
10065: ($version==&getversion($uri))) {
1.440 www 10066: $uri=~s/\.(\w+)$/\.$version\.$1/;
10067: }
10068: }
10069: untie %bighash;
1.413 www 10070: }
1.599 albertel 10071: return &do_cache_new('courseresversion',$key,&declutter($uri),600);
1.438 www 10072: }
10073:
10074: sub deversion {
10075: my $url=shift;
10076: $url=~s/\.\d+\.(\w+)$/\.$1/;
10077: return $url;
1.210 www 10078: }
10079:
1.31 www 10080: # ------------------------------------------------------ Return symb list entry
10081:
10082: sub symbread {
1.249 www 10083: my ($thisfn,$donotrecurse)=@_;
1.542 albertel 10084: my $cache_str='request.symbread.cached.'.$thisfn;
1.1179 raeburn 10085: if (defined($env{$cache_str})) {
10086: if (($thisfn) || ($env{$cache_str} ne '')) {
10087: return $env{$cache_str};
10088: }
10089: }
1.242 www 10090: # no filename provided? try from environment
1.44 www 10091: unless ($thisfn) {
1.620 albertel 10092: if ($env{'request.symb'}) {
10093: return $env{$cache_str}=&symbclean($env{'request.symb'});
1.539 albertel 10094: }
1.620 albertel 10095: $thisfn=$env{'request.filename'};
1.44 www 10096: }
1.569 albertel 10097: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.242 www 10098: # is that filename actually a symb? Verify, clean, and return
10099: if ($thisfn=~/\_\_\_\d+\_\_\_(.*)$/) {
1.539 albertel 10100: if (&symbverify($thisfn,$1)) {
1.620 albertel 10101: return $env{$cache_str}=&symbclean($thisfn);
1.539 albertel 10102: }
1.242 www 10103: }
1.44 www 10104: $thisfn=declutter($thisfn);
1.31 www 10105: my %hash;
1.37 www 10106: my %bighash;
10107: my $syval='';
1.620 albertel 10108: if (($env{'request.course.fn'}) && ($thisfn)) {
1.481 raeburn 10109: my $targetfn = $thisfn;
1.609 banghart 10110: if ( ($thisfn =~ m/^(uploaded|editupload)\//) && ($thisfn !~ m/\.(page|sequence)$/) ) {
1.481 raeburn 10111: $targetfn = 'adm/wrapper/'.$thisfn;
10112: }
1.687 albertel 10113: if ($targetfn =~ m|^adm/wrapper/(ext/.*)|) {
10114: $targetfn=$1;
10115: }
1.620 albertel 10116: if (tie(%hash,'GDBM_File',$env{'request.course.fn'}.'_symb.db',
1.256 albertel 10117: &GDBM_READER(),0640)) {
1.481 raeburn 10118: $syval=$hash{$targetfn};
1.37 www 10119: untie(%hash);
10120: }
10121: # ---------------------------------------------------------- There was an entry
10122: if ($syval) {
1.601 albertel 10123: #unless ($syval=~/\_\d+$/) {
1.620 albertel 10124: #unless ($env{'form.request.prefix'}=~/\.(\d+)\_$/) {
1.949 raeburn 10125: #&appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10126: #return $env{$cache_str}='';
1.601 albertel 10127: #}
10128: #$syval.=$1;
10129: #}
1.37 www 10130: } else {
10131: # ------------------------------------------------------- Was not in symb table
1.620 albertel 10132: if (tie(%bighash,'GDBM_File',$env{'request.course.fn'}.'.db',
1.256 albertel 10133: &GDBM_READER(),0640)) {
1.37 www 10134: # ---------------------------------------------- Get ID(s) for current resource
1.280 www 10135: my $ids=$bighash{'ids_'.&clutter($thisfn)};
1.65 www 10136: unless ($ids) {
10137: $ids=$bighash{'ids_/'.$thisfn};
1.242 www 10138: }
10139: unless ($ids) {
10140: # alias?
10141: $ids=$bighash{'mapalias_'.$thisfn};
1.65 www 10142: }
1.37 www 10143: if ($ids) {
10144: # ------------------------------------------------------------------- Has ID(s)
10145: my @possibilities=split(/\,/,$ids);
1.39 www 10146: if ($#possibilities==0) {
10147: # ----------------------------------------------- There is only one possibility
1.37 www 10148: my ($mapid,$resid)=split(/\./,$ids);
1.626 albertel 10149: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10150: $resid,$thisfn);
1.249 www 10151: } elsif (!$donotrecurse) {
1.39 www 10152: # ------------------------------------------ There is more than one possibility
10153: my $realpossible=0;
1.800 albertel 10154: foreach my $id (@possibilities) {
10155: my $file=$bighash{'src_'.$id};
1.39 www 10156: if (&allowed('bre',$file)) {
1.800 albertel 10157: my ($mapid,$resid)=split(/\./,$id);
1.39 www 10158: if ($bighash{'map_type_'.$mapid} ne 'page') {
10159: $realpossible++;
1.626 albertel 10160: $syval=&encode_symb($bighash{'map_id_'.$mapid},
10161: $resid,$thisfn);
1.39 www 10162: }
10163: }
1.191 harris41 10164: }
1.39 www 10165: if ($realpossible!=1) { $syval=''; }
1.249 www 10166: } else {
10167: $syval='';
1.37 www 10168: }
10169: }
10170: untie(%bighash)
1.481 raeburn 10171: }
1.31 www 10172: }
1.62 www 10173: if ($syval) {
1.620 albertel 10174: return $env{$cache_str}=$syval;
1.62 www 10175: }
1.31 www 10176: }
1.949 raeburn 10177: &appenv({'request.ambiguous' => $thisfn});
1.620 albertel 10178: return $env{$cache_str}='';
1.31 www 10179: }
10180:
10181: # ---------------------------------------------------------- Return random seed
10182:
1.32 www 10183: sub numval {
10184: my $txt=shift;
10185: $txt=~tr/A-J/0-9/;
10186: $txt=~tr/a-j/0-9/;
10187: $txt=~tr/K-T/0-9/;
10188: $txt=~tr/k-t/0-9/;
10189: $txt=~tr/U-Z/0-5/;
10190: $txt=~tr/u-z/0-5/;
10191: $txt=~s/\D//g;
1.564 albertel 10192: if ($_64bit) { if ($txt > 2**32) { return -1; } }
1.32 www 10193: return int($txt);
1.368 albertel 10194: }
10195:
1.484 albertel 10196: sub numval2 {
10197: my $txt=shift;
10198: $txt=~tr/A-J/0-9/;
10199: $txt=~tr/a-j/0-9/;
10200: $txt=~tr/K-T/0-9/;
10201: $txt=~tr/k-t/0-9/;
10202: $txt=~tr/U-Z/0-5/;
10203: $txt=~tr/u-z/0-5/;
10204: $txt=~s/\D//g;
10205: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10206: my $total;
10207: foreach my $val (@txts) { $total+=$val; }
1.564 albertel 10208: if ($_64bit) { if ($total > 2**32) { return -1; } }
1.484 albertel 10209: return int($total);
10210: }
10211:
1.575 albertel 10212: sub numval3 {
10213: use integer;
10214: my $txt=shift;
10215: $txt=~tr/A-J/0-9/;
10216: $txt=~tr/a-j/0-9/;
10217: $txt=~tr/K-T/0-9/;
10218: $txt=~tr/k-t/0-9/;
10219: $txt=~tr/U-Z/0-5/;
10220: $txt=~tr/u-z/0-5/;
10221: $txt=~s/\D//g;
10222: my @txts=split(/(\d\d\d\d\d\d\d\d\d)/,$txt);
10223: my $total;
10224: foreach my $val (@txts) { $total+=$val; }
10225: if ($_64bit) { $total=(($total<<32)>>32); }
10226: return $total;
10227: }
10228:
1.675 albertel 10229: sub digest {
10230: my ($data)=@_;
10231: my $digest=&Digest::MD5::md5($data);
10232: my ($a,$b,$c,$d)=unpack("iiii",$digest);
10233: my ($e,$f);
10234: {
10235: use integer;
10236: $e=($a+$b);
10237: $f=($c+$d);
10238: if ($_64bit) {
10239: $e=(($e<<32)>>32);
10240: $f=(($f<<32)>>32);
10241: }
10242: }
10243: if (wantarray) {
10244: return ($e,$f);
10245: } else {
10246: my $g;
10247: {
10248: use integer;
10249: $g=($e+$f);
10250: if ($_64bit) {
10251: $g=(($g<<32)>>32);
10252: }
10253: }
10254: return $g;
10255: }
10256: }
10257:
1.368 albertel 10258: sub latest_rnd_algorithm_id {
1.675 albertel 10259: return '64bit5';
1.366 albertel 10260: }
1.32 www 10261:
1.503 albertel 10262: sub get_rand_alg {
10263: my ($courseid)=@_;
1.790 albertel 10264: if (!$courseid) { $courseid=(&whichuser())[1]; }
1.503 albertel 10265: if ($courseid) {
1.620 albertel 10266: return $env{"course.$courseid.rndseed"};
1.503 albertel 10267: }
10268: return &latest_rnd_algorithm_id();
10269: }
10270:
1.562 albertel 10271: sub validCODE {
10272: my ($CODE)=@_;
10273: if (defined($CODE) && $CODE ne '' && $CODE =~ /^\w+$/) { return 1; }
10274: return 0;
10275: }
10276:
1.491 albertel 10277: sub getCODE {
1.620 albertel 10278: if (&validCODE($env{'form.CODE'})) { return $env{'form.CODE'}; }
1.618 albertel 10279: if ( (defined($Apache::lonhomework::parsing_a_problem) ||
10280: defined($Apache::lonhomework::parsing_a_task) ) &&
10281: &validCODE($Apache::lonhomework::history{'resource.CODE'})) {
1.491 albertel 10282: return $Apache::lonhomework::history{'resource.CODE'};
10283: }
10284: return undef;
10285: }
1.1133 foxr 10286: #
10287: # Determines the random seed for a specific context:
10288: #
10289: # parameters:
10290: # symb - in course context the symb for the seed.
10291: # course_id - The course id of the form domain_coursenum.
10292: # domain - Domain for the user.
10293: # course - Course for the user.
10294: # cenv - environment of the course.
10295: #
10296: # NOTE:
10297: # All parameters are picked out of the environment if missing
10298: # or not defined.
10299: # If a symb cannot be determined the current time is used instead.
10300: #
10301: # For a given well defined symb, courside, domain, username,
10302: # and course environment, the seed is reproducible.
10303: #
1.31 www 10304: sub rndseed {
1.1133 foxr 10305: my ($symb,$courseid,$domain,$username, $cenv)=@_;
1.790 albertel 10306: my ($wsymb,$wcourseid,$wdomain,$wusername)=&whichuser();
1.896 albertel 10307: if (!defined($symb)) {
1.366 albertel 10308: unless ($symb=$wsymb) { return time; }
10309: }
1.1146 foxr 10310: if (!defined $courseid) {
10311: $courseid=$wcourseid;
10312: }
10313: if (!defined $domain) { $domain=$wdomain; }
10314: if (!defined $username) { $username=$wusername }
1.1133 foxr 10315:
10316: my $which;
10317: if (defined($cenv->{'rndseed'})) {
10318: $which = $cenv->{'rndseed'};
10319: } else {
10320: $which =&get_rand_alg($courseid);
10321: }
1.491 albertel 10322: if (defined(&getCODE())) {
1.1133 foxr 10323:
1.675 albertel 10324: if ($which eq '64bit5') {
10325: return &rndseed_CODE_64bit5($symb,$courseid,$domain,$username);
10326: } elsif ($which eq '64bit4') {
1.575 albertel 10327: return &rndseed_CODE_64bit4($symb,$courseid,$domain,$username);
10328: } else {
10329: return &rndseed_CODE_64bit($symb,$courseid,$domain,$username);
10330: }
1.675 albertel 10331: } elsif ($which eq '64bit5') {
10332: return &rndseed_64bit5($symb,$courseid,$domain,$username);
1.575 albertel 10333: } elsif ($which eq '64bit4') {
10334: return &rndseed_64bit4($symb,$courseid,$domain,$username);
1.501 albertel 10335: } elsif ($which eq '64bit3') {
10336: return &rndseed_64bit3($symb,$courseid,$domain,$username);
1.443 albertel 10337: } elsif ($which eq '64bit2') {
10338: return &rndseed_64bit2($symb,$courseid,$domain,$username);
1.366 albertel 10339: } elsif ($which eq '64bit') {
10340: return &rndseed_64bit($symb,$courseid,$domain,$username);
10341: }
10342: return &rndseed_32bit($symb,$courseid,$domain,$username);
10343: }
10344:
10345: sub rndseed_32bit {
10346: my ($symb,$courseid,$domain,$username)=@_;
10347: {
10348: use integer;
10349: my $symbchck=unpack("%32C*",$symb) << 27;
10350: my $symbseed=numval($symb) << 22;
10351: my $namechck=unpack("%32C*",$username) << 17;
10352: my $nameseed=numval($username) << 12;
10353: my $domainseed=unpack("%32C*",$domain) << 7;
10354: my $courseseed=unpack("%32C*",$courseid);
10355: my $num=$symbseed+$nameseed+$domainseed+$courseseed+$namechck+$symbchck;
1.790 albertel 10356: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10357: #&logthis("rndseed :$num:$symb");
1.564 albertel 10358: if ($_64bit) { $num=(($num<<32)>>32); }
1.366 albertel 10359: return $num;
10360: }
10361: }
10362:
10363: sub rndseed_64bit {
10364: my ($symb,$courseid,$domain,$username)=@_;
10365: {
10366: use integer;
10367: my $symbchck=unpack("%32S*",$symb) << 21;
10368: my $symbseed=numval($symb) << 10;
10369: my $namechck=unpack("%32S*",$username);
10370:
10371: my $nameseed=numval($username) << 21;
10372: my $domainseed=unpack("%32S*",$domain) << 10;
10373: my $courseseed=unpack("%32S*",$courseid);
10374:
10375: my $num1=$symbchck+$symbseed+$namechck;
10376: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10377: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10378: #&logthis("rndseed :$num:$symb");
1.564 albertel 10379: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.366 albertel 10380: return "$num1,$num2";
1.155 albertel 10381: }
1.366 albertel 10382: }
10383:
1.443 albertel 10384: sub rndseed_64bit2 {
10385: my ($symb,$courseid,$domain,$username)=@_;
10386: {
10387: use integer;
10388: # strings need to be an even # of cahracters long, it it is odd the
10389: # last characters gets thrown away
10390: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10391: my $symbseed=numval($symb) << 10;
10392: my $namechck=unpack("%32S*",$username.' ');
10393:
10394: my $nameseed=numval($username) << 21;
1.501 albertel 10395: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10396: my $courseseed=unpack("%32S*",$courseid.' ');
10397:
10398: my $num1=$symbchck+$symbseed+$namechck;
10399: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10400: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10401: #&logthis("rndseed :$num:$symb");
1.803 albertel 10402: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.501 albertel 10403: return "$num1,$num2";
10404: }
10405: }
10406:
10407: sub rndseed_64bit3 {
10408: my ($symb,$courseid,$domain,$username)=@_;
10409: {
10410: use integer;
10411: # strings need to be an even # of cahracters long, it it is odd the
10412: # last characters gets thrown away
10413: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10414: my $symbseed=numval2($symb) << 10;
10415: my $namechck=unpack("%32S*",$username.' ');
10416:
10417: my $nameseed=numval2($username) << 21;
1.443 albertel 10418: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10419: my $courseseed=unpack("%32S*",$courseid.' ');
10420:
10421: my $num1=$symbchck+$symbseed+$namechck;
10422: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10423: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10424: #&logthis("rndseed :$num1:$num2:$_64bit");
1.564 albertel 10425: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10426:
1.503 albertel 10427: return "$num1:$num2";
1.443 albertel 10428: }
10429: }
10430:
1.575 albertel 10431: sub rndseed_64bit4 {
10432: my ($symb,$courseid,$domain,$username)=@_;
10433: {
10434: use integer;
10435: # strings need to be an even # of cahracters long, it it is odd the
10436: # last characters gets thrown away
10437: my $symbchck=unpack("%32S*",$symb.' ') << 21;
10438: my $symbseed=numval3($symb) << 10;
10439: my $namechck=unpack("%32S*",$username.' ');
10440:
10441: my $nameseed=numval3($username) << 21;
10442: my $domainseed=unpack("%32S*",$domain.' ') << 10;
10443: my $courseseed=unpack("%32S*",$courseid.' ');
10444:
10445: my $num1=$symbchck+$symbseed+$namechck;
10446: my $num2=$nameseed+$domainseed+$courseseed;
1.790 albertel 10447: #&logthis("$symbseed:$nameseed;$domainseed|$courseseed;$namechck:$symbchck");
10448: #&logthis("rndseed :$num1:$num2:$_64bit");
1.575 albertel 10449: if ($_64bit) { $num1=(($num1<<32)>>32); $num2=(($num2<<32)>>32); }
1.1110 www 10450:
1.575 albertel 10451: return "$num1:$num2";
10452: }
10453: }
10454:
1.675 albertel 10455: sub rndseed_64bit5 {
10456: my ($symb,$courseid,$domain,$username)=@_;
10457: my ($num1,$num2)=&digest("$symb,$courseid,$domain,$username");
10458: return "$num1:$num2";
10459: }
10460:
1.366 albertel 10461: sub rndseed_CODE_64bit {
10462: my ($symb,$courseid,$domain,$username)=@_;
1.155 albertel 10463: {
1.366 albertel 10464: use integer;
1.443 albertel 10465: my $symbchck=unpack("%32S*",$symb.' ') << 16;
1.484 albertel 10466: my $symbseed=numval2($symb);
1.491 albertel 10467: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10468: my $CODEseed=numval(&getCODE());
1.443 albertel 10469: my $courseseed=unpack("%32S*",$courseid.' ');
1.484 albertel 10470: my $num1=$symbseed+$CODEchck;
10471: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10472: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10473: #&logthis("rndseed :$num1:$num2:$symb");
1.564 albertel 10474: if ($_64bit) { $num1=(($num1<<32)>>32); }
10475: if ($_64bit) { $num2=(($num2<<32)>>32); }
1.503 albertel 10476: return "$num1:$num2";
1.366 albertel 10477: }
10478: }
10479:
1.575 albertel 10480: sub rndseed_CODE_64bit4 {
10481: my ($symb,$courseid,$domain,$username)=@_;
10482: {
10483: use integer;
10484: my $symbchck=unpack("%32S*",$symb.' ') << 16;
10485: my $symbseed=numval3($symb);
10486: my $CODEchck=unpack("%32S*",&getCODE().' ') << 16;
10487: my $CODEseed=numval3(&getCODE());
10488: my $courseseed=unpack("%32S*",$courseid.' ');
10489: my $num1=$symbseed+$CODEchck;
10490: my $num2=$CODEseed+$courseseed+$symbchck;
1.790 albertel 10491: #&logthis("$symbseed:$CODEchck|$CODEseed:$courseseed:$symbchck");
10492: #&logthis("rndseed :$num1:$num2:$symb");
1.575 albertel 10493: if ($_64bit) { $num1=(($num1<<32)>>32); }
10494: if ($_64bit) { $num2=(($num2<<32)>>32); }
10495: return "$num1:$num2";
10496: }
10497: }
10498:
1.675 albertel 10499: sub rndseed_CODE_64bit5 {
10500: my ($symb,$courseid,$domain,$username)=@_;
10501: my $code = &getCODE();
10502: my ($num1,$num2)=&digest("$symb,$courseid,$code");
10503: return "$num1:$num2";
10504: }
10505:
1.366 albertel 10506: sub setup_random_from_rndseed {
10507: my ($rndseed)=@_;
1.503 albertel 10508: if ($rndseed =~/([,:])/) {
10509: my ($num1,$num2)=split(/[,:]/,$rndseed);
1.366 albertel 10510: &Math::Random::random_set_seed(abs($num1),abs($num2));
10511: } else {
10512: &Math::Random::random_set_seed_from_phrase($rndseed);
1.98 albertel 10513: }
1.36 albertel 10514: }
10515:
1.474 albertel 10516: sub latest_receipt_algorithm_id {
1.835 albertel 10517: return 'receipt3';
1.474 albertel 10518: }
10519:
1.480 www 10520: sub recunique {
10521: my $fucourseid=shift;
10522: my $unique;
1.835 albertel 10523: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2' ||
10524: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10525: $unique=$env{"course.$fucourseid.internal.encseed"};
1.480 www 10526: } else {
10527: $unique=$perlvar{'lonReceipt'};
10528: }
10529: return unpack("%32C*",$unique);
10530: }
10531:
10532: sub recprefix {
10533: my $fucourseid=shift;
10534: my $prefix;
1.835 albertel 10535: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2'||
10536: $env{"course.$fucourseid.receiptalg"} eq 'receipt3' ) {
1.620 albertel 10537: $prefix=$env{"course.$fucourseid.internal.encpref"};
1.480 www 10538: } else {
10539: $prefix=$perlvar{'lonHostID'};
10540: }
10541: return unpack("%32C*",$prefix);
10542: }
10543:
1.76 www 10544: sub ireceipt {
1.474 albertel 10545: my ($funame,$fudom,$fucourseid,$fusymb,$part)=@_;
1.835 albertel 10546:
10547: my $return =&recprefix($fucourseid).'-';
10548:
10549: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt3' ||
10550: $env{'request.state'} eq 'construct') {
10551: $return .= (&digest("$funame,$fudom,$fucourseid,$fusymb,$part")%10000);
10552: return $return;
10553: }
10554:
1.76 www 10555: my $cuname=unpack("%32C*",$funame);
10556: my $cudom=unpack("%32C*",$fudom);
10557: my $cucourseid=unpack("%32C*",$fucourseid);
10558: my $cusymb=unpack("%32C*",$fusymb);
1.480 www 10559: my $cunique=&recunique($fucourseid);
1.474 albertel 10560: my $cpart=unpack("%32S*",$part);
1.835 albertel 10561: if ($env{"course.$fucourseid.receiptalg"} eq 'receipt2') {
10562:
1.790 albertel 10563: #&logthis("doing receipt2 using parts $cpart, uname $cuname and udom $cudom gets ".($cpart%$cuname)." and ".($cpart%$cudom));
1.474 albertel 10564:
10565: $return.= ($cunique%$cuname+
10566: $cunique%$cudom+
10567: $cusymb%$cuname+
10568: $cusymb%$cudom+
10569: $cucourseid%$cuname+
10570: $cucourseid%$cudom+
10571: $cpart%$cuname+
10572: $cpart%$cudom);
10573: } else {
10574: $return.= ($cunique%$cuname+
10575: $cunique%$cudom+
10576: $cusymb%$cuname+
10577: $cusymb%$cudom+
10578: $cucourseid%$cuname+
10579: $cucourseid%$cudom);
10580: }
10581: return $return;
1.76 www 10582: }
10583:
10584: sub receipt {
1.474 albertel 10585: my ($part)=@_;
1.790 albertel 10586: my ($symb,$courseid,$domain,$name) = &whichuser();
1.474 albertel 10587: return &ireceipt($name,$domain,$courseid,$symb,$part);
1.76 www 10588: }
1.260 ng 10589:
1.790 albertel 10590: sub whichuser {
10591: my ($passedsymb)=@_;
10592: my ($symb,$courseid,$domain,$name,$publicuser);
10593: if (defined($env{'form.grade_symb'})) {
10594: my ($tmp_courseid)=&get_env_multiple('form.grade_courseid');
10595: my $allowed=&allowed('vgr',$tmp_courseid);
10596: if (!$allowed &&
10597: exists($env{'request.course.sec'}) &&
10598: $env{'request.course.sec'} !~ /^\s*$/) {
10599: $allowed=&allowed('vgr',$tmp_courseid.
10600: '/'.$env{'request.course.sec'});
10601: }
10602: if ($allowed) {
10603: ($symb)=&get_env_multiple('form.grade_symb');
10604: $courseid=$tmp_courseid;
10605: ($domain)=&get_env_multiple('form.grade_domain');
10606: ($name)=&get_env_multiple('form.grade_username');
10607: return ($symb,$courseid,$domain,$name,$publicuser);
10608: }
10609: }
10610: if (!$passedsymb) {
10611: $symb=&symbread();
10612: } else {
10613: $symb=$passedsymb;
10614: }
10615: $courseid=$env{'request.course.id'};
10616: $domain=$env{'user.domain'};
10617: $name=$env{'user.name'};
10618: if ($name eq 'public' && $domain eq 'public') {
10619: if (!defined($env{'form.username'})) {
10620: $env{'form.username'}.=time.rand(10000000);
10621: }
10622: $name.=$env{'form.username'};
10623: }
10624: return ($symb,$courseid,$domain,$name,$publicuser);
10625:
10626: }
10627:
1.36 albertel 10628: # ------------------------------------------------------------ Serves up a file
1.472 albertel 10629: # returns either the contents of the file or
10630: # -1 if the file doesn't exist
1.481 raeburn 10631: #
10632: # if the target is a file that was uploaded via DOCS,
10633: # a check will be made to see if a current copy exists on the local server,
10634: # if it does this will be served, otherwise a copy will be retrieved from
10635: # the home server for the course and stored in /home/httpd/html/userfiles on
10636: # the local server.
1.472 albertel 10637:
1.36 albertel 10638: sub getfile {
1.538 albertel 10639: my ($file) = @_;
1.609 banghart 10640: if ($file =~ m -^/*(uploaded|editupload)/-) { $file=&filelocation("",$file); }
1.538 albertel 10641: &repcopy($file);
10642: return &readfile($file);
10643: }
10644:
10645: sub repcopy_userfile {
10646: my ($file)=@_;
1.1142 raeburn 10647: my $londocroot = $perlvar{'lonDocRoot'};
10648: if ($file =~ m{^/*(uploaded|editupload)/}) { $file=&filelocation("",$file); }
1.1164 raeburn 10649: if ($file =~ m{^\Q/home/httpd/lonUsers/\E}) { return 'ok'; }
1.538 albertel 10650: my ($cdom,$cnum,$filename) =
1.811 albertel 10651: ($file=~m|^\Q$perlvar{'lonDocRoot'}\E/+userfiles/+($match_domain)/+($match_name)/+(.*)|);
1.538 albertel 10652: my $uri="/uploaded/$cdom/$cnum/$filename";
10653: if (-e "$file") {
1.828 www 10654: # we already have a local copy, check it out
1.538 albertel 10655: my @fileinfo = stat($file);
1.828 www 10656: my $rtncode;
10657: my $info;
1.538 albertel 10658: my $lwpresp = &getuploaded('HEAD',$uri,$cdom,$cnum,\$info,\$rtncode);
1.482 albertel 10659: if ($lwpresp ne 'ok') {
1.828 www 10660: # there is no such file anymore, even though we had a local copy
1.482 albertel 10661: if ($rtncode eq '404') {
1.538 albertel 10662: unlink($file);
1.482 albertel 10663: }
10664: return -1;
10665: }
10666: if ($info < $fileinfo[9]) {
1.828 www 10667: # nice, the file we have is up-to-date, just say okay
1.607 raeburn 10668: return 'ok';
1.828 www 10669: } else {
10670: # the file is outdated, get rid of it
10671: unlink($file);
1.482 albertel 10672: }
1.828 www 10673: }
10674: # one way or the other, at this point, we don't have the file
10675: # construct the correct path for the file
10676: my @parts = ($cdom,$cnum);
10677: if ($filename =~ m|^(.+)/[^/]+$|) {
10678: push @parts, split(/\//,$1);
10679: }
10680: my $path = $perlvar{'lonDocRoot'}.'/userfiles';
10681: foreach my $part (@parts) {
10682: $path .= '/'.$part;
10683: if (!-e $path) {
10684: mkdir($path,0770);
1.482 albertel 10685: }
10686: }
1.828 www 10687: # now the path exists for sure
10688: # get a user agent
10689: my $ua=new LWP::UserAgent;
10690: my $transferfile=$file.'.in.transfer';
10691: # FIXME: this should flock
10692: if (-e $transferfile) { return 'ok'; }
10693: my $request;
10694: $uri=~s/^\///;
1.980 raeburn 10695: my $homeserver = &homeserver($cnum,$cdom);
10696: my $protocol = $protocol{$homeserver};
10697: $protocol = 'http' if ($protocol ne 'https');
10698: $request=new HTTP::Request('GET',$protocol.'://'.&hostname($homeserver).'/raw/'.$uri);
1.828 www 10699: my $response=$ua->request($request,$transferfile);
10700: # did it work?
10701: if ($response->is_error()) {
10702: unlink($transferfile);
10703: &logthis("Userfile repcopy failed for $uri");
10704: return -1;
10705: }
10706: # worked, rename the transfer file
10707: rename($transferfile,$file);
1.607 raeburn 10708: return 'ok';
1.481 raeburn 10709: }
10710:
1.517 albertel 10711: sub tokenwrapper {
10712: my $uri=shift;
1.980 raeburn 10713: $uri=~s|^https?\://([^/]+)||;
1.552 albertel 10714: $uri=~s|^/||;
1.620 albertel 10715: $env{'user.environment'}=~/\/([^\/]+)\.id/;
1.517 albertel 10716: my $token=$1;
1.552 albertel 10717: my (undef,$udom,$uname,$file)=split('/',$uri,4);
10718: if ($udom && $uname && $file) {
10719: $file=~s|(\?\.*)*$||;
1.949 raeburn 10720: &appenv({"userfile.$udom/$uname/$file" => $env{'request.course.id'}});
1.980 raeburn 10721: my $homeserver = &homeserver($uname,$udom);
10722: my $protocol = $protocol{$homeserver};
10723: $protocol = 'http' if ($protocol ne 'https');
10724: return $protocol.'://'.&hostname($homeserver).'/'.$uri.
1.517 albertel 10725: (($uri=~/\?/)?'&':'?').'token='.$token.
10726: '&tokenissued='.$perlvar{'lonHostID'};
10727: } else {
10728: return '/adm/notfound.html';
10729: }
10730: }
10731:
1.828 www 10732: # call with reqtype HEAD: get last modification time
10733: # call with reqtype GET: get the file contents
10734: # Do not call this with reqtype GET for large files! It loads everything into memory
10735: #
1.481 raeburn 10736: sub getuploaded {
10737: my ($reqtype,$uri,$cdom,$cnum,$info,$rtncode) = @_;
10738: $uri=~s/^\///;
1.980 raeburn 10739: my $homeserver = &homeserver($cnum,$cdom);
10740: my $protocol = $protocol{$homeserver};
10741: $protocol = 'http' if ($protocol ne 'https');
10742: $uri = $protocol.'://'.&hostname($homeserver).'/raw/'.$uri;
1.481 raeburn 10743: my $ua=new LWP::UserAgent;
10744: my $request=new HTTP::Request($reqtype,$uri);
10745: my $response=$ua->request($request);
10746: $$rtncode = $response->code;
1.482 albertel 10747: if (! $response->is_success()) {
10748: return 'failed';
10749: }
10750: if ($reqtype eq 'HEAD') {
1.486 www 10751: $$info = &HTTP::Date::str2time( $response->header('Last-modified') );
1.482 albertel 10752: } elsif ($reqtype eq 'GET') {
10753: $$info = $response->content;
1.472 albertel 10754: }
1.482 albertel 10755: return 'ok';
1.36 albertel 10756: }
10757:
1.481 raeburn 10758: sub readfile {
10759: my $file = shift;
10760: if ( (! -e $file ) || ($file eq '') ) { return -1; };
10761: my $fh;
10762: open($fh,"<$file");
10763: my $a='';
1.800 albertel 10764: while (my $line = <$fh>) { $a .= $line; }
1.481 raeburn 10765: return $a;
10766: }
10767:
1.36 albertel 10768: sub filelocation {
1.590 banghart 10769: my ($dir,$file) = @_;
10770: my $location;
10771: $file=~ s/^\s*(\S+)\s*$/$1/; ## strip off leading and trailing spaces
1.700 albertel 10772:
10773: if ($file =~ m-^/adm/-) {
10774: $file=~s-^/adm/wrapper/-/-;
10775: $file=~s-^/adm/coursedocs/showdoc/-/-;
10776: }
1.882 albertel 10777:
1.1139 www 10778: if ($file =~ m-^\Q$Apache::lonnet::perlvar{'lonTabDir'}\E/-) {
1.956 raeburn 10779: $location = $file;
1.609 banghart 10780: } elsif ($file=~/^\/*(uploaded|editupload)/) { # is an uploaded file
1.590 banghart 10781: my ($udom,$uname,$filename)=
1.811 albertel 10782: ($file=~m -^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$-);
1.590 banghart 10783: my $home=&homeserver($uname,$udom);
10784: my $is_me=0;
10785: my @ids=¤t_machine_ids();
10786: foreach my $id (@ids) { if ($id eq $home) { $is_me=1; } }
10787: if ($is_me) {
1.1117 foxr 10788: $location=propath($udom,$uname).'/userfiles/'.$filename;
1.590 banghart 10789: } else {
10790: $location=$Apache::lonnet::perlvar{'lonDocRoot'}.'/userfiles/'.
10791: $udom.'/'.$uname.'/'.$filename;
10792: }
1.882 albertel 10793: } elsif ($file =~ m-^/adm/-) {
10794: $location = $perlvar{'lonDocRoot'}.'/'.$file;
1.590 banghart 10795: } else {
10796: $file=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.1139 www 10797: $file=~s:^/(res|priv)/:/:;
10798: my $space=$1;
1.590 banghart 10799: if ( !( $file =~ m:^/:) ) {
10800: $location = $dir. '/'.$file;
10801: } else {
1.1142 raeburn 10802: $location = $perlvar{'lonDocRoot'}.'/'.$space.$file;
1.590 banghart 10803: }
1.59 albertel 10804: }
1.590 banghart 10805: $location=~s://+:/:g; # remove duplicate /
1.930 albertel 10806: while ($location=~m{/\.\./}) {
10807: if ($location =~ m{/[^/]+/\.\./}) {
10808: $location=~ s{/[^/]+/\.\./}{/}g;
10809: } else {
10810: $location=~ s{/\.\./}{/}g;
10811: }
10812: } #remove dir/..
1.590 banghart 10813: while ($location=~m:/\./:) {$location=~ s:/\./:/:g;} #remove /./
10814: return $location;
1.46 www 10815: }
1.36 albertel 10816:
1.46 www 10817: sub hreflocation {
10818: my ($dir,$file)=@_;
1.980 raeburn 10819: unless (($file=~m-^https?\://-i) || ($file=~m-^/-)) {
1.666 albertel 10820: $file=filelocation($dir,$file);
1.700 albertel 10821: } elsif ($file=~m-^/adm/-) {
10822: $file=~s-^/adm/wrapper/-/-;
10823: $file=~s-^/adm/coursedocs/showdoc/-/-;
1.666 albertel 10824: }
10825: if ($file=~m-^\Q$perlvar{'lonDocRoot'}\E-) {
10826: $file=~s-^\Q$perlvar{'lonDocRoot'}\E--;
10827: } elsif ($file=~m-^\Q$perlvar{'lonUsersDir'}\E-) {
1.1143 raeburn 10828: $file=~s{^/home/httpd/lonUsers/($match_domain)/./././($match_name)/userfiles/}
10829: {/uploaded/$1/$2/}x;
1.46 www 10830: }
1.913 albertel 10831: if ($file=~ m{^/userfiles/}) {
10832: $file =~ s{^/userfiles/}{/uploaded/};
10833: }
1.462 albertel 10834: return $file;
1.465 albertel 10835: }
10836:
1.1139 www 10837:
10838:
10839:
10840:
1.465 albertel 10841: sub current_machine_domains {
1.853 albertel 10842: return &machine_domains(&hostname($perlvar{'lonHostID'}));
10843: }
10844:
10845: sub machine_domains {
10846: my ($hostname) = @_;
1.465 albertel 10847: my @domains;
1.838 albertel 10848: my %hostname = &all_hostnames();
1.465 albertel 10849: while( my($id, $name) = each(%hostname)) {
1.467 matthew 10850: # &logthis("-$id-$name-$hostname-");
1.465 albertel 10851: if ($hostname eq $name) {
1.844 albertel 10852: push(@domains,&host_domain($id));
1.465 albertel 10853: }
10854: }
10855: return @domains;
10856: }
10857:
10858: sub current_machine_ids {
1.853 albertel 10859: return &machine_ids(&hostname($perlvar{'lonHostID'}));
10860: }
10861:
10862: sub machine_ids {
10863: my ($hostname) = @_;
10864: $hostname ||= &hostname($perlvar{'lonHostID'});
1.465 albertel 10865: my @ids;
1.888 albertel 10866: my %name_to_host = &all_names();
1.889 albertel 10867: if (ref($name_to_host{$hostname}) eq 'ARRAY') {
10868: return @{ $name_to_host{$hostname} };
10869: }
10870: return;
1.31 www 10871: }
10872:
1.824 raeburn 10873: sub additional_machine_domains {
10874: my @domains;
10875: open(my $fh,"<$perlvar{'lonTabDir'}/expected_domains.tab");
10876: while( my $line = <$fh>) {
10877: $line =~ s/\s//g;
10878: push(@domains,$line);
10879: }
10880: return @domains;
10881: }
10882:
10883: sub default_login_domain {
10884: my $domain = $perlvar{'lonDefDomain'};
10885: my $testdomain=(split(/\./,$ENV{'HTTP_HOST'}))[0];
10886: foreach my $posdom (¤t_machine_domains(),
10887: &additional_machine_domains()) {
10888: if (lc($posdom) eq lc($testdomain)) {
10889: $domain=$posdom;
10890: last;
10891: }
10892: }
10893: return $domain;
10894: }
10895:
1.31 www 10896: # ------------------------------------------------------------- Declutters URLs
10897:
10898: sub declutter {
10899: my $thisfn=shift;
1.569 albertel 10900: if ($thisfn=~m|^/enc/|) { $thisfn=&Apache::lonenc::unencrypted($thisfn); }
1.479 albertel 10901: $thisfn=~s/^\Q$perlvar{'lonDocRoot'}\E//;
1.31 www 10902: $thisfn=~s/^\///;
1.697 albertel 10903: $thisfn=~s|^adm/wrapper/||;
10904: $thisfn=~s|^adm/coursedocs/showdoc/||;
1.31 www 10905: $thisfn=~s/^res\///;
1.1172 bisitz 10906: $thisfn=~s/^priv\///;
1.1032 raeburn 10907: unless (($thisfn =~ /^ext/) || ($thisfn =~ /\.(page|sequence)___\d+___ext/)) {
10908: $thisfn=~s/\?.+$//;
10909: }
1.268 www 10910: return $thisfn;
10911: }
10912:
10913: # ------------------------------------------------------------- Clutter up URLs
10914:
10915: sub clutter {
10916: my $thisfn='/'.&declutter(shift);
1.887 albertel 10917: if ($thisfn !~ m{^/(uploaded|editupload|adm|userfiles|ext|raw|priv|public)/}
1.884 albertel 10918: || $thisfn =~ m{^/adm/(includes|pages)} ) {
1.270 www 10919: $thisfn='/res'.$thisfn;
10920: }
1.1031 raeburn 10921: if ($thisfn !~m|^/adm|) {
10922: if ($thisfn =~ m|^/ext/|) {
1.694 albertel 10923: $thisfn='/adm/wrapper'.$thisfn;
1.695 albertel 10924: } else {
10925: my ($ext) = ($thisfn =~ /\.(\w+)$/);
10926: my $embstyle=&Apache::loncommon::fileembstyle($ext);
1.698 albertel 10927: if ($embstyle eq 'ssi'
10928: || ($embstyle eq 'hdn')
10929: || ($embstyle eq 'rat')
10930: || ($embstyle eq 'prv')
10931: || ($embstyle eq 'ign')) {
10932: #do nothing with these
10933: } elsif (($embstyle eq 'img')
1.695 albertel 10934: || ($embstyle eq 'emb')
10935: || ($embstyle eq 'wrp')) {
10936: $thisfn='/adm/wrapper'.$thisfn;
1.698 albertel 10937: } elsif ($embstyle eq 'unk'
10938: && $thisfn!~/\.(sequence|page)$/) {
1.695 albertel 10939: $thisfn='/adm/coursedocs/showdoc'.$thisfn;
1.698 albertel 10940: } else {
1.718 www 10941: # &logthis("Got a blank emb style");
1.695 albertel 10942: }
1.694 albertel 10943: }
10944: }
1.31 www 10945: return $thisfn;
1.12 www 10946: }
10947:
1.787 albertel 10948: sub clutter_with_no_wrapper {
10949: my $uri = &clutter(shift);
10950: if ($uri =~ m-^/adm/-) {
10951: $uri =~ s-^/adm/wrapper/-/-;
10952: $uri =~ s-^/adm/coursedocs/showdoc/-/-;
10953: }
10954: return $uri;
10955: }
10956:
1.557 albertel 10957: sub freeze_escape {
10958: my ($value)=@_;
10959: if (ref($value)) {
10960: $value=&nfreeze($value);
10961: return '__FROZEN__'.&escape($value);
10962: }
10963: return &escape($value);
10964: }
10965:
1.11 www 10966:
1.557 albertel 10967: sub thaw_unescape {
10968: my ($value)=@_;
10969: if ($value =~ /^__FROZEN__/) {
10970: substr($value,0,10,undef);
10971: $value=&unescape($value);
10972: return &thaw($value);
10973: }
10974: return &unescape($value);
10975: }
10976:
1.436 albertel 10977: sub correct_line_ends {
10978: my ($result)=@_;
10979: $$result =~s/\r\n/\n/mg;
10980: $$result =~s/\r/\n/mg;
1.415 albertel 10981: }
1.1 albertel 10982: # ================================================================ Main Program
10983:
1.184 www 10984: sub goodbye {
1.204 albertel 10985: &logthis("Starting Shut down");
1.443 albertel 10986: #not converted to using infrastruture and probably shouldn't be
1.870 albertel 10987: &logthis(sprintf("%-20s is %s",'%badServerCache',length(&nfreeze(\%badServerCache))));
1.443 albertel 10988: #converted
1.599 albertel 10989: # &logthis(sprintf("%-20s is %s",'%metacache',scalar(%metacache)));
1.870 albertel 10990: &logthis(sprintf("%-20s is %s",'%homecache',length(&nfreeze(\%homecache))));
10991: # &logthis(sprintf("%-20s is %s",'%titlecache',length(&nfreeze(\%titlecache))));
10992: # &logthis(sprintf("%-20s is %s",'%courseresdatacache',length(&nfreeze(\%courseresdatacache))));
1.425 albertel 10993: #1.1 only
1.870 albertel 10994: # &logthis(sprintf("%-20s is %s",'%userresdatacache',length(&nfreeze(\%userresdatacache))));
10995: # &logthis(sprintf("%-20s is %s",'%getsectioncache',length(&nfreeze(\%getsectioncache))));
10996: # &logthis(sprintf("%-20s is %s",'%courseresversioncache',length(&nfreeze(\%courseresversioncache))));
10997: # &logthis(sprintf("%-20s is %s",'%resversioncache',length(&nfreeze(\%resversioncache))));
10998: &logthis(sprintf("%-20s is %s",'%remembered',length(&nfreeze(\%remembered))));
1.599 albertel 10999: &logthis(sprintf("%-20s is %s",'kicks',$kicks));
11000: &logthis(sprintf("%-20s is %s",'hits',$hits));
1.184 www 11001: &flushcourselogs();
11002: &logthis("Shutting down");
11003: }
11004:
1.852 albertel 11005: sub get_dns {
1.869 albertel 11006: my ($url,$func,$ignore_cache) = @_;
11007: if (!$ignore_cache) {
11008: my ($content,$cached)=
11009: &Apache::lonnet::is_cached_new('dns',$url);
11010: if ($cached) {
11011: &$func($content);
11012: return;
11013: }
11014: }
11015:
11016: my %alldns;
1.852 albertel 11017: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11018: foreach my $dns (<$config>) {
11019: next if ($dns !~ /^\^(\S*)/x);
1.979 raeburn 11020: my $line = $1;
11021: my ($host,$protocol) = split(/:/,$line);
11022: if ($protocol ne 'https') {
11023: $protocol = 'http';
11024: }
11025: $alldns{$host} = $protocol;
1.869 albertel 11026: }
11027: while (%alldns) {
11028: my ($dns) = keys(%alldns);
1.852 albertel 11029: my $ua=new LWP::UserAgent;
1.1134 raeburn 11030: $ua->timeout(30);
1.979 raeburn 11031: my $request=new HTTP::Request('GET',"$alldns{$dns}://$dns$url");
1.852 albertel 11032: my $response=$ua->request($request);
1.979 raeburn 11033: delete($alldns{$dns});
1.852 albertel 11034: next if ($response->is_error());
11035: my @content = split("\n",$response->content);
1.869 albertel 11036: &Apache::lonnet::do_cache_new('dns',$url,\@content,30*24*60*60);
1.852 albertel 11037: &$func(\@content);
1.869 albertel 11038: return;
1.852 albertel 11039: }
11040: close($config);
1.871 albertel 11041: my $which = (split('/',$url))[3];
11042: &logthis("unable to contact DNS defaulting to on disk file dns_$which.tab\n");
11043: open($config,"<$perlvar{'lonTabDir'}/dns_$which.tab");
1.869 albertel 11044: my @content = <$config>;
11045: &$func(\@content);
11046: return;
1.852 albertel 11047: }
1.327 albertel 11048: # ------------------------------------------------------------ Read domain file
11049: {
1.852 albertel 11050: my $loaded;
1.846 albertel 11051: my %domain;
11052:
1.852 albertel 11053: sub parse_domain_tab {
11054: my ($lines) = @_;
11055: foreach my $line (@$lines) {
11056: next if ($line =~ /^(\#|\s*$ )/x);
1.403 www 11057:
1.846 albertel 11058: chomp($line);
1.852 albertel 11059: my ($name,@elements) = split(/:/,$line,9);
1.846 albertel 11060: my %this_domain;
11061: foreach my $field ('description', 'auth_def', 'auth_arg_def',
11062: 'lang_def', 'city', 'longi', 'lati',
11063: 'primary') {
11064: $this_domain{$field} = shift(@elements);
11065: }
11066: $domain{$name} = \%this_domain;
1.852 albertel 11067: }
11068: }
1.864 albertel 11069:
11070: sub reset_domain_info {
11071: undef($loaded);
11072: undef(%domain);
11073: }
11074:
1.852 albertel 11075: sub load_domain_tab {
1.869 albertel 11076: my ($ignore_cache) = @_;
11077: &get_dns('/adm/dns/domain',\&parse_domain_tab,$ignore_cache);
1.852 albertel 11078: my $fh;
11079: if (open($fh,"<".$perlvar{'lonTabDir'}.'/domain.tab')) {
11080: my @lines = <$fh>;
11081: &parse_domain_tab(\@lines);
1.448 albertel 11082: }
1.852 albertel 11083: close($fh);
11084: $loaded = 1;
1.327 albertel 11085: }
1.846 albertel 11086:
11087: sub domain {
1.852 albertel 11088: &load_domain_tab() if (!$loaded);
11089:
1.846 albertel 11090: my ($name,$what) = @_;
11091: return if ( !exists($domain{$name}) );
11092:
11093: if (!$what) {
11094: return $domain{$name}{'description'};
11095: }
11096: return $domain{$name}{$what};
11097: }
1.974 raeburn 11098:
11099: sub domain_info {
11100: &load_domain_tab() if (!$loaded);
11101: return %domain;
11102: }
11103:
1.327 albertel 11104: }
11105:
11106:
1.1 albertel 11107: # ------------------------------------------------------------- Read hosts file
11108: {
1.838 albertel 11109: my %hostname;
1.844 albertel 11110: my %hostdom;
1.845 albertel 11111: my %libserv;
1.852 albertel 11112: my $loaded;
1.888 albertel 11113: my %name_to_host;
1.1074 raeburn 11114: my %internetdom;
1.1107 raeburn 11115: my %LC_dns_serv;
1.852 albertel 11116:
11117: sub parse_hosts_tab {
11118: my ($file) = @_;
11119: foreach my $configline (@$file) {
11120: next if ($configline =~ /^(\#|\s*$ )/x);
1.1107 raeburn 11121: chomp($configline);
11122: if ($configline =~ /^\^/) {
11123: if ($configline =~ /^\^([\w.\-]+)/) {
11124: $LC_dns_serv{$1} = 1;
11125: }
11126: next;
11127: }
1.1074 raeburn 11128: my ($id,$domain,$role,$name,$protocol,$intdom)=split(/:/,$configline);
1.852 albertel 11129: $name=~s/\s//g;
11130: if ($id && $domain && $role && $name) {
11131: $hostname{$id}=$name;
1.888 albertel 11132: push(@{$name_to_host{$name}}, $id);
1.852 albertel 11133: $hostdom{$id}=$domain;
11134: if ($role eq 'library') { $libserv{$id}=$name; }
1.969 raeburn 11135: if (defined($protocol)) {
11136: if ($protocol eq 'https') {
11137: $protocol{$id} = $protocol;
11138: } else {
11139: $protocol{$id} = 'http';
11140: }
1.968 raeburn 11141: } else {
1.969 raeburn 11142: $protocol{$id} = 'http';
1.968 raeburn 11143: }
1.1074 raeburn 11144: if (defined($intdom)) {
11145: $internetdom{$id} = $intdom;
11146: }
1.852 albertel 11147: }
11148: }
11149: }
1.864 albertel 11150:
11151: sub reset_hosts_info {
1.897 albertel 11152: &purge_remembered();
1.864 albertel 11153: &reset_domain_info();
11154: &reset_hosts_ip_info();
1.892 albertel 11155: undef(%name_to_host);
1.864 albertel 11156: undef(%hostname);
11157: undef(%hostdom);
11158: undef(%libserv);
11159: undef($loaded);
11160: }
1.1 albertel 11161:
1.852 albertel 11162: sub load_hosts_tab {
1.869 albertel 11163: my ($ignore_cache) = @_;
11164: &get_dns('/adm/dns/hosts',\&parse_hosts_tab,$ignore_cache);
1.852 albertel 11165: open(my $config,"<$perlvar{'lonTabDir'}/hosts.tab");
11166: my @config = <$config>;
11167: &parse_hosts_tab(\@config);
11168: close($config);
11169: $loaded=1;
1.1 albertel 11170: }
1.852 albertel 11171:
1.838 albertel 11172: sub hostname {
1.852 albertel 11173: &load_hosts_tab() if (!$loaded);
11174:
1.838 albertel 11175: my ($lonid) = @_;
11176: return $hostname{$lonid};
11177: }
1.845 albertel 11178:
1.838 albertel 11179: sub all_hostnames {
1.852 albertel 11180: &load_hosts_tab() if (!$loaded);
11181:
1.838 albertel 11182: return %hostname;
11183: }
1.845 albertel 11184:
1.888 albertel 11185: sub all_names {
11186: &load_hosts_tab() if (!$loaded);
11187:
11188: return %name_to_host;
11189: }
11190:
1.974 raeburn 11191: sub all_host_domain {
11192: &load_hosts_tab() if (!$loaded);
11193: return %hostdom;
11194: }
11195:
1.845 albertel 11196: sub is_library {
1.852 albertel 11197: &load_hosts_tab() if (!$loaded);
11198:
1.845 albertel 11199: return exists($libserv{$_[0]});
11200: }
11201:
11202: sub all_library {
1.852 albertel 11203: &load_hosts_tab() if (!$loaded);
11204:
1.845 albertel 11205: return %libserv;
11206: }
11207:
1.1062 droeschl 11208: sub unique_library {
11209: #2x reverse removes all hostnames that appear more than once
11210: my %unique = reverse &all_library();
11211: return reverse %unique;
11212: }
11213:
1.841 albertel 11214: sub get_servers {
1.852 albertel 11215: &load_hosts_tab() if (!$loaded);
11216:
1.841 albertel 11217: my ($domain,$type) = @_;
11218: my %possible_hosts = ($type eq 'library') ? %libserv
11219: : %hostname;
11220: my %result;
1.842 albertel 11221: if (ref($domain) eq 'ARRAY') {
11222: while ( my ($host,$hostname) = each(%possible_hosts)) {
1.843 albertel 11223: if (grep(/^\Q$hostdom{$host}\E$/,@$domain)) {
1.842 albertel 11224: $result{$host} = $hostname;
11225: }
11226: }
11227: } else {
11228: while ( my ($host,$hostname) = each(%possible_hosts)) {
11229: if ($hostdom{$host} eq $domain) {
11230: $result{$host} = $hostname;
11231: }
1.841 albertel 11232: }
11233: }
11234: return %result;
11235: }
1.845 albertel 11236:
1.1062 droeschl 11237: sub get_unique_servers {
11238: my %unique = reverse &get_servers(@_);
11239: return reverse %unique;
11240: }
11241:
1.844 albertel 11242: sub host_domain {
1.852 albertel 11243: &load_hosts_tab() if (!$loaded);
11244:
1.844 albertel 11245: my ($lonid) = @_;
11246: return $hostdom{$lonid};
11247: }
11248:
1.841 albertel 11249: sub all_domains {
1.852 albertel 11250: &load_hosts_tab() if (!$loaded);
11251:
1.841 albertel 11252: my %seen;
11253: my @uniq = grep(!$seen{$_}++, values(%hostdom));
11254: return @uniq;
11255: }
1.1074 raeburn 11256:
11257: sub internet_dom {
11258: &load_hosts_tab() if (!$loaded);
11259:
11260: my ($lonid) = @_;
11261: return $internetdom{$lonid};
11262: }
1.1107 raeburn 11263:
11264: sub is_LC_dns {
11265: &load_hosts_tab() if (!$loaded);
11266:
11267: my ($hostname) = @_;
11268: return exists($LC_dns_serv{$hostname});
11269: }
11270:
1.1 albertel 11271: }
11272:
1.847 albertel 11273: {
11274: my %iphost;
1.856 albertel 11275: my %name_to_ip;
11276: my %lonid_to_ip;
1.869 albertel 11277:
1.847 albertel 11278: sub get_hosts_from_ip {
11279: my ($ip) = @_;
11280: my %iphosts = &get_iphost();
11281: if (ref($iphosts{$ip})) {
11282: return @{$iphosts{$ip}};
11283: }
11284: return;
1.839 albertel 11285: }
1.864 albertel 11286:
11287: sub reset_hosts_ip_info {
11288: undef(%iphost);
11289: undef(%name_to_ip);
11290: undef(%lonid_to_ip);
11291: }
1.856 albertel 11292:
11293: sub get_host_ip {
11294: my ($lonid) = @_;
11295: if (exists($lonid_to_ip{$lonid})) {
11296: return $lonid_to_ip{$lonid};
11297: }
11298: my $name=&hostname($lonid);
11299: my $ip = gethostbyname($name);
11300: return if (!$ip || length($ip) ne 4);
11301: $ip=inet_ntoa($ip);
11302: $name_to_ip{$name} = $ip;
11303: $lonid_to_ip{$lonid} = $ip;
11304: return $ip;
11305: }
1.847 albertel 11306:
11307: sub get_iphost {
1.869 albertel 11308: my ($ignore_cache) = @_;
1.894 albertel 11309:
1.869 albertel 11310: if (!$ignore_cache) {
11311: if (%iphost) {
11312: return %iphost;
11313: }
11314: my ($ip_info,$cached)=
11315: &Apache::lonnet::is_cached_new('iphost','iphost');
11316: if ($cached) {
11317: %iphost = %{$ip_info->[0]};
11318: %name_to_ip = %{$ip_info->[1]};
11319: %lonid_to_ip = %{$ip_info->[2]};
11320: return %iphost;
11321: }
11322: }
1.894 albertel 11323:
11324: # get yesterday's info for fallback
11325: my %old_name_to_ip;
11326: my ($ip_info,$cached)=
11327: &Apache::lonnet::is_cached_new('iphost','iphost');
11328: if ($cached) {
11329: %old_name_to_ip = %{$ip_info->[1]};
11330: }
11331:
1.888 albertel 11332: my %name_to_host = &all_names();
11333: foreach my $name (keys(%name_to_host)) {
1.847 albertel 11334: my $ip;
11335: if (!exists($name_to_ip{$name})) {
11336: $ip = gethostbyname($name);
11337: if (!$ip || length($ip) ne 4) {
1.894 albertel 11338: if (defined($old_name_to_ip{$name})) {
11339: $ip = $old_name_to_ip{$name};
11340: &logthis("Can't find $name defaulting to old $ip");
11341: } else {
11342: &logthis("Name $name no IP found");
11343: next;
11344: }
11345: } else {
11346: $ip=inet_ntoa($ip);
1.847 albertel 11347: }
11348: $name_to_ip{$name} = $ip;
11349: } else {
11350: $ip = $name_to_ip{$name};
1.653 albertel 11351: }
1.888 albertel 11352: foreach my $id (@{ $name_to_host{$name} }) {
11353: $lonid_to_ip{$id} = $ip;
11354: }
11355: push(@{$iphost{$ip}},@{$name_to_host{$name}});
1.598 albertel 11356: }
1.869 albertel 11357: &Apache::lonnet::do_cache_new('iphost','iphost',
11358: [\%iphost,\%name_to_ip,\%lonid_to_ip],
1.894 albertel 11359: 48*60*60);
1.869 albertel 11360:
1.847 albertel 11361: return %iphost;
1.598 albertel 11362: }
11363:
1.992 raeburn 11364: #
11365: # Given a DNS returns the loncapa host name for that DNS
11366: #
11367: sub host_from_dns {
11368: my ($dns) = @_;
11369: my @hosts;
11370: my $ip;
11371:
1.993 raeburn 11372: if (exists($name_to_ip{$dns})) {
1.992 raeburn 11373: $ip = $name_to_ip{$dns};
11374: }
11375: if (!$ip) {
11376: $ip = gethostbyname($dns); # Initial translation to IP is in net order.
11377: if (length($ip) == 4) {
11378: $ip = &IO::Socket::inet_ntoa($ip);
11379: }
11380: }
11381: if ($ip) {
11382: @hosts = get_hosts_from_ip($ip);
11383: return $hosts[0];
11384: }
11385: return undef;
1.986 foxr 11386: }
1.992 raeburn 11387:
1.1074 raeburn 11388: sub get_internet_names {
11389: my ($lonid) = @_;
11390: return if ($lonid eq '');
11391: my ($idnref,$cached)=
11392: &Apache::lonnet::is_cached_new('internetnames',$lonid);
11393: if ($cached) {
11394: return $idnref;
11395: }
11396: my $ip = &get_host_ip($lonid);
11397: my @hosts = &get_hosts_from_ip($ip);
11398: my %iphost = &get_iphost();
11399: my (@idns,%seen);
11400: foreach my $id (@hosts) {
11401: my $dom = &host_domain($id);
11402: my $prim_id = &domain($dom,'primary');
11403: my $prim_ip = &get_host_ip($prim_id);
11404: next if ($seen{$prim_ip});
11405: if (ref($iphost{$prim_ip}) eq 'ARRAY') {
11406: foreach my $id (@{$iphost{$prim_ip}}) {
11407: my $intdom = &internet_dom($id);
11408: unless (grep(/^\Q$intdom\E$/,@idns)) {
11409: push(@idns,$intdom);
11410: }
11411: }
11412: }
11413: $seen{$prim_ip} = 1;
11414: }
11415: return &Apache::lonnet::do_cache_new('internetnames',$lonid,\@idns,12*60*60);
11416: }
11417:
1.986 foxr 11418: }
11419:
1.1079 raeburn 11420: sub all_loncaparevs {
11421: 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);
11422: }
11423:
1.862 albertel 11424: BEGIN {
11425:
11426: # ----------------------------------- Read loncapa.conf and loncapa_apache.conf
11427: unless ($readit) {
11428: {
11429: my $configvars = LONCAPA::Configuration::read_conf('loncapa.conf');
11430: %perlvar = (%perlvar,%{$configvars});
11431: }
11432:
11433:
1.1 albertel 11434: # ------------------------------------------------------ Read spare server file
11435: {
1.448 albertel 11436: open(my $config,"<$perlvar{'lonTabDir'}/spare.tab");
1.1 albertel 11437:
11438: while (my $configline=<$config>) {
11439: chomp($configline);
1.284 matthew 11440: if ($configline) {
1.784 albertel 11441: my ($host,$type) = split(':',$configline,2);
1.785 albertel 11442: if (!defined($type) || $type eq '') { $type = 'default' };
1.784 albertel 11443: push(@{ $spareid{$type} }, $host);
1.1 albertel 11444: }
11445: }
1.448 albertel 11446: close($config);
1.1 albertel 11447: }
1.11 www 11448: # ------------------------------------------------------------ Read permissions
11449: {
1.448 albertel 11450: open(my $config,"<$perlvar{'lonTabDir'}/roles.tab");
1.11 www 11451:
11452: while (my $configline=<$config>) {
1.448 albertel 11453: chomp($configline);
11454: if ($configline) {
11455: my ($role,$perm)=split(/ /,$configline);
11456: if ($perm ne '') { $pr{$role}=$perm; }
11457: }
1.11 www 11458: }
1.448 albertel 11459: close($config);
1.11 www 11460: }
11461:
11462: # -------------------------------------------- Read plain texts for permissions
11463: {
1.448 albertel 11464: open(my $config,"<$perlvar{'lonTabDir'}/rolesplain.tab");
1.11 www 11465:
11466: while (my $configline=<$config>) {
1.448 albertel 11467: chomp($configline);
11468: if ($configline) {
1.742 raeburn 11469: my ($short,@plain)=split(/:/,$configline);
11470: %{$prp{$short}} = ();
11471: if (@plain > 0) {
11472: $prp{$short}{'std'} = $plain[0];
11473: for (my $i=1; $i<@plain; $i++) {
11474: $prp{$short}{'alt'.$i} = $plain[$i];
11475: }
11476: }
1.448 albertel 11477: }
1.135 www 11478: }
1.448 albertel 11479: close($config);
1.135 www 11480: }
11481:
11482: # ---------------------------------------------------------- Read package table
11483: {
1.448 albertel 11484: open(my $config,"<$perlvar{'lonTabDir'}/packages.tab");
1.135 www 11485:
11486: while (my $configline=<$config>) {
1.483 albertel 11487: if ($configline !~ /\S/ || $configline=~/^#/) { next; }
1.448 albertel 11488: chomp($configline);
11489: my ($short,$plain)=split(/:/,$configline);
11490: my ($pack,$name)=split(/\&/,$short);
11491: if ($plain ne '') {
11492: $packagetab{$pack.'&'.$name.'&name'}=$name;
11493: $packagetab{$short}=$plain;
11494: }
1.11 www 11495: }
1.448 albertel 11496: close($config);
1.329 matthew 11497: }
11498:
1.1073 raeburn 11499: # ---------------------------------------------------------- Read loncaparev table
11500: {
11501: if (-e "$perlvar{'lonTabDir'}/loncaparevs.tab") {
11502: if (open(my $config,"<$perlvar{'lonTabDir'}/loncaparevs.tab")) {
11503: while (my $configline=<$config>) {
11504: chomp($configline);
11505: my ($hostid,$loncaparev)=split(/:/,$configline);
11506: $loncaparevs{$hostid}=$loncaparev;
11507: }
11508: close($config);
11509: }
11510: }
11511: }
11512:
1.1074 raeburn 11513: # ---------------------------------------------------------- Read serverhostID table
11514: {
11515: if (-e "$perlvar{'lonTabDir'}/serverhomeIDs.tab") {
11516: if (open(my $config,"<$perlvar{'lonTabDir'}/serverhomeIDs.tab")) {
11517: while (my $configline=<$config>) {
11518: chomp($configline);
11519: my ($name,$id)=split(/:/,$configline);
11520: $serverhomeIDs{$name}=$id;
11521: }
11522: close($config);
11523: }
11524: }
11525: }
11526:
1.1079 raeburn 11527: {
11528: my $file = $Apache::lonnet::perlvar{'lonTabDir'}.'/releaseslist.xml';
11529: if (-e $file) {
11530: my $parser = HTML::LCParser->new($file);
11531: while (my $token = $parser->get_token()) {
11532: if ($token->[0] eq 'S') {
11533: my $item = $token->[1];
11534: my $name = $token->[2]{'name'};
11535: my $value = $token->[2]{'value'};
11536: if ($item ne '' && $name ne '' && $value ne '') {
11537: my $release = $parser->get_text();
11538: $release =~ s/(^\s*|\s*$ )//gx;
11539: $needsrelease{$item.':'.$name.':'.$value} = $release;
11540: }
11541: }
11542: }
11543: }
1.1073 raeburn 11544: }
11545:
1.1138 raeburn 11546: # ---------------------------------------------------------- Read managers table
11547: {
11548: if (-e "$perlvar{'lonTabDir'}/managers.tab") {
11549: if (open(my $config,"<$perlvar{'lonTabDir'}/managers.tab")) {
11550: while (my $configline=<$config>) {
11551: chomp($configline);
11552: next if ($configline =~ /^\#/);
11553: if (($configline =~ /^[\w\-]+$/) || ($configline =~ /^[\w\-]+\:[\w\-]+$/)) {
11554: $managerstab{$configline} = 1;
11555: }
11556: }
11557: close($config);
11558: }
11559: }
11560: }
11561:
1.329 matthew 11562: # ------------- set up temporary directory
11563: {
1.1117 foxr 11564: $tmpdir = LONCAPA::tempdir();
1.329 matthew 11565:
1.11 www 11566: }
11567:
1.794 albertel 11568: $memcache=new Cache::Memcached({'servers' => ['127.0.0.1:11211'],
11569: 'compress_threshold'=> 20_000,
11570: });
1.185 www 11571:
1.281 www 11572: $processmarker='_'.time.'_'.$perlvar{'lonHostID'};
1.186 www 11573: $dumpcount=0;
1.958 www 11574: $locknum=0;
1.22 www 11575:
1.163 harris41 11576: &logtouch();
1.672 albertel 11577: &logthis('<font color="yellow">INFO: Read configuration</font>');
1.195 www 11578: $readit=1;
1.564 albertel 11579: {
11580: use integer;
11581: my $test=(2**32)+1;
1.568 albertel 11582: if ($test != 0) { $_64bit=1; } else { $_64bit=0; }
1.564 albertel 11583: &logthis(" Detected 64bit platform ($_64bit)");
11584: }
1.195 www 11585: }
1.1 albertel 11586: }
1.179 www 11587:
1.1 albertel 11588: 1;
1.191 harris41 11589: __END__
11590:
1.243 albertel 11591: =pod
11592:
1.191 harris41 11593: =head1 NAME
11594:
1.243 albertel 11595: Apache::lonnet - Subroutines to ask questions about things in the network.
1.191 harris41 11596:
11597: =head1 SYNOPSIS
11598:
1.243 albertel 11599: Invoked by other LON-CAPA modules, when they need to talk to or about objects in the network.
1.191 harris41 11600:
11601: &Apache::lonnet::SUBROUTINENAME(ARGUMENTS);
11602:
1.243 albertel 11603: Common parameters:
11604:
11605: =over 4
11606:
11607: =item *
11608:
11609: $uname : an internal username (if $cname expecting a course Id specifically)
11610:
11611: =item *
11612:
11613: $udom : a domain (if $cdom expecting a course's domain specifically)
11614:
11615: =item *
11616:
11617: $symb : a resource instance identifier
11618:
11619: =item *
11620:
11621: $namespace : the name of a .db file that contains the data needed or
11622: being set.
11623:
11624: =back
11625:
1.394 bowersj2 11626: =head1 OVERVIEW
1.191 harris41 11627:
1.394 bowersj2 11628: lonnet provides subroutines which interact with the
11629: lonc/lond (TCP) network layer of LON-CAPA. They can be used to ask
11630: about classes, users, and resources.
1.243 albertel 11631:
11632: For many of these objects you can also use this to store data about
11633: them or modify them in various ways.
1.191 harris41 11634:
1.394 bowersj2 11635: =head2 Symbs
1.191 harris41 11636:
1.394 bowersj2 11637: To identify a specific instance of a resource, LON-CAPA uses symbols
11638: or "symbs"X<symb>. These identifiers are built from the URL of the
11639: map, the resource number of the resource in the map, and the URL of
11640: the resource itself. The latter is somewhat redundant, but might help
11641: if maps change.
11642:
11643: An example is
11644:
11645: msu/korte/parts/part1.sequence___19___msu/korte/tests/part12.problem
11646:
11647: The respective map entry is
11648:
11649: <resource id="19" src="/res/msu/korte/tests/part12.problem"
11650: title="Problem 2">
11651: </resource>
11652:
11653: Symbs are used by the random number generator, as well as to store and
11654: restore data specific to a certain instance of for example a problem.
11655:
11656: =head2 Storing And Retrieving Data
11657:
11658: X<store()>X<cstore()>X<restore()>Three of the most important functions
11659: in C<lonnet.pm> are C<&Apache::lonnet::cstore()>,
11660: C<&Apache::lonnet:restore()>, and C<&Apache::lonnet::store()>, which
11661: is is the non-critical message twin of cstore. These functions are for
11662: handlers to store a perl hash to a user's permanent data space in an
11663: easy manner, and to retrieve it again on another call. It is expected
11664: that a handler would use this once at the beginning to retrieve data,
11665: and then again once at the end to send only the new data back.
11666:
11667: The data is stored in the user's data directory on the user's
11668: homeserver under the ID of the course.
11669:
11670: The hash that is returned by restore will have all of the previous
11671: value for all of the elements of the hash.
11672:
11673: Example:
11674:
11675: #creating a hash
11676: my %hash;
11677: $hash{'foo'}='bar';
11678:
11679: #storing it
11680: &Apache::lonnet::cstore(\%hash);
11681:
11682: #changing a value
11683: $hash{'foo'}='notbar';
11684:
11685: #adding a new value
11686: $hash{'bar'}='foo';
11687: &Apache::lonnet::cstore(\%hash);
11688:
11689: #retrieving the hash
11690: my %history=&Apache::lonnet::restore();
11691:
11692: #print the hash
11693: foreach my $key (sort(keys(%history))) {
11694: print("\%history{$key} = $history{$key}");
11695: }
11696:
11697: Will print out:
1.191 harris41 11698:
1.394 bowersj2 11699: %history{1:foo} = bar
11700: %history{1:keys} = foo:timestamp
11701: %history{1:timestamp} = 990455579
11702: %history{2:bar} = foo
11703: %history{2:foo} = notbar
11704: %history{2:keys} = foo:bar:timestamp
11705: %history{2:timestamp} = 990455580
11706: %history{bar} = foo
11707: %history{foo} = notbar
11708: %history{timestamp} = 990455580
11709: %history{version} = 2
11710:
11711: Note that the special hash entries C<keys>, C<version> and
11712: C<timestamp> were added to the hash. C<version> will be equal to the
11713: total number of versions of the data that have been stored. The
11714: C<timestamp> attribute will be the UNIX time the hash was
11715: stored. C<keys> is available in every historical section to list which
11716: keys were added or changed at a specific historical revision of a
11717: hash.
11718:
11719: B<Warning>: do not store the hash that restore returns directly. This
11720: will cause a mess since it will restore the historical keys as if the
11721: were new keys. I.E. 1:foo will become 1:1:foo etc.
1.191 harris41 11722:
1.394 bowersj2 11723: Calling convention:
1.191 harris41 11724:
1.394 bowersj2 11725: my %record=&Apache::lonnet::restore($symb,$courseid,$domain,$uname,$home);
11726: &Apache::lonnet::cstore(\%newrecord,$symb,$courseid,$domain,$uname,$home);
1.191 harris41 11727:
1.394 bowersj2 11728: For more detailed information, see lonnet specific documentation.
1.191 harris41 11729:
1.394 bowersj2 11730: =head1 RETURN MESSAGES
1.191 harris41 11731:
1.394 bowersj2 11732: =over 4
1.191 harris41 11733:
1.394 bowersj2 11734: =item * B<con_lost>: unable to contact remote host
1.191 harris41 11735:
1.394 bowersj2 11736: =item * B<con_delayed>: unable to contact remote host, message will be delivered
11737: when the connection is brought back up
1.191 harris41 11738:
1.394 bowersj2 11739: =item * B<con_failed>: unable to contact remote host and unable to save message
11740: for later delivery
1.191 harris41 11741:
1.967 bisitz 11742: =item * B<error:>: an error a occurred, a description of the error follows the :
1.191 harris41 11743:
1.394 bowersj2 11744: =item * B<no_such_host>: unable to fund a host associated with the user/domain
1.243 albertel 11745: that was requested
1.191 harris41 11746:
1.243 albertel 11747: =back
1.191 harris41 11748:
1.243 albertel 11749: =head1 PUBLIC SUBROUTINES
1.191 harris41 11750:
1.243 albertel 11751: =head2 Session Environment Functions
1.191 harris41 11752:
1.243 albertel 11753: =over 4
1.191 harris41 11754:
1.394 bowersj2 11755: =item *
11756: X<appenv()>
1.949 raeburn 11757: B<appenv($hashref,$rolesarrayref)>: the value of %{$hashref} is written to
1.394 bowersj2 11758: the user envirnoment file, and will be restored for each access this
1.620 albertel 11759: user makes during this session, also modifies the %env for the current
1.949 raeburn 11760: process. Optional rolesarrayref - if defined contains a reference to an array
11761: of roles which are exempt from the restriction on modifying user.role entries
11762: in the user's environment.db and in %env.
1.191 harris41 11763:
11764: =item *
1.394 bowersj2 11765: X<delenv()>
1.987 raeburn 11766: B<delenv($delthis,$regexp)>: removes all items from the session
11767: environment file that begin with $delthis. If the
11768: optional second arg - $regexp - is true, $delthis is treated as a
11769: regular expression, otherwise \Q$delthis\E is used.
11770: The values are also deleted from the current processes %env.
1.191 harris41 11771:
1.795 albertel 11772: =item * get_env_multiple($name)
11773:
11774: gets $name from the %env hash, it seemlessly handles the cases where multiple
11775: values may be defined and end up as an array ref.
11776:
11777: returns an array of values
11778:
1.243 albertel 11779: =back
11780:
11781: =head2 User Information
1.191 harris41 11782:
1.243 albertel 11783: =over 4
1.191 harris41 11784:
11785: =item *
1.394 bowersj2 11786: X<queryauthenticate()>
11787: B<queryauthenticate($uname,$udom)>: try to determine user's current
1.191 harris41 11788: authentication scheme
11789:
11790: =item *
1.394 bowersj2 11791: X<authenticate()>
1.1073 raeburn 11792: B<authenticate($uname,$upass,$udom,$checkdefauth,$clientcancheckhost)>: try to
1.394 bowersj2 11793: authenticate user from domain's lib servers (first use the current
11794: one). C<$upass> should be the users password.
1.1073 raeburn 11795: $checkdefauth is optional (value is 1 if a check should be made to
11796: authenticate user using default authentication method, and allow
11797: account creation if username does not have account in the domain).
11798: $clientcancheckhost is optional (value is 1 if checking whether the
11799: server can host will occur on the client side in lonauth.pm).
1.191 harris41 11800:
11801: =item *
1.394 bowersj2 11802: X<homeserver()>
11803: B<homeserver($uname,$udom)>: find the server which has
11804: the user's directory and files (there must be only one), this caches
11805: the answer, and also caches if there is a borken connection.
1.191 harris41 11806:
11807: =item *
1.394 bowersj2 11808: X<idget()>
11809: B<idget($udom,@ids)>: find the usernames behind a list of IDs
11810: (IDs are a unique resource in a domain, there must be only 1 ID per
11811: username, and only 1 username per ID in a specific domain) (returns
11812: hash: id=>name,id=>name)
1.191 harris41 11813:
11814: =item *
1.394 bowersj2 11815: X<idrget()>
11816: B<idrget($udom,@unames)>: find the IDs behind a list of
11817: usernames (returns hash: name=>id,name=>id)
1.191 harris41 11818:
11819: =item *
1.394 bowersj2 11820: X<idput()>
11821: B<idput($udom,%ids)>: store away a list of names and associated IDs
1.191 harris41 11822:
11823: =item *
1.394 bowersj2 11824: X<rolesinit()>
1.1169 droeschl 11825: B<rolesinit($udom,$username)>: get user privileges.
11826: returns user role, first access and timer interval hashes
1.243 albertel 11827:
11828: =item *
1.1171 droeschl 11829: X<privileged()>
11830: B<privileged($username,$domain)>: returns a true if user has a
11831: privileged and active role (i.e. su or dc), false otherwise.
11832:
11833: =item *
1.551 albertel 11834: X<getsection()>
11835: B<getsection($udom,$uname,$cname)>: finds the section of student in the
1.243 albertel 11836: course $cname, return section name/number or '' for "not in course"
11837: and '-1' for "no section"
11838:
11839: =item *
1.394 bowersj2 11840: X<userenvironment()>
11841: B<userenvironment($udom,$uname,@what)>: gets the values of the keys
1.243 albertel 11842: passed in @what from the requested user's environment, returns a hash
11843:
1.858 raeburn 11844: =item *
11845: X<userlog_query()>
1.859 albertel 11846: B<userlog_query($uname,$udom,%filters)>: retrieves data from a user's
11847: activity.log file. %filters defines filters applied when parsing the
11848: log file. These can be start or end timestamps, or the type of action
11849: - log to look for Login or Logout events, check for Checkin or
11850: Checkout, role for role selection. The response is in the form
11851: timestamp1:hostid1:event1×tamp2:hostid2:event2 where events are
11852: escaped strings of the action recorded in the activity.log file.
1.858 raeburn 11853:
1.243 albertel 11854: =back
11855:
11856: =head2 User Roles
11857:
11858: =over 4
11859:
11860: =item *
11861:
1.810 raeburn 11862: allowed($priv,$uri,$symb,$role) : check for a user privilege; returns codes for allowed actions
1.243 albertel 11863: F: full access
11864: U,I,K: authentication modes (cxx only)
11865: '': forbidden
11866: 1: user needs to choose course
11867: 2: browse allowed
1.766 albertel 11868: A: passphrase authentication needed
1.243 albertel 11869:
11870: =item *
11871:
11872: definerole($rolename,$sysrole,$domrole,$courole) : define role; define a custom
11873: role rolename set privileges in format of lonTabs/roles.tab for system, domain,
11874: and course level
11875:
11876: =item *
11877:
1.988 raeburn 11878: plaintext($short,$type,$cid,$forcedefault) : return value in %prp hash
11879: (rolesplain.tab); plain text explanation of a user role term.
1.1008 raeburn 11880: $type is Course (default) or Community.
1.988 raeburn 11881: If $forcedefault evaluates to true, text returned will be default
11882: text for $type. Otherwise, if this is a course, the text returned
11883: will be a custom name for the role (if defined in the course's
11884: environment). If no custom name is defined the default is returned.
11885:
1.832 raeburn 11886: =item *
11887:
1.935 raeburn 11888: get_my_roles($uname,$udom,$context,$types,$roles,$roledoms,$withsec) :
1.858 raeburn 11889: All arguments are optional. Returns a hash of a roles, either for
11890: co-author/assistant author roles for a user's Construction Space
1.906 albertel 11891: (default), or if $context is 'userroles', roles for the user himself,
1.933 raeburn 11892: In the hash, keys are set to colon-separated $uname,$udom,$role, and
11893: (optionally) if $withsec is true, a fourth colon-separated item - $section.
11894: For each key, value is set to colon-separated start and end times for
11895: the role. If no username and domain are specified, will default to
1.934 raeburn 11896: current user/domain. Types, roles, and roledoms are references to arrays
1.858 raeburn 11897: of role statuses (active, future or previous), roles
11898: (e.g., cc,in, st etc.) and domains of the roles which can be used
11899: to restrict the list of roles reported. If no array ref is
11900: provided for types, will default to return only active roles.
1.834 albertel 11901:
1.243 albertel 11902: =back
11903:
11904: =head2 User Modification
11905:
11906: =over 4
11907:
11908: =item *
11909:
1.957 raeburn 11910: assignrole($udom,$uname,$url,$role,$end,$start,$deleteflag,$selfenroll,$context) : assign role; give a role to a
1.243 albertel 11911: user for the level given by URL. Optional start and end dates (leave empty
11912: string or zero for "no date")
1.191 harris41 11913:
11914: =item *
11915:
1.243 albertel 11916: changepass($uname,$udom,$currentpass,$newpass,$server) : attempts to
11917: change a users, password, possible return values are: ok,
11918: pwchange_failure, non_authorized, auth_mode_error, unknown_user,
11919: refused
1.191 harris41 11920:
11921: =item *
11922:
1.243 albertel 11923: modifyuserauth($udom,$uname,$umode,$upass) : modify user authentication
1.191 harris41 11924:
11925: =item *
11926:
1.1058 raeburn 11927: modifyuser($udom,$uname,$uid,$umode,$upass,$first,$middle,$last, $gene,
11928: $forceid,$desiredhome,$email,$inststatus,$candelete) :
11929:
11930: will update user information (firstname,middlename,lastname,generation,
11931: permanentemail), and if forceid is true, student/employee ID also.
11932: A user's institutional affiliation(s) can also be updated.
11933: User information fields will not be overwritten with empty entries
11934: unless the field is included in the $candelete array reference.
11935: This array is included when a single user is modified via "Manage Users",
11936: or when Autoupdate.pl is run by cron in a domain.
1.191 harris41 11937:
11938: =item *
11939:
1.286 matthew 11940: modifystudent
11941:
1.957 raeburn 11942: modify a student's enrollment and identification information.
1.286 matthew 11943: The course id is resolved based on the current users environment.
11944: This means the envoking user must be a course coordinator or otherwise
11945: associated with a course.
11946:
1.297 matthew 11947: This call is essentially a wrapper for lonnet::modifyuser and
11948: lonnet::modify_student_enrollment
1.286 matthew 11949:
11950: Inputs:
11951:
11952: =over 4
11953:
1.957 raeburn 11954: =item B<$udom> Student's loncapa domain
1.286 matthew 11955:
1.957 raeburn 11956: =item B<$uname> Student's loncapa login name
1.286 matthew 11957:
1.964 bisitz 11958: =item B<$uid> Student/Employee ID
1.286 matthew 11959:
1.957 raeburn 11960: =item B<$umode> Student's authentication mode
1.286 matthew 11961:
1.957 raeburn 11962: =item B<$upass> Student's password
1.286 matthew 11963:
1.957 raeburn 11964: =item B<$first> Student's first name
1.286 matthew 11965:
1.957 raeburn 11966: =item B<$middle> Student's middle name
1.286 matthew 11967:
1.957 raeburn 11968: =item B<$last> Student's last name
1.286 matthew 11969:
1.957 raeburn 11970: =item B<$gene> Student's generation
1.286 matthew 11971:
1.957 raeburn 11972: =item B<$usec> Student's section in course
1.286 matthew 11973:
11974: =item B<$end> Unix time of the roles expiration
11975:
11976: =item B<$start> Unix time of the roles start date
11977:
11978: =item B<$forceid> If defined, allow $uid to be changed
11979:
11980: =item B<$desiredhome> server to use as home server for student
11981:
1.957 raeburn 11982: =item B<$email> Student's permanent e-mail address
11983:
11984: =item B<$type> Type of enrollment (auto or manual)
11985:
1.963 raeburn 11986: =item B<$locktype> boolean - enrollment type locked to prevent Autoenroll.pl changing manual to auto
11987:
11988: =item B<$cid> courseID - needed if a course role is assigned by a user whose current role is DC
1.957 raeburn 11989:
1.963 raeburn 11990: =item B<$selfenroll> boolean - 1 if user role change occurred via self-enrollment
1.957 raeburn 11991:
1.963 raeburn 11992: =item B<$context> role change context (shown in User Management Logs display in a course)
1.957 raeburn 11993:
1.963 raeburn 11994: =item B<$inststatus> institutional status of user - : separated string of escaped status types
1.957 raeburn 11995:
1.286 matthew 11996: =back
1.297 matthew 11997:
11998: =item *
11999:
12000: modify_student_enrollment
12001:
12002: Change a students enrollment status in a class. The environment variable
12003: 'role.request.course' must be defined for this function to proceed.
12004:
12005: Inputs:
12006:
12007: =over 4
12008:
12009: =item $udom, students domain
12010:
12011: =item $uname, students name
12012:
12013: =item $uid, students user id
12014:
12015: =item $first, students first name
12016:
12017: =item $middle
12018:
12019: =item $last
12020:
12021: =item $gene
12022:
12023: =item $usec
12024:
12025: =item $end
12026:
12027: =item $start
12028:
1.957 raeburn 12029: =item $type
12030:
12031: =item $locktype
12032:
12033: =item $cid
12034:
12035: =item $selfenroll
12036:
12037: =item $context
12038:
1.297 matthew 12039: =back
12040:
1.191 harris41 12041:
12042: =item *
12043:
1.243 albertel 12044: assigncustomrole($udom,$uname,$url,$rdom,$rnam,$rolename,$end,$start) : assign
12045: custom role; give a custom role to a user for the level given by URL. Specify
12046: name and domain of role author, and role name
1.191 harris41 12047:
12048: =item *
12049:
1.243 albertel 12050: revokerole($udom,$uname,$url,$role) : revoke a role for url
1.191 harris41 12051:
12052: =item *
12053:
1.243 albertel 12054: revokecustomrole($udom,$uname,$url,$role) : revoke a custom role
12055:
12056: =back
12057:
12058: =head2 Course Infomation
12059:
12060: =over 4
1.191 harris41 12061:
12062: =item *
12063:
1.1118 foxr 12064: coursedescription($courseid,$options) : returns a hash of information about the
1.631 albertel 12065: specified course id, including all environment settings for the
12066: course, the description of the course will be in the hash under the
12067: key 'description'
1.191 harris41 12068:
1.1118 foxr 12069: $options is an optional parameter that if supplied is a hash reference that controls
12070: what how this function works. It has the following key/values:
12071:
12072: =over 4
12073:
12074: =item freshen_cache
12075:
12076: If defined, and the environment cache for the course is valid, it is
12077: returned in the returned hash.
12078:
12079: =item one_time
12080:
12081: If defined, the last cache time is set to _now_
12082:
12083: =item user
12084:
12085: If defined, the supplied username is used instead of the current user.
12086:
12087:
12088: =back
12089:
1.191 harris41 12090: =item *
12091:
1.624 albertel 12092: resdata($name,$domain,$type,@which) : request for current parameter
12093: setting for a specific $type, where $type is either 'course' or 'user',
12094: @what should be a list of parameters to ask about. This routine caches
12095: answers for 5 minutes.
1.243 albertel 12096:
1.877 foxr 12097: =item *
12098:
12099: get_courseresdata($courseid, $domain) : dump the entire course resource
12100: data base, returning a hash that is keyed by the resource name and has
12101: values that are the resource value. I believe that the timestamps and
12102: versions are also returned.
12103:
12104:
1.243 albertel 12105: =back
12106:
12107: =head2 Course Modification
12108:
12109: =over 4
1.191 harris41 12110:
12111: =item *
12112:
1.243 albertel 12113: writecoursepref($courseid,%prefs) : write preferences (environment
12114: database) for a course
1.191 harris41 12115:
12116: =item *
12117:
1.1011 raeburn 12118: createcourse($udom,$description,$url,$course_server,$nonstandard,$inst_code,$course_owner,$crstype,$cnum) : make course
12119:
12120: =item *
12121:
1.1038 raeburn 12122: generate_coursenum($udom,$crstype) : get a unique (unused) course number in domain $udom for course type $crstype (Course or Community).
1.243 albertel 12123:
1.1167 droeschl 12124: =item *
12125:
12126: is_course($courseid), is_course($cdom, $cnum)
12127:
12128: Accepts either a combined $courseid (in the form of domain_courseid) or the
12129: two component version $cdom, $cnum. It checks if the specified course exists.
12130:
12131: Returns:
12132: undef if the course doesn't exist, otherwise
12133: in scalar context the combined courseid.
12134: in list context the two components of the course identifier, domain and
12135: courseid.
12136:
1.243 albertel 12137: =back
12138:
12139: =head2 Resource Subroutines
12140:
12141: =over 4
1.191 harris41 12142:
12143: =item *
12144:
1.243 albertel 12145: subscribe($fname) : subscribe to a resource, returns URL if possible (probably should use repcopy instead)
1.191 harris41 12146:
12147: =item *
12148:
1.243 albertel 12149: repcopy($filename) : subscribes to the requested file, and attempts to
12150: replicate from the owning library server, Might return
1.607 raeburn 12151: 'unavailable', 'not_found', 'forbidden', 'ok', or
12152: 'bad_request', also attempts to grab the metadata for the
1.243 albertel 12153: resource. Expects the local filesystem pathname
12154: (/home/httpd/html/res/....)
12155:
12156: =back
12157:
12158: =head2 Resource Information
12159:
12160: =over 4
1.191 harris41 12161:
12162: =item *
12163:
1.243 albertel 12164: EXT($varname,$symb,$udom,$uname) : evaluates and returns the value of
12165: a vairety of different possible values, $varname should be a request
12166: string, and the other parameters can be used to specify who and what
12167: one is asking about.
12168:
12169: Possible values for $varname are environment.lastname (or other item
12170: from the envirnment hash), user.name (or someother aspect about the
12171: user), resource.0.maxtries (or some other part and parameter of a
12172: resource)
1.204 albertel 12173:
12174: =item *
12175:
1.243 albertel 12176: directcondval($number) : get current value of a condition; reads from a state
12177: string
1.204 albertel 12178:
12179: =item *
12180:
1.243 albertel 12181: condval($condidx) : value of condition index based on state
1.204 albertel 12182:
12183: =item *
12184:
1.243 albertel 12185: metadata($uri,$what,$liburi,$prefix,$depthcount) : request a
12186: resource's metadata, $what should be either a specific key, or either
12187: 'keys' (to get a list of possible keys) or 'packages' to get a list of
12188: packages that this resource currently uses, the last 3 arguments are only used internally for recursive metadata.
12189:
12190: this function automatically caches all requests
1.191 harris41 12191:
12192: =item *
12193:
1.243 albertel 12194: metadata_query($query,$custom,$customshow) : make a metadata query against the
12195: network of library servers; returns file handle of where SQL and regex results
12196: will be stored for query
1.191 harris41 12197:
12198: =item *
12199:
1.243 albertel 12200: symbread($filename) : return symbolic list entry (filename argument optional);
12201: returns the data handle
1.191 harris41 12202:
12203: =item *
12204:
1.243 albertel 12205: symbverify($symb,$thisfn) : verifies that $symb actually exists and is
1.582 albertel 12206: a possible symb for the URL in $thisfn, and if is an encryypted
12207: resource that the user accessed using /enc/ returns a 1 on success, 0
12208: on failure, user must be in a course, as it assumes the existance of
1.620 albertel 12209: the course initial hash, and uses $env('request.course.id'}
1.243 albertel 12210:
1.191 harris41 12211:
12212: =item *
12213:
1.243 albertel 12214: symbclean($symb) : removes versions numbers from a symb, returns the
12215: cleaned symb
1.191 harris41 12216:
12217: =item *
12218:
1.243 albertel 12219: is_on_map($uri) : checks if the $uri is somewhere on the current
12220: course map, user must be in a course for it to work.
1.191 harris41 12221:
12222: =item *
12223:
1.243 albertel 12224: numval($salt) : return random seed value (addend for rndseed)
1.191 harris41 12225:
12226: =item *
12227:
1.243 albertel 12228: rndseed($symb,$courseid,$udom,$uname) : create a random sum; returns
12229: a random seed, all arguments are optional, if they aren't sent it uses the
12230: environment to derive them. Note: if symb isn't sent and it can't get one
12231: from &symbread it will use the current time as its return value
1.191 harris41 12232:
12233: =item *
12234:
1.243 albertel 12235: ireceipt($funame,$fudom,$fucourseid,$fusymb) : return unique,
12236: unfakeable, receipt
1.191 harris41 12237:
12238: =item *
12239:
1.620 albertel 12240: receipt() : API to ireceipt working off of env values; given out to users
1.191 harris41 12241:
12242: =item *
12243:
1.243 albertel 12244: countacc($url) : count the number of accesses to a given URL
1.191 harris41 12245:
12246: =item *
12247:
1.243 albertel 12248: 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 12249:
12250: =item *
12251:
1.243 albertel 12252: 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 12253:
12254: =item *
12255:
1.243 albertel 12256: expirespread($uname,$udom,$stype,$usymb) : set expire date for spreadsheet
1.191 harris41 12257:
12258: =item *
12259:
1.243 albertel 12260: devalidate($symb) : devalidate temporary spreadsheet calculations,
12261: forcing spreadsheet to reevaluate the resource scores next time.
12262:
12263: =back
12264:
12265: =head2 Storing/Retreiving Data
12266:
12267: =over 4
1.191 harris41 12268:
12269: =item *
12270:
1.243 albertel 12271: store($storehash,$symb,$namespace,$udom,$uname) : stores hash permanently
12272: for this url; hashref needs to be given and should be a \%hashname; the
12273: remaining args aren't required and if they aren't passed or are '' they will
1.620 albertel 12274: be derived from the env
1.191 harris41 12275:
12276: =item *
12277:
1.243 albertel 12278: cstore($storehash,$symb,$namespace,$udom,$uname) : same as store but
12279: uses critical subroutine
1.191 harris41 12280:
12281: =item *
12282:
1.243 albertel 12283: restore($symb,$namespace,$udom,$uname) : returns hash for this symb;
12284: all args are optional
1.191 harris41 12285:
12286: =item *
12287:
1.717 albertel 12288: dumpstore($namespace,$udom,$uname,$regexp,$range) :
12289: dumps the complete (or key matching regexp) namespace into a hash
12290: ($udom, $uname, $regexp, $range are optional) for a namespace that is
12291: normally &store()ed into
12292:
12293: $range should be either an integer '100' (give me the first 100
12294: matching records)
12295: or be two integers sperated by a - with no spaces
12296: '30-50' (give me the 30th through the 50th matching
12297: records)
12298:
12299:
12300: =item *
12301:
12302: putstore($namespace,$symb,$version,$storehash,$udomain,$uname) :
12303: replaces a &store() version of data with a replacement set of data
12304: for a particular resource in a namespace passed in the $storehash hash
12305: reference
12306:
12307: =item *
12308:
1.243 albertel 12309: tmpstore($storehash,$symb,$namespace,$udom,$uname) : storage that
12310: works very similar to store/cstore, but all data is stored in a
12311: temporary location and can be reset using tmpreset, $storehash should
12312: be a hash reference, returns nothing on success
1.191 harris41 12313:
12314: =item *
12315:
1.243 albertel 12316: tmprestore($symb,$namespace,$udom,$uname) : storage that works very
12317: similar to restore, but all data is stored in a temporary location and
12318: can be reset using tmpreset. Returns a hash of values on success,
12319: error string otherwise.
1.191 harris41 12320:
12321: =item *
12322:
1.243 albertel 12323: tmpreset($symb,$namespace,$udom,$uname) : temporary storage reset,
12324: deltes all keys for $symb form the temporary storage hash.
1.191 harris41 12325:
12326: =item *
12327:
1.243 albertel 12328: get($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12329: reference filled in from namesp ($udom and $uname are optional)
1.191 harris41 12330:
12331: =item *
12332:
1.243 albertel 12333: del($namespace,$storearr,$udom,$uname) : deletes keys out of array from
12334: namesp ($udom and $uname are optional)
1.191 harris41 12335:
12336: =item *
12337:
1.702 albertel 12338: dump($namespace,$udom,$uname,$regexp,$range) :
1.243 albertel 12339: dumps the complete (or key matching regexp) namespace into a hash
1.702 albertel 12340: ($udom, $uname, $regexp, $range are optional)
1.449 matthew 12341:
1.702 albertel 12342: $range should be either an integer '100' (give me the first 100
12343: matching records)
12344: or be two integers sperated by a - with no spaces
12345: '30-50' (give me the 30th through the 50th matching
12346: records)
1.449 matthew 12347: =item *
12348:
12349: inc($namespace,$store,$udom,$uname) : increments $store in $namespace.
12350: $store can be a scalar, an array reference, or if the amount to be
12351: incremented is > 1, a hash reference.
12352:
12353: ($udom and $uname are optional)
1.191 harris41 12354:
12355: =item *
12356:
1.243 albertel 12357: put($namespace,$storehash,$udom,$uname) : stores hash in namesp
12358: ($udom and $uname are optional)
1.191 harris41 12359:
12360: =item *
12361:
1.243 albertel 12362: cput($namespace,$storehash,$udom,$uname) : critical put
12363: ($udom and $uname are optional)
1.191 harris41 12364:
12365: =item *
12366:
1.748 albertel 12367: newput($namespace,$storehash,$udom,$uname) :
12368:
12369: Attempts to store the items in the $storehash, but only if they don't
12370: currently exist, if this succeeds you can be certain that you have
12371: successfully created a new key value pair in the $namespace db.
12372:
12373:
12374: Args:
12375: $namespace: name of database to store values to
12376: $storehash: hashref to store to the db
12377: $udom: (optional) domain of user containing the db
12378: $uname: (optional) name of user caontaining the db
12379:
12380: Returns:
12381: 'ok' -> succeeded in storing all keys of $storehash
12382: 'key_exists: <key>' -> failed to anything out of $storehash, as at
12383: least <key> already existed in the db (other
12384: requested keys may also already exist)
1.967 bisitz 12385: 'error: <msg>' -> unable to tie the DB or other error occurred
1.748 albertel 12386: 'con_lost' -> unable to contact request server
12387: 'refused' -> action was not allowed by remote machine
12388:
12389:
12390: =item *
12391:
1.243 albertel 12392: eget($namespace,$storearr,$udom,$uname) : returns hash with keys from array
12393: reference filled in from namesp (encrypts the return communication)
12394: ($udom and $uname are optional)
1.191 harris41 12395:
12396: =item *
12397:
1.243 albertel 12398: log($udom,$name,$home,$message) : write to permanent log for user; use
12399: critical subroutine
12400:
1.806 raeburn 12401: =item *
12402:
1.860 raeburn 12403: get_dom($namespace,$storearr,$udom,$uhome) : returns hash with keys from
12404: array reference filled in from namespace found in domain level on either
12405: specified domain server ($uhome) or primary domain server ($udom and $uhome are optional).
1.806 raeburn 12406:
12407: =item *
12408:
1.860 raeburn 12409: put_dom($namespace,$storehash,$udom,$uhome) : stores hash in namespace at
12410: domain level either on specified domain server ($uhome) or primary domain
12411: server ($udom and $uhome are optional)
1.806 raeburn 12412:
1.943 raeburn 12413: =item *
12414:
12415: get_domain_defaults($target_domain) : returns hash with defaults for
12416: authentication and language in the domain. Keys are: auth_def, auth_arg_def,
12417: lang_def; corresponsing values are authentication type (internal, krb4, krb5,
12418: or localauth), initial password or a kerberos realm, language (e.g., en-us).
12419: Values are retrieved from cache (if current), or from domain's configuration.db
12420: (if available), or lastly from values in lonTabs/dns_domain,tab,
12421: or lonTabs/domain.tab.
12422:
12423: %domdefaults = &get_auth_defaults($target_domain);
12424:
1.243 albertel 12425: =back
12426:
12427: =head2 Network Status Functions
12428:
12429: =over 4
1.191 harris41 12430:
12431: =item *
12432:
1.1137 raeburn 12433: dirlist() : return directory list based on URI (first arg).
12434:
12435: Inputs: 1 required, 5 optional.
12436:
12437: =over
12438:
12439: =item
12440: $uri - path to file in filesystem (starts: /res or /userfiles/). Required.
12441:
12442: =item
12443: $userdomain - domain of user/course to be listed. Extracted from $uri if absent.
12444:
12445: =item
12446: $username - username of user/course to be listed. Extracted from $uri if absent.
12447:
12448: =item
12449: $getpropath - boolean: 1 if prepend path using &propath().
12450:
12451: =item
12452: $getuserdir - boolean: 1 if prepend path for "userfiles".
12453:
12454: =item
12455: $alternateRoot - path to prepend in place of path from $uri.
12456:
12457: =back
12458:
12459: Returns: Array of up to two items.
12460:
12461: =over
12462:
12463: a reference to an array of files/subdirectories
12464:
12465: =over
12466:
12467: Each element in the array of files/subdirectories is a & separated list of
12468: item name and the result of running stat on the item. If dirlist was requested
12469: for a file instead of a directory, the item name will be ''. For a directory
12470: listing, if the item is a metadata file, the element will end &N&M
12471: (where N amd M are either 0 or 1, corresponding to obsolete set (1), or
12472: default copyright set (1).
12473:
12474: =back
12475:
12476: a scalar containing error condition (if encountered).
12477:
12478: =over
12479:
12480: =item
12481: no_host (no homeserver identified for $username:$domain).
12482:
12483: =item
12484: no_such_host (server contacted for listing not identified as valid host).
12485:
12486: =item
12487: con_lost (connection to remote server failed).
12488:
12489: =item
12490: refused (invalid $username:$domain received on lond side).
12491:
12492: =item
12493: no_such_dir (directory at specified path on lond side does not exist).
12494:
12495: =item
12496: empty (directory at specified path on lond side is empty).
12497:
12498: =over
12499:
12500: This is currently not encountered because the &ls3, &ls2,
12501: &ls (_handler) routines on the lond side do not filter out
12502: . and .. from a directory listing.
12503:
12504: =back
12505:
12506: =back
12507:
12508: =back
1.191 harris41 12509:
12510: =item *
12511:
1.243 albertel 12512: spareserver() : find server with least workload from spare.tab
12513:
1.986 foxr 12514:
12515: =item *
12516:
12517: host_from_dns($dns) : Returns the loncapa hostname corresponding to a DNS name or undef
12518: if there is no corresponding loncapa host.
12519:
1.243 albertel 12520: =back
12521:
1.986 foxr 12522:
1.243 albertel 12523: =head2 Apache Request
12524:
12525: =over 4
1.191 harris41 12526:
12527: =item *
12528:
1.243 albertel 12529: ssi($url,%hash) : server side include, does a complete request cycle on url to
12530: localhost, posts hash
12531:
12532: =back
12533:
12534: =head2 Data to String to Data
12535:
12536: =over 4
1.191 harris41 12537:
12538: =item *
12539:
1.243 albertel 12540: hash2str(%hash) : convert a hash into a string complete with escaping and '='
12541: and '&' separators, supports elements that are arrayrefs and hashrefs
1.191 harris41 12542:
12543: =item *
12544:
1.243 albertel 12545: hashref2str($hashref) : convert a hashref into a string complete with
12546: escaping and '=' and '&' separators, supports elements that are
12547: arrayrefs and hashrefs
1.191 harris41 12548:
12549: =item *
12550:
1.243 albertel 12551: arrayref2str($arrayref) : convert an arrayref into a string complete
12552: with escaping and '&' separators, supports elements that are arrayrefs
12553: and hashrefs
1.191 harris41 12554:
12555: =item *
12556:
1.243 albertel 12557: str2hash($string) : convert string to hash using unescaping and
12558: splitting on '=' and '&', supports elements that are arrayrefs and
12559: hashrefs
1.191 harris41 12560:
12561: =item *
12562:
1.243 albertel 12563: str2array($string) : convert string to hash using unescaping and
12564: splitting on '&', supports elements that are arrayrefs and hashrefs
12565:
12566: =back
12567:
12568: =head2 Logging Routines
12569:
12570:
12571: These routines allow one to make log messages in the lonnet.log and
12572: lonnet.perm logfiles.
1.191 harris41 12573:
1.1119 foxr 12574: =over 4
12575:
1.191 harris41 12576: =item *
12577:
1.243 albertel 12578: logtouch() : make sure the logfile, lonnet.log, exists
1.191 harris41 12579:
12580: =item *
12581:
1.243 albertel 12582: logthis() : append message to the normal lonnet.log file, it gets
12583: preiodically rolled over and deleted.
1.191 harris41 12584:
12585: =item *
12586:
1.243 albertel 12587: logperm() : append a permanent message to lonnet.perm.log, this log
12588: file never gets deleted by any automated portion of the system, only
12589: messages of critical importance should go in here.
12590:
1.1119 foxr 12591:
1.243 albertel 12592: =back
12593:
12594: =head2 General File Helper Routines
12595:
12596: =over 4
1.191 harris41 12597:
12598: =item *
12599:
1.481 raeburn 12600: getfile($file,$caller) : two cases - requests for files in /res or in /uploaded.
12601: (a) files in /uploaded
12602: (i) If a local copy of the file exists -
12603: compares modification date of local copy with last-modified date for
12604: definitive version stored on home server for course. If local copy is
12605: stale, requests a new version from the home server and stores it.
12606: If the original has been removed from the home server, then local copy
12607: is unlinked.
12608: (ii) If local copy does not exist -
12609: requests the file from the home server and stores it.
12610:
12611: If $caller is 'uploadrep':
12612: This indicates a call from lonuploadrep.pm (PerlHeaderParserHandler phase)
12613: for request for files originally uploaded via DOCS.
12614: - returns 'ok' if fresh local copy now available, -1 otherwise.
12615:
12616: Otherwise:
12617: This indicates a call from the content generation phase of the request.
12618: - returns the entire contents of the file or -1.
12619:
12620: (b) files in /res
12621: - returns the entire contents of a file or -1;
12622: it properly subscribes to and replicates the file if neccessary.
1.191 harris41 12623:
1.712 albertel 12624:
12625: =item *
12626:
12627: stat_file($url) : $url is expected to be a /res/ or /uploaded/ style file
12628: reference
12629:
12630: returns either a stat() list of data about the file or an empty list
12631: if the file doesn't exist or couldn't find out about it (connection
12632: problems or user unknown)
12633:
1.191 harris41 12634: =item *
12635:
1.243 albertel 12636: filelocation($dir,$file) : returns file system location of a file
12637: based on URI; meant to be "fairly clean" absolute reference, $dir is a
12638: directory that relative $file lookups are to looked in ($dir of /a/dir
12639: and a file of ../bob will become /a/bob)
1.191 harris41 12640:
12641: =item *
12642:
12643: hreflocation($dir,$file) : returns file system location or a URL; same as
12644: filelocation except for hrefs
12645:
12646: =item *
12647:
12648: declutter() : declutters URLs (remove docroot, beginning slashes, 'res' etc)
12649:
1.243 albertel 12650: =back
12651:
1.608 albertel 12652: =head2 Usererfile file routines (/uploaded*)
12653:
12654: =over 4
12655:
12656: =item *
12657:
12658: userfileupload(): main rotine for putting a file in a user or course's
12659: filespace, arguments are,
12660:
1.620 albertel 12661: formname - required - this is the name of the element in $env where the
1.608 albertel 12662: filename, and the contents of the file to create/modifed exist
1.620 albertel 12663: the filename is in $env{'form.'.$formname.'.filename'} and the
12664: contents of the file is located in $env{'form.'.$formname}
1.1090 raeburn 12665: context - if coursedoc, store the file in the course of the active role
12666: of the current user;
12667: if 'existingfile': store in 'overwrites' in /home/httpd/perl/tmp
12668: if 'canceloverwrite': delete file in tmp/overwrites directory
1.608 albertel 12669: subdir - required - subdirectory to put the file in under ../userfiles/
12670: if undefined, it will be placed in "unknown"
12671:
12672: (This routine calls clean_filename() to remove any dangerous
12673: characters from the filename, and then calls finuserfileupload() to
12674: complete the transaction)
12675:
12676: returns either the url of the uploaded file (/uploaded/....) if successful
12677: and /adm/notfound.html if unsuccessful
12678:
12679: =item *
12680:
12681: clean_filename(): routine for cleaing a filename up for storage in
12682: userfile space, argument is:
12683:
12684: filename - proposed filename
12685:
12686: returns: the new clean filename
12687:
12688: =item *
12689:
1.1090 raeburn 12690: finishuserfileupload(): routine that creates and sends the file to
1.608 albertel 12691: userspace, probably shouldn't be called directly
12692:
12693: docuname: username or courseid of destination for the file
12694: docudom: domain of user/course of destination for the file
12695: formname: same as for userfileupload()
1.1090 raeburn 12696: fname: filename (including subdirectories) for the file
12697: parser: if 'parse', will parse (html) file to extract references to objects, links etc.
12698: allfiles: reference to hash used to store objects found by parser
12699: codebase: reference to hash used for codebases of java objects found by parser
12700: thumbwidth: width (pixels) of thumbnail to be created for uploaded image
12701: thumbheight: height (pixels) of thumbnail to be created for uploaded image
12702: resizewidth: width to be used to resize image using resizeImage from ImageMagick
12703: resizeheight: height to be used to resize image using resizeImage from ImageMagick
12704: context: if 'overwrite', will move the uploaded file from its temporary location to
12705: userfiles to facilitate overwriting a previously uploaded file with same name.
1.1095 raeburn 12706: mimetype: reference to scalar to accommodate mime type determined
12707: from File::MMagic if $parser = parse.
1.608 albertel 12708:
12709: returns either the url of the uploaded file (/uploaded/....) if successful
1.1090 raeburn 12710: and /adm/notfound.html if unsuccessful (or an error message if context
12711: was 'overwrite').
12712:
1.608 albertel 12713:
12714: =item *
12715:
12716: renameuserfile(): renames an existing userfile to a new name
12717:
12718: Args:
12719: docuname: username or courseid of destination for the file
12720: docudom: domain of user/course of destination for the file
12721: old: current file name (including any subdirs under userfiles)
12722: new: desired file name (including any subdirs under userfiles)
12723:
12724: =item *
12725:
12726: mkdiruserfile(): creates a directory is a userfiles dir
12727:
12728: Args:
12729: docuname: username or courseid of destination for the file
12730: docudom: domain of user/course of destination for the file
12731: dir: dir to create (including any subdirs under userfiles)
12732:
12733: =item *
12734:
12735: removeuserfile(): removes a file that exists in userfiles
12736:
12737: Args:
12738: docuname: username or courseid of destination for the file
12739: docudom: domain of user/course of destination for the file
12740: fname: filname to delete (including any subdirs under userfiles)
12741:
12742: =item *
12743:
12744: removeuploadedurl(): convience function for removeuserfile()
12745:
12746: Args:
12747: url: a full /uploaded/... url to delete
12748:
1.747 albertel 12749: =item *
12750:
12751: get_portfile_permissions():
12752: Args:
12753: domain: domain of user or course contain the portfolio files
12754: user: name of user or num of course contain the portfolio files
12755: Returns:
12756: hashref of a dump of the proper file_permissions.db
12757:
12758:
12759: =item *
12760:
12761: get_access_controls():
12762:
12763: Args:
12764: current_permissions: the hash ref returned from get_portfile_permissions()
12765: group: (optional) the group you want the files associated with
12766: file: (optional) the file you want access info on
12767:
12768: Returns:
1.749 raeburn 12769: a hash (keys are file names) of hashes containing
12770: keys are: path to file/file_name\0uniqueID:scope_end_start (see below)
12771: values are XML containing access control settings (see below)
1.747 albertel 12772:
12773: Internal notes:
12774:
1.749 raeburn 12775: access controls are stored in file_permissions.db as key=value pairs.
12776: key -> path to file/file_name\0uniqueID:scope_end_start
12777: where scope -> public,guest,course,group,domains or users.
12778: end -> UNIX time for end of access (0 -> no end date)
12779: start -> UNIX time for start of access
12780:
12781: value -> XML description of access control
12782: <scope type=""> (type =1 of: public,guest,course,group,domains,users">
12783: <start></start>
12784: <end></end>
12785:
12786: <password></password> for scope type = guest
12787:
12788: <domain></domain> for scope type = course or group
12789: <number></number>
12790: <roles id="">
12791: <role></role>
12792: <access></access>
12793: <section></section>
12794: <group></group>
12795: </roles>
12796:
12797: <dom></dom> for scope type = domains
12798:
12799: <users> for scope type = users
12800: <user>
12801: <uname></uname>
12802: <udom></udom>
12803: </user>
12804: </users>
12805: </scope>
12806:
12807: Access data is also aggregated for each file in an additional key=value pair:
12808: key -> path to file/file_name\0accesscontrol
12809: value -> reference to hash
12810: hash contains key = value pairs
12811: where key = uniqueID:scope_end_start
12812: value = UNIX time record was last updated
12813:
12814: Used to improve speed of look-ups of access controls for each file.
12815:
12816: Locks on files (resulting from submission of portfolio file to a homework problem stored in array of arrays.
12817:
12818: modify_access_controls():
12819:
12820: Modifies access controls for a portfolio file
12821: Args
12822: 1. file name
12823: 2. reference to hash of required changes,
12824: 3. domain
12825: 4. username
12826: where domain,username are the domain of the portfolio owner
12827: (either a user or a course)
12828:
12829: Returns:
12830: 1. result of additions or updates ('ok' or 'error', with error message).
12831: 2. result of deletions ('ok' or 'error', with error message).
12832: 3. reference to hash of any new or updated access controls.
12833: 4. reference to hash used to map incoming IDs to uniqueIDs assigned to control.
12834: key = integer (inbound ID)
12835: value = uniqueID
1.747 albertel 12836:
1.608 albertel 12837: =back
12838:
1.243 albertel 12839: =head2 HTTP Helper Routines
12840:
12841: =over 4
12842:
1.191 harris41 12843: =item *
12844:
12845: escape() : unpack non-word characters into CGI-compatible hex codes
12846:
12847: =item *
12848:
12849: unescape() : pack CGI-compatible hex codes into actual non-word ASCII character
12850:
1.243 albertel 12851: =back
12852:
12853: =head1 PRIVATE SUBROUTINES
12854:
12855: =head2 Underlying communication routines (Shouldn't call)
12856:
12857: =over 4
12858:
12859: =item *
12860:
12861: subreply() : tries to pass a message to lonc, returns con_lost if incapable
12862:
12863: =item *
12864:
12865: reply() : uses subreply to send a message to remote machine, logs all failures
12866:
12867: =item *
12868:
12869: critical() : passes a critical message to another server; if cannot
12870: get through then place message in connection buffer directory and
12871: returns con_delayed, if incapable of saving message, returns
12872: con_failed
12873:
12874: =item *
12875:
12876: reconlonc() : tries to reconnect lonc client processes.
12877:
12878: =back
12879:
12880: =head2 Resource Access Logging
12881:
12882: =over 4
12883:
12884: =item *
12885:
12886: flushcourselogs() : flush (save) buffer logs and access logs
12887:
12888: =item *
12889:
12890: courselog($what) : save message for course in hash
12891:
12892: =item *
12893:
12894: courseacclog($what) : save message for course using &courselog(). Perform
12895: special processing for specific resource types (problems, exams, quizzes, etc).
12896:
1.191 harris41 12897: =item *
12898:
12899: goodbye() : flush course logs and log shutting down; it is called in srm.conf
12900: as a PerlChildExitHandler
1.243 albertel 12901:
12902: =back
12903:
12904: =head2 Other
12905:
12906: =over 4
12907:
12908: =item *
12909:
12910: symblist($mapname,%newhash) : update symbolic storage links
1.191 harris41 12911:
12912: =back
12913:
12914: =cut
1.877 foxr 12915:
FreeBSD-CVSweb <freebsd-cvsweb@FreeBSD.org>